1

I am trying to make an $http call in order to store a JSON into $rootScope in the .run() function in an Angular app but the call is done after the controllers are loaded and I cannot use any of the data from the call. Can anyone help me with this issue?

Also tried to see what happens with console.log, the output is "b" then "a" and for $rootScope.xml is undefined

var app = angular.module('lobby', ['ngRoute']);

app.run(['$rootScope','$http', function($rootScope, $http) {
    $http.get(Main.constants.BASEURL+'x.xml').success(function(xml) {
        $rootScope.xml = $.xml2json(xml.data);
        console.log('a');
    });
}]);

app.controller('CategoriesController', function($rootScope) {
    console.log($rootScope.xml);
    console.log('b');
});
2
  • why not just call your $http.get on your controller? Either that or make a service which can return a promise that you can inject and resolve in your controller Commented Jan 10, 2015 at 18:55
  • I need this call for more than one controller I don't wanna do 10 calls for the same file, that's why I'm trying to find a way to just do one before the app loads Commented Jan 10, 2015 at 18:56

1 Answer 1

1

You can try placing a $watch on $rootScope.xml and listen for a new value, which should occur when the $http call resolves & xml scope variable value gets changed.

Code

app.controller('CategoriesController', function($rootScope) {
    $rootScope.$watch('xml', function(newValue, oldValue) {
        if($rootScope.xml) {
            console.log($rootScope.xml);
        }
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

It's a step forward but I still have an issue, now in console.log I get b, undefined, a and then the object. I need to get rid of the undefined case because if I try to use the object I get an error that crashes angular.js
see edit, you have oldValue and newValue as well to eliminate an undefined situation
Thanks a lot for the solution, I've filtered it with $.type

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.