I'm building an ecommerce site (based on shopify) and I'm using multiple small angularjs apps to handle things such as a quick shopping cart, wishlists, filtering products and a few other smaller items. I initially used one big application (that had routing and everything), but it was a bit to restrictive when I didn't have a full REST API.
There are a couple of services that I would like to share between the angular apps (the cart service, so I can have a quick add button that will reflect in the mini-cart and such), but I'm not sure of the best way (if there is a way) to go about this. Just sharing a module with the service doesn't keep the same state across the apps.
I tried my hand at it, but I it doesn't seem to update state between both apps. The following is the javascript I tried using. It's also on jsfiddle with accompanying html: http://jsfiddle.net/k9KM7/1/
angular.module('test-service', [])
.service('TestService', function($window){
var text = 'Initial state';
if (!!$window.sharedService){
return $window.sharedService;
}
$window.sharedService = {
change: function(newText){
text = newText;
},
get: function(){
return text;
}
}
return $window.sharedService;
});
angular.module('app1', ['test-service'])
.controller('App1Ctrl', function($scope, TestService){
$scope.text = function(){ return TestService.get() }
$scope.change = function(){ TestService.change('app 1 activated') }
});
angular.module('app2', ['test-service'])
.controller('App2Ctrl', function($scope, TestService){
$scope.text = function(){ return TestService.get() }
$scope.change = function(){ TestService.change('app 2 activated') }
});
var app1El = document.getElementById('app1');
var app2El = document.getElementById('app2');
angular.bootstrap(app1El, ['app1', 'test-service']);
angular.bootstrap(app2El, ['app2', 'test-service']);
Any help would be appreciated
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…