如何使用 $rootScope
将变量存储在我想要稍后在另一个 Controller 中访问的 Controller 中?例如:
angular.module('myApp').controller('myCtrl', function($scope) {
var a = //something in the scope
//put it in the root scope
});
angular.module('myApp').controller('myCtrl2', function($scope) {
var b = //get var a from root scope somehow
//use var b
});
我该怎么做?
最佳答案
在根范围设置的变量可通过原型(prototype)继承供 Controller 范围使用。
这是 @Nitish 演示的修改版本,更清楚地显示了这种关系: http://jsfiddle.net/TmPk5/6/
请注意,rootScope 的变量是在模块初始化时设置的,然后每个继承的作用域都会获得自己的副本,可以独立设置(change
函数)。此外,rootScope 的值也可以更新(myCtrl2
中的 changeRs
函数)
angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
})
.controller('myCtrl2', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.changeRs = function() {
$rootScope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
});
关于angularjs - 如何在 Angular 中使用 $rootScope 来存储变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18880737/