Share a single service between multiple angular.js apps

The sharedService is being shared, but one angular app doesn’t know that something updated in the other app so it doesn’t kick off a $digest. You have to manually tell the $rootScope of each application to start a $digest by calling $rootscope.$apply()

Fiddle: http://jsfiddle.net/pvtpenguin/k9KM7/3/

  angular.module('test-service', [])
  .service('TestService', function($rootScope, $window){
    var text="Initial state";
    $window.rootScopes = $window.rootScopes || [];
    $window.rootScopes.push($rootScope);

    if (!!$window.sharedService){
      return $window.sharedService;
    }

    $window.sharedService = {
      change: function(newText){
        text = newText;
        angular.forEach($window.rootScopes, function(scope) {
          if(!scope.$$phase) {
              scope.$apply();
          }
        });
      },
      get: function(){
        return text;
      }
    }

    return $window.sharedService;
  });

Leave a Comment