【发布时间】:2013-06-02 23:08:44
【问题描述】:
我正在尝试绑定到 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}}
【问题讨论】:
-
RootScope 只是此应用程序实例的根范围,您将希望使用服务/工厂,并以某种方式在某处保留存在更改。
-
@xmltechgeek 你能举例说明如何正确地做到这一点吗?这听起来像是我需要学习的东西,谢谢
-
尝试将
$rootScope.currentUser设置为错误时的虚拟值,并检查是否是原因。
标签: javascript angularjs