angularjs - 如何在 Angular 中使用 $rootScope 来存储变量?

标签 angularjs angularjs-scope angularjs-controller rootscope

如何使用 $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/

相关文章:

angularjs - 重新排列 : is it possible to have a progress bar ?

javascript - 使用 angular.js 和 php 在 $http 请求中的错误回调函数中遇到问题

javascript - 无法让 Angular 应用程序在 MVC 布局中工作

angularjs - 什么时候 $scope.$apply 需要用 Angular 处理对象/数组?

javascript - Angular 1 中的 Angular 2 组件?

AngularJS 和 Typescript : How to assign a class/type as a directive's controller?

angularjs - 如何在打开的模态组件中访问 `BsModalRef`?

javascript - 在 AngularJS 中使用绑定(bind)变量调用 Controller 方法

javascript - $http Post 不发送数据

javascript - AngularJS 将新服务注入(inject)我的 Controller 时出现问题