angularjs观察rootcope的变化

Har*_*rry 38 javascript angularjs

我正在尝试绑定到rootscope,以便在用户登录时可以在不同的服务器上设置状态.这是我的模块.

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'
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

没有控制器,因为它只是用户的全球存在而与DOM无关.

这不起作用,手表只运行一次,但从未在后续更改中运行.谢谢你的帮助.

编辑:登录代码如下所示:

  $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
    });
  };
Run Code Online (Sandbox Code Playgroud)

此代码在DOM中更新.它显示了html中的用户名,例如:

a.user(ui-if="currentUser", ng-href="/user/{{currentUser._id}}") {{currentUser.username}}
Run Code Online (Sandbox Code Playgroud)

Har*_*rry 67

语法$rootScope.$watch('currentUser')不是$rootScope.$watch($rootScope.currentUser)