我正在建立一个电子商务网站(基于shopify),并且使用多个小型angularjs应用程序来处理诸如快速购物车,收藏夹,过滤产品和其他一些较小物品的事情。我最初使用的是一个大型应用程序(具有路由和所有功能),但是当我没有完整的REST API时,这有点限制性。
我想在角度应用程序之间共享一些服务(购物车服务,所以我可以有一个快速添加按钮,它将反映在微型购物车等中),但我不确定最好的解决此问题的方法(如果有方法)。仅与服务共享模块不会在应用程序中保持相同的状态。
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']);
任何帮助,将不胜感激
将sharedService被共享,但一个角的应用程序不知道的东西在其他应用程序更新,所以它不揭开序幕$digest。您必须通过调用手动告诉$rootScope每个应用程序启动$digest``$rootscope.$apply()
sharedService
$digest
$rootScope
$digest``$rootscope.$apply()
小提琴: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; });