AngularJS $watch root scope variable for changes

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

In app.js under .run:

 $rootScope.uPLevel = 0;

.controller

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

1 Answer

up vote 18 down vote accepted

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

Two sidenotes:

  • 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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
$watchAngularJS中的一个函数,用于监视一个表达式的变化并触发相应的回调函数。它可以用于监听对象的变化并执行相应的操作。 通过在控制器中使用$watch函数,可以监听一个model的变化,当model发生变化时,$watch函数会触发回调函数,并传递新值和旧值作为参数。 在上述引用的代码中,$watch函数的第一个参数是要监听的对象,可以是一个字符串表达式或一个函数。第二个参数是一个回调函数,当监听的对象发生变化时,这个函数会被触发。第三个参数是可选的,用于判断监听的对象的变化是否使用深比较。 总的来说,$watch函数是AngularJS中用于监听对象变化的重要工具,可以帮助我们实时监测和处理数据的变化。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [angularjs $watch](https://blog.csdn.net/qianqianstd/article/details/75040501)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* [AngularJS--$watch用法 整理](https://blog.csdn.net/shi_6_tians/article/details/100102393)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值