angularjs看着rootscope变化 [英] angularjs Watching rootscope changes

查看:142
本文介绍了angularjs看着rootscope变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图绑定到rootscope,这样我可以在不同的服务器,当用户登录上设置presence。
这里是我的模块。

  angular.module('presence',
  [
  ]
).RUN(函数($ rootScope){
  $ rootScope。$腕表($ rootScope.currentUser,函数(){
    的console.log('变化的currentUser)
    的console.log($ rootScope.currentUser)
    presence.setGlobal({
      U:$ rootScope.currentUser,
      儿子'
    })
  })
})

有没有控制器,因为它只是用户的全球presence和无关的DOM。

这是行不通的,手表运行一次,但不会再在随后的变化。感谢您的帮助。

编辑:登录code是这样的:

  $ scope.login =功能(){
    $ http.post(的http://本地主机:3000 /登录',$ scope.user).success(功能(资源,地位){
      如果(RES和放大器;&安培; res._id){
        $ rootScope.currentUser =水库
      }
    })错误(功能(资源,地位){
      $ scope.error = res.err
    });
  };

这code更新的DOM罚款。它显示了HTML的用户名,例如:

  a.user(UI-IF =的currentUser,NG-HREF =/用户/ {{currentUser._id}}){{currentUser.username}}


解决方案

的语法是 $ rootScope。$腕表('的currentUser')不是 $ rootScope。$腕表($ rootScope.currentUser)

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}}

解决方案

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

这篇关于angularjs看着rootscope变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆