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);
shareimprove this question
 

1 Answer

activeoldestvotes
up vote18down voteaccepted

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