1

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

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> 

回答

1

每当我们创造它有自己的this(上下文)的功能。在你的情况this你正在使用里面$http.get成功函数不是this(上下文)的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

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