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;
        }
     };
 }
]);
View:
<div class="span4" ng-controller="SiteConfigCtrl">
            <header>
                <h2>
                    {{site.title}}
                </h2>
            </header>
                I would write it with promise factory:
myApp.factory('SiteConfigService', ['$http', '$rootScope', '$timeout', 'RESTService', '$q'
 function ($http, $rootScope, $timeout, RESTService, $q) {
    var siteConfig = {} ;
    RESTService.get("https://domain/incentiveconfig", function(data) {
        siteConfig = data;
    });
  // or just 
  // var siteConfig = RESTService.get("https://domain/incentiveconfig");
    return {
        getConfig:function () {
             var deferred = $q.defer();
             deferred.resolve(siteConfig);
              return deferred.promise;    
        }
     };
 }
]);
Controller side
         SiteConfigService.getConfig()
                    .then(function (result) {
                       $scope.site = result;                           
                    }, function (result) {
                        alert("Error: No data returned");
                    });
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With