AngularJS $watch root scope variable for changes
来源:互联网 发布:msn软件官方下载 编辑:程序博客网 时间:2024/05/22 00:11
AngularJS $watch root scope variable for changes
up vote3down votefavorite
2
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);
angularjs
add a comment
1 Answer
activeoldestvotes
up vote18down vote
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 passtrue
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
- AngularJS $watch root scope variable for changes
- angularJS<六、$scope里的$watch方法>
- angularjs $scope.$watch 遇到的问题
- angularJS<$scope里的$watch方法>
- Angularjs $scope 里面的$apply方法 和 $watch方法
- angularJS $scope的$watch方法监听model改变
- Angularjs $scope 里面的$apply 方法 和 $watch 方法
- AngularJs学习笔记(4)--$scope里的$watch方法
- AngularJS 学习笔记(2)-MVC,$scope,$watch
- $scope.$watch
- angularjs $watch
- AngularJS scope
- AngularJs--Scope
- AngularJS: $scope
- AngularJS 中的scope($scope)
- angularjs UI控制其分离,scope应用及$watch观察模型变化
- AngularJS基础——$scope里的$apply方法和$watch方法
- [AngularJS面面观] 12. scope中的watch机制---第三种策略$watchCollection
- 第n个丑数
- 数据结构之自建算法库——链栈
- Surrounded Regions
- 服务发现:Zookeeper vs etcd vs Consul
- 一个简单的算法---实现找出数组中一个数字出现次数最多的数字
- AngularJS $watch root scope variable for changes
- Java接口类只能声明静态属性
- 程序猿老张-上
- 如何在web.xml中加载外部多个xml文件
- sql统计某年的12个月工作数据
- 利用Jquery给当前页或者跳转后页面的导航栏添加选中后样式
- 智能指针
- 如何做一个有文艺气息的程序员?
- iOS 识别系统内部地址、电话信息并点击可跳转至系统自带软件