How to make data available in all areas in Angularjs
I want to get data from the server using $http
and make it available to all routes and controllers in my application.
Sample Javascript Code
myApp.factory('menuService', function($http){
$http.get('/pages').success(function(data){
return data; //list of pages
});
});
myApp.run(function($rootScope, menuService){
$rootScope.menu = menuService;
});
Sample HTML Code
<ul >
<li ng-repeat="page in menu">{{page.title}}</li>
</ul>
This code actually returns data, but does not print it in my html page. Please can anyone help? Thanks to
You may be able to change yours a little menuService
. Try this ...
myApp.factory('menuService', function($http) {
function getData() {
return $http.get('/pages');
}
return {
'getData' : getData
}
});
Now that we have a function wrapped in our call $http
in a function getData()
, we can now easily use then()
to resolve the promise returned getData()
in .run()
, ensuring that we get the resolved value and $rootScope.menu
get the assigned values. This new setting does not menuService
now set the landscape to add other features at a later time, which we most likely want.
myApp.run(function($rootScope, menuService) {
menuService.getData().then(function(response) {
$rootScope.menu = response;
})
});
Check out the $ http docs for a better understanding of asynchronous behavior
You are inverting a different promise pattern.
Instead, your code should be:
myApp.factory('menuService', function($http){
return $http.get('/pages');
});
myApp.run(function($rootScope, menuService){
menuService.then(function(data) {
$rootScope.menu = data;
})
});