Initializing AngularJS service factory style
- by wisemanIV
I have a service that retrieves data via REST. I want to store the resulting data in service level variable for use in multiple controllers. When I put all the REST logic directly into controllers everything works fine but when I attempt to move the retrieval / storing of data into a service the controller is not being updated when the data comes back. I've tried lots of different ways of maintain the binding between service and controller.
Controller:
myApp.controller('SiteConfigCtrl', ['$scope', '$rootScope', '$route', 'SiteConfigService',
function ($scope, $rootScope, $route, SiteConfigService) {
$scope.init = function() {
console.log("SiteConfigCtrl init");
$scope.site = SiteConfigService.getConfig();
}
}
]);
Service:
myApp.factory('SiteConfigService', ['$http', '$rootScope', '$timeout', 'RESTService',
function ($http, $rootScope, $timeout, RESTService) {
var siteConfig = {} ;
RESTService.get("https://domain/incentiveconfig", function(data) {
siteConfig = data;
});
return {
getConfig:function () {
console.debug("SiteConfigService getConfig:");
console.debug(siteConfig);
return siteConfig;
}
};
}
]);