Search code examples
javascripthtmlangularjsangularjs-scopeangularjs-service

How to make data available in all scopes in Angularjs


I wish to fetch data from the server-side using $http and and make it available to the all routes and controllers in my app.

Javascript code sample

myApp.factory('menuService', function($http){

 $http.get('/pages').success(function(data){

        return data; //list of pages
    });
});

myApp.run(function($rootScope, menuService){

    $rootScope.menu = menuService;
});

HTML code sample

<ul >
    <li ng-repeat="page in menu">{{page.title}}</li>
</ul>

This code actually returns the data but does not print it on my html page. Please can someone help? Thanks


Solution

  • You may be able to benefit from setting up your menuService a bit different. Try the following...

    myApp.factory('menuService', function($http) {
    
        function getData() {
            return $http.get('/pages');
        }
    
        return {
            'getData' : getData
        }
    });
    

    Now we have a function wrapped in our $http call in a getData() function, we can now easily leverage then() to resolve the promise returned by getData() in .run(), ensuring we get a resolved value and $rootScope.menu gets assigned the values we want. This new setup on menuService now sets the landscape to add other functions at later times, which we'll likely want.

    myApp.run(function($rootScope, menuService) {
        menuService.getData().then(function(response) {
            $rootScope.menu = response;
        })
    });
    

    Check out the $http docs for a better understanding on asynchronous behavior