我在尝试将“this”与 Controller 内的 Angular 函数(特别是 $http.get)一起使用时遇到问题。
例子:
Javascript-(伪代码)
...
.controller('testController')
{
$http.get(data)
{
this.Stuff = data;
}
}
...
HTML-
<div ng-controller='testController as test'>
{{test.Stuff}}
</div>
当试图访问 html 中的 test.Stuff 时,它是空的。
我知道存在范围问题,但我不应该能够在 $http 函数中访问 Controller 的“this”吗?
最佳答案
您会注意到成功回调中的 this
指的是 window
(全局对象)。您的成功回调是使用 window
作为上下文调用的,因为不是其他函数成员的函数是使用 window
对象作为函数的上下文调用的。如果您希望 this
引用您的 Controller 实例,您必须将该上下文绑定(bind)到该函数。您可以使用 angular.bind来完成这个。
.controller('testController')
{
$http.get(data).success(angular.bind(this, function(data) {
this.Stuff = data;
}));
}
关于javascript - Controller 内的 Angular $http 函数作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24809189/