I have this code and it is working well:
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; });
});
Using "Controller as" syntax in earlier version of angularjs, you can replace $scope
with this
. if I do it, my controller will be like:
app.controller("resourcesCtrl", function (resourceService) {
this.resourceList = [];
this.setResourceList = function(data){
this.resourceList = data;
};
resourceService.GetAll(this.setResourceList);
});
I add setResourceList
, to call it as a method of controller, to have access to the controller context using this
.
But now, when setResourceList
method is running as a callback function, the this
is window
(as I have a function call, not a method call), so this.resourceList
is undefined.
I'm seeking any solution to solve the problem, and I think the problem root is replacing $scope
with this
. Is there any way to access the properties of controller when they are not defined using $scope
?