gpt4 book ai didi

javascript - angularjs 观察 rootscope 的变化

转载 作者:IT王子 更新时间:2023-10-29 03:10:17 24 4
gpt4 key购买 nike

我正在尝试绑定(bind)到 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'
})
})
})

没有 Controller ,因为它只是关于用户的全局存在,与 DOM 无关。

这是行不通的, watch 会运行一次,但不会在后续更改时再次运行。感谢您的帮助。

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

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

最佳答案

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

关于javascript - angularjs 观察 rootscope 的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16888166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com