Shared Services
http://stackoverflow.com/questions/16725392/share-a-single-service-between-multiple-angular-js-apps
by rtcherry
HTML
<script src="http://code.jquery.com/jquery-1.6.4.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div id="firstApp">
<button ng-click="change()">Change</button>{{ getData() }}</div>
<div id="secondApp">
<button ng-click="change()">Change</button>{{ getData() }}</div>
JavaScript
angular.module('shared-service', [])
.service('SharedService', ['$window', '$rootScope', '$timeout', function ($window, $rootScope, $timeout) {
var rootScopes = [],
data = 'Initial state';
if ( !$window.sharedService) {
$window.sharedService = {
registerScope: function (scope) {
rootScopes.push(scope);
},
getData: function () {
return data;
},
setData: function (input) {
angular.copy(input, data);
angular.forEach(rootScopes, function (rootScope) {
$timeout(rootScope.$apply);
});
}
};
}
$window.sharedService.registerScope($rootScope);
return $window.sharedService;
}]);
angular.module('firstApp', ['shared-service'])
.controller('FirstAppController', ['$scope', 'SharedService', function ($scope, SharedService) {
$scope.getData = SharedService.getData;
$scope.change = function () {
SharedService.setData('app 1 activated');
};
}]);
angular.module('secondApp', ['shared-service'])
.controller('SecondAppController', ['$scope', 'SharedService', function ($scope, SharedService) {
$scope.getData = function () {
return SharedService.getData();
};
$scope.change = function () {
SharedService.setData('app 2 activated');
};
}]);
var firstAppElement = $('#firstApp')[0],
secondAppElement = $('#secondApp')[0];
angular.bootstrap(firstAppElement, ['firstApp', 'shared-service']);
angular.bootstrap(secondAppElement, ['secondApp', 'shared-service']);