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 ?

1 Answer 1

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.