我有这段代码,它运行良好:
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
。 如果我这样做,我的控制器会像:
app.controller("resourcesCtrl", function (resourceService) {
this.resourceList = [];
this.setResourceList = function(data){
this.resourceList = data;
};
resourceService.GetAll(this.setResourceList);
});
我添加了setResourceList
,以将其称为控制器的方法,以便使用this
访问控制器上下文。但是现在,当setResourceList
方法作为回调函数运行时,this
是window
的(因为我有一个函数调用,而不是方法调用),所以this.resourceList
是未定义的。我正在寻找解决问题的任何解决方案,我认为问题的根源是用this
替换$scope
.当控制器的属性未使用 $scope
定义时,有没有办法访问它们?
使用闭包来捕获this
的值。
app.controller("resourcesCtrl", function (resourceService) {
var that = this;
this.resourceList = [];
this.setResourceList = function(data){
that.resourceList = data;
};
resourceService.GetAll(this.setResourceList);
});