Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs Watching rootscope changes

I'm trying to bind to rootscope so that I can set presence on a different server when the user logins. Here's my module.

angular.module('presence',    [   ] )  .run(function ($rootScope) {   $rootScope.$watch($rootScope.currentUser, function () {     console.log('change currentUser')     console.log($rootScope.currentUser)     presence.setGlobal({       u: $rootScope.currentUser,       s: 'on'     })   }) }) 

There's no controller because it's just about the global presence of the user and has nothing to do with the DOM.

This is not working, the watch runs once but never again on subsequent changes. Thanks for your help.

Edit: Login code looks like this:

  $scope.login = function() {     $http.post('http://localhost:3000/login', $scope.user).success(function(res, status) {       if (res && res._id) {         $rootScope.currentUser = res       }     }).error(function(res, status) {       $scope.error = res.err     });   }; 

This code updates fine in the DOM. It shows the username in the html for example:

a.user(ui-if="currentUser", ng-href="/user/{{currentUser._id}}") {{currentUser.username}} 
like image 547
Harry Avatar asked Jun 02 '13 23:06

Harry


People also ask

What is rootScope in AngularJS?

All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive. The rootScope is available in the entire application. If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.

How do I get rootScope in AngularJS?

If you want to access root scope out side of controller, use: var rs = angular. element($('body')). scope(); then use rs.

What is rootScope apply ()?

$scope.$apply() This function is used to execute an expression in Agular. The function expression is optional and you can directly use $apply(). This is used to run watcher for the entire scope. $rootScope.$digest()


1 Answers

The syntax was $rootScope.$watch('currentUser') not $rootScope.$watch($rootScope.currentUser)

like image 75
Harry Avatar answered Sep 18 '22 13:09

Harry