我如何使用$ rootScope的角度来储存变量? [英] How do I use $rootScope in Angular to store variables?

查看:183
本文介绍了我如何使用$ rootScope的角度来储存变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在控制器我想在另一个控制器以后访问使用 $ rootScope 来存储变量?例如:

How do I use $rootScope to store variables in a controller I want to later access in another controller? For example:

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
});

我将如何做到这一点?

How would I do this?

推荐答案

设置为根作用域的变量都可以通过继承原型控制器范围。

Variables set at the root-scope are available to the controller scope via prototypical inheritance.

下面是显示的关系更清楚一点@尼蒂什的演示的修改版本:
http://jsfiddle.net/TmPk5/6/

Here is a modified version of @Nitish's demo that shows the relationship a bit clearer: http://jsfiddle.net/TmPk5/6/

注意,当模块初始化rootScope的变量设置,然后每个继承范围的获得自己的副本可以单独设置(即变更功能)。此外,rootScope的值可以过更新(即兑换函数 myCtrl2

Notice that the rootScope's variable is set when the module initializes, and then each of the inherited scope's get their own copy which can be set independently (the change function). Also, the rootScope's value can be updated too (the changeRs function in myCtrl2)

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;
    };
});

这篇关于我如何使用$ rootScope的角度来储存变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆