2017-02-11 52 views
0

我试图从根控制器更改常量的值。 然后状态转到登录控制器,其中常量的值仍旧是旧的。更改常数值和角度广播到子控制器1.4.9

最初常数被设定这样的:

var myApp = angular.module("app"); 
myApp.constant("clientsList", [{"object1":....}]); 

我有一个包含

$rootScope.$emit('updateClients', null); 
$state.go('login', {}, {reload: true}); 

在根控制器注销功能:

> $rootScope.$on('updateClients', function(event, clients) { 
>   _this.clientsList = clients; 
>   angular.module("app").constant("clientsList", clients); 
>  }); 

而在登录控制器,后正在被state.go重定向(“登录”):

.controller('LoginController', LoginController); 
function LoginController(clientsList) { 
    // clientsList still have the old value here: 
} 

如何更改clientsList常量的值?

+0

“更改不变”即应该足以告诉你,你不应该这样做:p – Canastro

+0

我虽然这样。但是提供者包含与登录用户相关的数据。我可以使用其他服务... –

+0

雅,总是使用提供者(服务或工厂)来存储您想要全局访问的数据。 – Canastro

回答

1

我会建议使用工厂(或者您喜欢的服务)来执行对API的调用并存储结果。这样你就可以访问所有控制器中的这些值。

我创建,我们使用相同的工厂来获取客户端和存储这个虚拟实例,然后我们得到的clientsList两个不同的控制器:

angular.module('webapp', []) 
 
     .controller('AppCtrl', function($scope, DummyFactory) { 
 
      $scope.clientsList = []; 
 
      $scope.getClients = function() { 
 
      DummyFactory.getClients().then(function(clientsList) { 
 
       $scope.clientsList = clientsList; 
 
      }); 
 
      }; 
 
     
 
     }) 
 
     .controller('OtherCtrl', function($scope, DummyFactory) { 
 
      $scope.clientsList = DummyFactory.clientsList; 
 
     }) 
 
     .factory('DummyFactory', function ($q, $timeout) { 
 
     var clientsList = []; 
 
     
 
     var getClients = function() { 
 
      // Here replace with your service call 
 
      return $q(function (resolve) { 
 
       $timeout(function() { 
 
       var result = [{name: 'a'}, {name:'b'}]; 
 
       
 
       // Here I use this so I don't create a new array 
 
       // this way the reference is not lost in "Other Controller" 
 
       // You could assign a new array, but then you 
 
       // would have to have a $watch on the "OtherController" 
 
       Array.prototype.push.apply(clientsList, result); 
 
       resolve(clientsList); 
 
       }, 500); 
 
      }); 
 
     }; 
 
     
 
     return { 
 
      clientsList: clientsList, 
 
      getClients: getClients  
 
     }; 
 
     });
<!DOCTYPE html> 
 
    <html ng-app="webapp"> 
 
    <head> 
 
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script> 
 
    </head> 
 
    <body ng-controller="AppCtrl"> 
 
     <div ng-controller="AppCtrl"> 
 
      <h1>App Controller:</h1> 
 
      <button ng-click="getClients()">GET CLIENTS</button> 
 
      <ul ng-repeat="item in clientsList"> 
 
       <li ng-bind="item.name"></li> 
 
      </ul> 
 
     </div> 
 
     
 
     <div ng-controller="OtherCtrl"> 
 
      <h1>Other Controller:</h1> 
 
      <ul ng-repeat="item in clientsList"> 
 
       <li ng-bind="item.name"></li> 
 
      </ul> 
 
     </div> 
 
    </body> 
 
    </html>