Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

javascript - 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}}
question from:https://stackoverflow.com/questions/16888166/angularjs-watching-rootscope-changes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...