Reputation: 418
I'am sloving problem of reusing same function with scope access in two Controllers decribed here: How to include/inject functions which use $scope into a controller in angularjs?
In controller:
new CommonService($scope).getSomethingFromDB();
In factory:
services.factory("CommonService", function (DBService) {
function Factory ($scope) {
this.$scope = $scope;
}
Factory.prototype.getSomethingFromDB = function () {
if( angular.isUndefined(this.$scope.vrsteObracuna) || this.$scope.vrsteObracuna === null) {
this.$scope.loading = true;
DBService.getSomethingFromDB(
function success(data) {
this.$scope.loading = false; //ERROR !!!
this.$scope.vrsteObracuna = data;
},
function error(data, status, headers, config) {
this.$scope.loading = false;
etna.notifications.error("Error fetching!");
}
)
}
return this.$scope.vrsteObracuna;
}
return Factory;
});
Problem is that after success callback from DBService.getSomethingFromDB this.$scope.loading is undefined ?
Upvotes: 1
Views: 73
Reputation: 129
You haven't $scope into "success" closure, try to use this code:
services.factory("CommonService", function (DBService) {
function Factory ($scope) {
this.$scope = $scope;
}
Factory.prototype.getSomethingFromDB = function () {
if( angular.isUndefined(this.$scope.vrsteObracuna) || this.$scope.vrsteObracuna === null) {
this.$scope.loading = true;
var that = this;
DBService.getSomethingFromDB(
function success(data) {
that.$scope.loading = false; //ERROR !!!
that.$scope.vrsteObracuna = data;
},
function error(data, status, headers, config) {
that.$scope.loading = false;
etna.notifications.error("Error fetching!");
}
)
}
return this.$scope.vrsteObracuna;
}
return Factory;
});
Upvotes: 2