39

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}}
Harry
  • 52,711
  • 71
  • 177
  • 261
  • RootScope is only the root scope for this instance of the application you'll want to use a service/factory instead and somehow persist the presence change somewhere. – Paul Ryan Jun 02 '13 at 23:26
  • @xmltechgeek can you give an example of how to do it properly? That sounds like what I need to learn thanks – Harry Jun 02 '13 at 23:45
  • try setting the `$rootScope.currentUser` to a dummy value on error as well to check if that is the cause. – basarat Jun 03 '13 at 01:18

2 Answers2

69

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

Harry
  • 52,711
  • 71
  • 177
  • 261
1

Something needs to change $rootScope.currentUser for you to be able to notice any changes in it. You have shared the code for that.

Also changes to $rootScope.currentUser need to take place inside the angularJS loop (http://docs.angularjs.org/guide/concepts). If it is done externally you can call $digest (http://docs.angularjs.org/api/ng.$rootScope.Scope#$digest)

basarat
  • 261,912
  • 58
  • 460
  • 511