AngularJS $ watch根范围变量进行更改 [英] AngularJS $watch root scope variable for changes

查看:48
本文介绍了AngularJS $ watch根范围变量进行更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下$ rootScope变量,该变量用于保存当前登录的用户特权级别,然后从其他控制器访问此变量.有没有一种方法可以监视rootScope变量的更改,以便通过对根范围变量的任何更改来更新控制器特定的变量?以下是到目前为止我正在使用的代码,有人可以告诉我我在做什么错以及如何解决吗?谢谢

I have the following $rootScope variable which I use to save the current logged in user privilege level, then I access this variable from other controllers. Is there a way I can watch the rootScope variable for changes in order to update controllers specific variables with any changes to the root scope variable? Below is the code I am using so far, can someone please tell me what I am doing wrong and how to fix it? Thanks

在.run下的app.js中:

In app.js under .run:

 $rootScope.uPLevel = 0;

.controller

.controller

   $scope.$watch($rootScope.uPLevel, function() {
            $scope.userPLevel = $rootScope.uPLevel;
   }, true);

推荐答案

$watch的第一个参数应该是字符串或函数(

The first parameter to $watch should either be a string or a function (docs). Right now you're passing it the value of $rootScope.uPLevel on controller initialization.

$scope.$watch(function() {
  return $rootScope.uPLevel;
}, function() {
  $scope.userPLevel = $rootScope.uPLevel;
}, true);

两个旁注:

  • 最好将此值存储在服务中,而不要存储在$rootScope中.
  • 如果uPLevel仅是一个整数(如您的示例所示),则无需将true作为第三个参数传递-仅用于数组和对象.如果您确实想观看收藏,则建议使用$watchCollection代替.
  • It may be prudent to store this value in a service instead of $rootScope.
  • If uPLevel is only an integer (as your example suggests) then you don't need to pass true as the third parameter - that's only for arrays and objects. If you do want to watch a collection, then I suggest using $watchCollection instead.

这篇关于AngularJS $ watch根范围变量进行更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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