我正在尝试绑定到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'
})
})
})没有控制器,因为它只是关于用户的全局存在,与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
});
};这段代码在DOM中更新得很好。它在html中显示用户名,例如:
a.user(ui-if="currentUser", ng-href="/user/{{currentUser._id}}") {{currentUser.username}}发布于 2013-06-07 04:35:08
语法是$rootScope.$watch('currentUser')而不是$rootScope.$watch($rootScope.currentUser)
发布于 2013-06-03 07:54:20
需要更改$rootScope.currentUser,以便您能够注意到其中的任何更改。你已经分享了它的代码。
此外,还需要在angularJS循环(http://docs.angularjs.org/guide/concepts)内对$rootScope.currentUser进行更改。如果是在外部完成的,可以调用$digest (http://docs.angularjs.org/api/ng.$rootScope.Scope#$digest)
https://stackoverflow.com/questions/16888166
复制相似问题