angularjs看着rootscope变化看着、angularjs、rootscope

2023-09-13 02:51:40 作者:浪得一身野气

我试图绑定到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    });  }; 
AngularJS Scope

这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)

 
精彩推荐