在 angular 中更新 http 请求回调中的变量

updating variable in http request callback in angular

这可能很简单,但仍然如此。我在我的控制器中有一个 http 调用,我在其中加载了一个 json 文件。我想根据结果更新 html 中的变量。它显然更新了 JS 中的变量 (console.log),但没有更新 html 中的变量。 有没有办法将 $apply 用于结果或类似的?还有什么用? 这是 (not) working plnkr

JS:

    function SomeController($http){
  this.someValue = 'initial';
  $http.get('test.json').then(function (data) {
    this.someValue="changed";
    console.log("get request "+this.someValue);
  });
}

app.controller('someController', SomeController);

HTML:

<div ng-controller="someController as some">
      <p>{{some.someValue}}</p>
    </div>

每当我们创建一个函数时,它都有自己的 this(上下文)。在您的情况下 this 您在 $http.get 内部使用的成功函数不是 SomeController 函数的 this(context)。您必须将 SomeController 函数上下文保留在 self 变量中,然后在 $http.get 函数的成功回调中使用该变量,以便 this 将被视为全局变量。

控制器

function SomeController($http){
  var self =this;
  self.someValue = 'initial';
  $http.get('test.json').then(function (data) {
    self.someValue="changed";
    console.log("get request "+this.someValue);
  });
}

Demo Plunkr

this 在您的 controller$http 中是不同的,因为它们在不同的范围块中,因此在另一个变量中分配 this,例如 _this并使用它。

试一试

function SomeController($http){
  var _this = this;
  _this.someValue = 'initial';
  $http.get('test.json').then(function (data) {
    _this.someValue="changed";
    console.log("get request "+_this.someValue);
  });
}