在多个angular.js应用程序之间共享一个单一服务

14 浏览
0 Comments

在多个angular.js应用程序之间共享一个单一服务

我正在构建一个电子商务网站(基于Shopify),我正在使用多个小型的AngularJS应用程序来处理一些事情,比如快速购物车、愿望清单、筛选产品和其他几个较小的项目。起初,我使用了一个大型的应用程序(包含路由和其他一切),但当我没有完整的REST API时,它有点限制性。

有几个服务我想在这些Angular应用程序之间共享(购物车服务,这样我可以有一个快速添加按钮,在迷你购物车中反映出来等等),但我不确定最佳的方法(如果有的话)是什么。只是分享一个带有服务的模块不能在这些应用程序之间保持相同的状态。

我试过了,但似乎不能在两个应用程序之间更新状态。以下是我尝试使用的JavaScript代码。它也在jsfiddle上有相应的HTML:http://jsfiddle.net/k9KM7/1/

angular.module('test-service', [])
  .service('TestService', function($window){
    var text = '初始状态';
    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('应用程序1已激活') }
  });
angular.module('app2', ['test-service'])
  .controller('App2Ctrl', function($scope, TestService){
    $scope.text = function(){ return TestService.get() }
    $scope.change = function(){ TestService.change('应用程序2已激活') }
  });
var app1El = document.getElementById('app1');
var app2El = document.getElementById('app2');
angular.bootstrap(app1El, ['app1', 'test-service']);
angular.bootstrap(app2El, ['app2', 'test-service']);

任何帮助将不胜感激。

0