2013-06-02 21 views
36

我試圖綁定到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}} 
+0

RootScope是隻爲你想要的應用程序的此實例根範圍改爲使用服務/工廠,並以某種方式在某處持續存在更改。 –

+0

@xmltechgeek你可以舉一個如何正確使用它的例子嗎?這聽起來像我需要學習,謝謝 – Harry

+0

嘗試設置'$ rootScope.currentUser'爲錯誤的虛擬值以及檢查是否是原因。 – basarat

回答

63

的語法是$rootScope.$watch('currentUser')$rootScope.$watch($rootScope.currentUser)

+1

嗨,你在哪裏寫這個聲明? –

+0

注入$ rootScope的位置。 –