Angular'控制器为'更新函数内部的属性

Angular 'controller as' updating an attribute inside a function

本文关键字:内部 属性 函数 控制器 Angular 更新      更新时间:2023-09-26

我正在努力学习在我的角度控制器中更频繁地使用controller as,并且在从另一个函数内部更新作用域时遇到了作用域问题:

.controller('profileCtrl', function(ProfileData, Restangular){
  // ProfileData comes from router.resolve
  this.user = ProfileData;
  // I want to update the data with a button click or something
  this.refresh = function(id){
    Restangular.one('users', id).get().then(function(resp){
      this.user = resp;
    })
  }
});

this.user = ProfileData中,this.user = resp实际上并不指代相同的this。我不知道它指的是什么,也许是函数?

我通过注入作用域然后更改我的更新功能来修复这个问题:

  this.refresh = function(id){
    Restangular.one('users', id).get(params).then(function(resp){
      $scope.profile.user = resp;
    })
  }

这种方法的问题在于它取决于我调用控制器myCtrl as profile

有没有一种方法可以在不注入作用域的情况下从我的函数中更新this.user

这将根据执行上下文被覆盖。

相反,您应该将其保存在一个临时变量中,并在闭包中引用它。

.controller('profileCtrl',      function(ProfileData, Restangular){
  // ProfileData comes from router.resolve
  var $this = this;
  $this.user = ProfileData;
  // I want to update the data with a button click or something
  $this.refresh = function(id){
    Restangular.one('users', id).get().then(function(resp){
      $this.user = resp;
    })
  }
});

这样,这总是你所期望的

您总是可以使用函数绑定来帮助您,但它的问题是,您因此无法访问默认this上的任何方法或值。例如,

.controller('profileCtrl', function(ProfileData, Restangular){
  // ProfileData comes from router.resolve
  this.user = ProfileData;
  // I want to update the data with a button click or something
  this.refresh = function(id){
    Restangular.one('users', id).get().then(function(resp){
      this.user = resp;
    }.bind(this)); //The 'this' in the .bind() function is the 'this' of the data outside the function. Weird, I know.
  }
});

不确定这是否能特别解决你的问题,但这是我在处理MooTools时非常熟悉的一种方法。