这可能很容易,但仍然如此。我在我的控制器中有一个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>
答案 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);
});
}
答案 1 :(得分:0)
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);
});
}