我有这段代码并且运行良好:
var app = angular.module("resources", []);
app.service("resourceService", function ($http) {
return {
GetAll: function (callBack) {
$http.get("api/Resource/Get").success(function (data) {
callBack(data);
})
}
}
});
app.controller("resourcesCtrl", function ($scope, resourceService) {
$scope.resourceList = [];
resourceService.GetAll(function (data) { $scope.resourceList = data; });
});
在早期版本的 angularjs 中使用“Controller as”语法,您可以将 $scope
替换为 this
。如果我这样做,我的 Controller 将是这样的:
app.controller("resourcesCtrl", function (resourceService) {
this.resourceList = [];
this.setResourceList = function(data){
this.resourceList = data;
};
resourceService.GetAll(this.setResourceList);
});
我添加了 setResourceList
,将其作为 Controller 方法调用,以便使用 this
访问 Controller 上下文。
但是现在,当 setResourceList
方法作为回调函数运行时,this
是 window
(因为我有一个函数调用,而不是方法调用), 所以 this.resourceList
是未定义的。
我正在寻找解决问题的方法,我认为问题的根源是用 this
替换 $scope
。当 Controller 的属性未使用 $scope
定义时,是否有任何方法可以访问它们?
最佳答案
使用闭包来捕获 this
的值。
app.controller("resourcesCtrl", function (resourceService) {
var that = this;
this.resourceList = [];
this.setResourceList = function(data){
that.resourceList = data;
};
resourceService.GetAll(this.setResourceList);
});
关于angularjs - 如何在 Angularjs $http.get().success() 中回调 Controller 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20867001/