使服务与2个控制器保持同步

时间:2015-05-27 15:19:12

标签: javascript angularjs angularjs-scope angularjs-service

我们的应用有一个服务广告系列,在路由器解析后,我们的主要产品控制器中使用了该服务。

MainCtrl:

$scope.campaign = campaign;
$scope.campaign.someProp = dynamicPerProduct();

第2行^添加了特定于广告系列的属性,例如覆盖默认电话号码。

我假设这会通过引用绑定到原始服务对象,但通过MainCtrl中的$ scope添加或更改属性似乎没有传递给InterimCtrl控制器,后者重新加载原始数据来自广告系列服务

激活临时页面就像在产品页面末尾添加/临时一样简单。是因为我在路由器中重新解析了该服务不在两个控制器上共享范围的广告系列服务吗?

临时管制员:

 $scope.campaign = campaign;
 // causes refresh of data, does not pick up on line 2 from above example

路由器:

$routeProvider
  .when('/:groupName/:productName/', {
    templateUrl: 'views/main.html',
    controller: 'MainCtrl',
    resolve: {
      campaign: ['$route', 'campaign',
        function($route, campaign) {
          return campaign.getCampaign($route.current.params.groupName, $route.current.params.productName)
            .then(function(campaignResult) {
              return campaignResult;
            });
        }
      ]
    }
  }).when('/:groupName/:productName/interim', {
    templateUrl: 'views/interim.html',
    controller: 'InterimCtrl',
    resolve: {
      campaign: ['$route', 'campaign',
        function($route, campaign) {
          return campaign.getCampaign($route.current.params.groupName, $route.current.params.productName)
            .then(function(campaignResult) {
              return campaignResult;
            });
        }
      ]
    }
  })

服务:

angular.module('campaign', [])
  .factory('campaign', function($log, $http, $q, $rootScope) {

    var campaigns = {};

    var getCampaign = function(groupName, productName, shortName) {

      var apiEndPoint; //defined by env, not necessary for example

      var campaign = campaigns[shortName];
      var deferred = $q.defer();
      if (campaign) {
        deferred.resolve(campaign);
      }

      $http.get(apiEndPoint, { cache: true }).then(function(response) {

        if (angular.isObject(response.data)) {
          campaigns[response.data.shortName] = {};
          angular.copy(response.data, campaigns[response.data.shortName])
          deferred.resolve(response.data);
        }
      })
      return deferred.promise;
    };

  
    return {
      getCampaign: getCampaign
    };

  });

0 个答案:

没有答案