1

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 ?

Community
  • 1
  • 1
Levijatanu
  • 371
  • 2
  • 17

1 Answers1

2

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;
});
Navvygator
  • 129
  • 2
  • Every closure in javascript has self "this" object (scope). You can use other "this" object (scope) in closure by variable "that" (or other variable name). – Navvygator Dec 01 '16 at 09:54