我試圖綁定到rootcope,以便在用戶登錄時可以在不同的服務器上設置狀態。 這是我的模塊。angularjs觀看根鏡的變化
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你可以舉一個如何正確使用它的例子嗎?這聽起來像我需要學習,謝謝 – Harry
嘗試設置'$ rootScope.currentUser'爲錯誤的虛擬值以及檢查是否是原因。 – basarat