我正在尝试从根控制器更改常量的值。 然后状态进入登录控制器,其中常量的值仍然是旧值。
最初CONSTANT的设置如下:
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('login')重定向后:
.controller('LoginController', LoginController);
function LoginController(clientsList) {
// clientsList still have the old value here:
}
如何更改clientsList常量的值?
答案 0 :(得分: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>