Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular Service to share JSON data among controllers
// data.json could look like:
// {
// "menu": [{"name": "Contact Us"}, {"name": "About Us"}]
// }
// app.js could look like:
var app = angular.module('myApp');
app.factory('commonData', ['$http', '$q', function($http, $q){
var menu = {};
var loaded = false;
var service={};
var getData = function() {
return {
"menu": menu
};
};
service.fetchData = function() {
var dataDefer = $q.defer();
if (loaded === true) {
dataDefer.resolve(getData());
} else {
$http.get('data.json').success(function(data) {
menu = data.menu;
loaded = true;
dataDefer.resolve(getData());
});
}
return dataDefer.promise;
};
return service;
}]);
app.controller('MenuController', ['$scope', 'commonData', function($scope, commonData) {
commonData.fetchData().then(function(data) {
$scope.menuItems = data.menu;
});
}]);
// in html, you can do:
// (in head, include app.js)
// ...
// <div ng-app="myApp">
// <div ng-controller="MenuController">
// <div ng-repeat="item in menuItems">
// ...{{item.name}}
// </div>
// </div>
// </div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment