加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 我如何使用$ rootScope在Angular存储变量?

发布时间:2020-12-17 09:31:19 所属栏目:安全 来源:网络整理
导读:如何使用$ rootScope将变量存储在控制器中,以便以后在另一个控制器中访问?例如: angular.module('myApp').controller('myCtrl',function($scope) { var a = //something in the scope //put it in the root scope});angular.module('myApp').controller('
如何使用$ rootScope将变量存储在控制器中,以便以后在另一个控制器中访问?例如:
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
});

我该怎么做?

在根范围设置的变量通过原型继承可用于控制器范围。

这里是@ Nitish的演示的修改版本,显示了关系更清晰:
http://jsfiddle.net/TmPk5/6/

注意,当模块初始化时,rootScope的变量被设置,然后每个继承的范围获得自己的可以独立设置的副本(变化函数)。此外,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',$rootScope) {
    $scope.change = function() {
        $scope.test = new Date();
    };

    $scope.changeRs = function() {
        $rootScope.test = new Date();
    };

    $scope.getOrig = function() {
        return $rootScope.test;
    };
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读