Initializing AngularJS service factory style

Posted by wisemanIV on Stack Overflow See other posts from Stack Overflow or by wisemanIV
Published on 2013-10-28T21:51:03Z Indexed on 2013/10/28 21:53 UTC
Read the original article Hit count: 187

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;
        }

     };
 }
]);

© Stack Overflow or respective owner

Related posts about angularjs

Related posts about angularjs-service