【问题标题】:updating variable in http request callback in angular以角度更新http请求回调中的变量
【发布时间】:2017-02-02 03:21:09
【问题描述】:

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

【问题讨论】:

    标签: javascript angularjs angularjs-controller angularjs-controlleras


    【解决方案1】:

    每当我们创建一个函数时,它都有自己的this(context)。在您的情况下,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

    【讨论】:

      【解决方案2】:

      您的controller$http 中的this 是不同的,因为它们位于不同的范围块中,因此将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);
        });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-17
        • 2017-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多