这可能很简单,但仍然如此。我的 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
不是 SomeController
的 this
(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);
});
}
关于javascript - 以 Angular 更新 http 请求回调中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39674757/