Multiple controllers call a service that loads data into an object named categories
:
.service('DataService', ['$http', '$q', function($http, $q) {
var categories = {};
// Public API.
return({
setCategory: setCategory,
getCategory: getCategory,
getJSON: getJSON,
categories: categories
});
function setCategory(name, category) {
console.log("setting category");
console.log(name, category)
categories[name] = category;
}
function getCategory(name) {
console.log("getCategories:");
console.log(categories[name]);
return categories[name];
}
function getJSON() {
//JSON stuff to initialize categories values.
}
The issue arises when calling getCategory(name) before categories
is populated:
$scope.category = DataService.getCategory(name);
//$scope.category is undefined
How can I modify the Service so that getCategory waits until categories is defined? Alternatively, how can I adjust the Controller so that getCategory only executes once categories has a value? Attempts with $scope.$watch in the controller have not been successful as it does not update the value.