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

查看:20
本文介绍了如何在 Angular 中使用 $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
});

我该怎么做?

推荐答案

在根作用域设置的变量通过原型继承可用于控制器作用域.

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

这是@Nitish 演示的修改版本,更清楚地显示了这种关系: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 的变量在模块初始化时设置,然后每个继承的作用域都得到自己的副本,可以独立设置(change 函数).此外,rootScope 的值也可以更新(myCtrl2 中的 changeRs 函数)

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

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

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