brother
brother

Reputation: 8151

Angular variable in factory?

In a Angular app i have a couple of calls to a WebAPI service.

The first call, lets call it call1, should determine a true/false value of a variable.

So i have this

vm.call1.$promise.then(function (data) { 
   $rootScope.variable1 = data.variable;
});

This variable is to be used inside a factory i have;

myApp.factory('myStore', function ($http, $q, $rootScope) {
    var showAll = $rootScope.variable1;

    var get = function () {
        if (showAll) {
            //do this
        } else {
            //do this
        }
    };

    return {
        get: get
    };
});

My problem is, that the factory above is loaded on pageload, and before the promise, and therefore the value is undefined.

How can i get the value, over to my factory, after the promise is complete?

Upvotes: 0

Views: 39

Answers (1)

Bata
Bata

Reputation: 651

No rootscope example: You can set the showAll flag manually:

vm.call1.$promise.then(function (data) { 
    myStore.setShowAll(data.variable);
});

and in the Factory:

myApp.factory('myStore', function ($http, $q) {
    var showAll = 'true or false to be a default';

    var get = function () {
        if (showAll) {
            //do this
        } else {
            //do this
        }
    };

    var setShowAll = function(value) {
        showAll = value;
    };

    return {
        get: get,
        setShowAll: setShowAll
    };
});

Rootscope example: If you for some reason really need to use $rootScope for this you can just check for $rootScope value when you get, you don't have to store the value in a varibale.

myApp.factory('myStore', function ($http, $q, $rootScope) {

    var get = function () {
        if ($rootScope.variable1) {
            //do this
        } else {
            //do this
        }
    };

    return {
        get: get
    };
});

Upvotes: 2

Related Questions