0

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?

1
  • Add a $watch on $rootScope.variable1, or put the factory call inside the $promise. Commented Mar 12, 2016 at 18:45

1 Answer 1

2

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

1 Comment

Spot on! Thank you very much! :)

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.