使用服务在控制器之间共享状态

时间:2015-08-03 20:42:52

标签: javascript angularjs

我想分享'州'通过使用服务在我的Angular应用程序中的多个控制器之间我的代码如下。我遇到的问题是,通过vm.toggleStatus()启动状态更改的控制器会更新,但在刷新页面之前,此状态不会在我的其他控制器中更新。

controller1.js:

angular.module('gameApp')
  .controller('PlayerActionsController', PlayerActionsController);

PlayerActionsController.$inject = ['$routeParams', 'playersService'];

function PlayerActionsController($routeParams, playersService) {
  var vm = this;
  var playerId = $routeParams.playerId;

  var getplayerInfo = function() {
    playersService.getPlayerInfo({
      playerId: playerId
    }).$promise.then(function(player) {
      vm.player = player;
    });
  };

  var init = function() {
    getplayerInfo();
  };

  init();

  vm.toggleStatus = function() {
    playersService.toggleStatus({
      playerId: playerId
    }, {}).$promise.then(function() {
      getplayerInfo();
    });
  };
}

controller2.js:

angular.module('gameApp')
  .controller('HeaderController', HeaderController);

HeaderController.$inject = ['$routeParams', 'playersService'];

function HeaderController($routeParams, playersService) {
  var vm = this;
  vm.playerId = $routeParams.playerId;

  var getPlayerInfo = function() {
    playersService.getPlayerInfo({
      playerId: vm.playerId
    }).$promise.then(function(player) {
      vm.player = player;
    });
  };

  var init = function() {
    getPlayerInfo();
  };

  init();
}

players.service.js:

angular.module('gameApp')
  .factory('playersService', ['$resource',
    function($resource) {
      var base = '/api/players/:playerId/';
      return $resource(base, {}, {
        getPlayerInfo: {method: 'GET', url: base + 'playerInfo'},
        toggleStatus: {method: 'PUT', url: base + 'toggleStatus'}
      });
    }]);

1 个答案:

答案 0 :(得分:2)

服务不会将数据推送到控制器,控制器需要从服务中提取数据或监听数据更改。

您可能要做的是更新服务以在数据更改时发出事件,然后将控制器列入这些事件并在更改发生时进行更新。例如:

//service toggleStatus
toggleStatus = function(data) {
    ... what it currently does.


    $rootScope.$emit('StatusChangedEvent', newStatus);

    ... return promise;
}

// in your controllers

$rootScope.$on('StatusChangedEvent', function(evt, newStatus) {
    $scope.status = newStatus;
});