2017-02-11 56 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>