以角度为单位更新http请求回调中的变量

时间:2016-09-24 09:28:13

标签: javascript angularjs angularjs-controller angularjs-controlleras

这可能很容易,但仍然如此。我在我的控制器中有一个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>

2 个答案:

答案 0 :(得分:1)

每当我们创建一个函数时,它都有自己的this(上下文)。在你的情况this中,你在$http.get内部使用的成功函数不是this函数的SomeController(上下文)。您必须将SomeController函数上下文保留在self变量&amp;然后在$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

答案 1 :(得分:0)

thiscontroller中的

$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);
  });
}