javascript - 以 Angular 更新 http 请求回调中的变量

标签 javascript angularjs angularjs-controller angularjs-controlleras

这可能很简单,但仍然如此。我的 Controller 中有一个 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(上下文)。在您的情况下,您在 $http.get 成功函数中使用的 this 不是 SomeControllerthis(context) > 功能。您必须将 SomeController 函数上下文保留在 self 变量中,然后在 $http.get 函数的成功回调中使用该变量,以便 this 将被视为全局变量。

Controller

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

关于javascript - 以 Angular 更新 http 请求回调中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39674757/

相关文章:

javascript - 未捕获的范围错误: Maximum call stack size exceeded - Bootstrap Validate

javascript - 使用base64编码将图像嵌入到tinymce中

javascript - 嵌套 AngularJS Controller 的误解

javascript - 返回从字符串位置获取的默认标记的纬度和经度

javascript - AngularJs View 不显示

javascript - 将 $scope 数据从 Controller 传递到 View

javascript - 在 JavaScript 中编写此代码的最短方法

javascript - url 完成加载 View 后删除 localstorage

javascript - Angularjs 范围之外的服务功能

javascript - AngularJS : controller with factory