Last active
May 18, 2016 16:45
-
-
Save benjiwheeler/c3708962ad908664a2a3bf73d753f530 to your computer and use it in GitHub Desktop.
Angular Service to share JSON data among controllers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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