2014-03-25 33 views
0

我正在寫一些小練習來教我自己AngularJS和我正在嘗試寫一些簡單的用戶授權任務。我有一個表單來收集/輸入用戶名和密碼,然後使用$http和CORS(因爲我的REST服務在另一個端口上運行)將它們發送到休息服務,它們會被檢查,如果有匹配,我會返回一個UUID並創建一個令牌,然後我的登錄值爲$rootScope上的true,就像這樣。更新AngularJS當用戶操作完成時查看

// this is in a service I call 'authService' 

this.login = function (user) { 

    return $http({method: 'POST', url: 'http://127.0.0.1:3000/login', data: user}) 
     .then(function (response) { 

      // set up a local storage token 
      storageService.setLocalStorage('token', response.data[0].uuid); 
      // broadCast is loggedIn - we have a match 
      $rootScope.loggedInUser = true; // this is set to false at the .run() of the app 
      $rootScope.$broadcast('LoggedIn'); 

      return 1; 
     }, function() { 
      // return http code later 
      return 0; 
     }); 

    }; 

    this.getLoggedIn = function() { 
     return $rootScope.loggedInUser; 
    }; 
在單獨的菜單視圖我有以下條件

現在(在authService添加爲菜單控制器上的扶養):

<div id="logIn" ng-show="!authService.getLoggedIn()">...</div> 

現在,當我加載的應用程序的第一次的條件是正確的,但是我希望這個條件更新,如果用戶登錄正確(所以div)不顯示。在菜單控制器中我有下面的代碼,它似乎沒有任何事情做?

$scope.$on('LoggedIn', function() { 
     authService.getLoggedIn(); // doesn't update the view? 
     console.log($rootScope.loggedInUser); // returns true 
     console.log(authService.getLoggedIn()); // returns true 
    }); 

$scope.$watch('loggedInUser', function() { 
    console.log('loggedInUser has changed ' + $rootScope.loggedInUser); 
    // This runs once when we set $rootScope.loggedInUser in the .run() of the app, output is: 'loggedInUser has changed false' 
    // then when we have successfully logged in again, output is 'loggedInUser has changed true' 
}); 

好了,所以當我改變了$ rootScope.loggedInUser,我做錯了什麼,我的做法在我的菜單視圖的<div>條件不更新,能有人給我一些建議或糾正我的這個方法。謝謝

+0

' ng-show'綁定到一個範圍值,比如'$ scope.isLogon'或一個返回true或false的範圍函數。 'authService.getLoggedIn()'沒有被定義,或者至少不在你在這裏展示的代碼中。所以意味着'authService.getLoggedIn()'總是爲false。 – wayne

+0

對不起,authService.getLoggedIn()是在一個服務中定義的,我將其添加爲菜單控制器的依賴關係,因此當我登錄console.log(authService.getLoggedIn())時;和$ scope。$ watch('loggedInUser'function(){})在控制器中被觸發,但視圖不被更新? –

+0

該視圖不能訪問authService,您可以在菜單控制器中執行代理'authService.getLoggedIn()'。像'$範圍。 getAuth = function(){return authService.getLoggedIn()}'。我也不認爲需要將rootScope引入您的用例。 – wayne

回答

0

你不需要做任何特殊的Angular更新視圖,當某些道具更新時,只要它在正確的範圍內。我爲你提供了一個Plunkr,這表明你不需要做任何特別的事情來刷新視圖。

http://plnkr.co/edit/B6kUwJdA4lRKkjAItSFO?p=preview

你不必做的手錶,你沒有做任何事情。這是Angular的力量。另外,你在Rootcope中設置東西很奇怪。我對你的建議是看我的例子,修改/重構你的代碼。此外,有這樣的東西:

ng-show="!authService.getLoggedIn()"

是不是做事的推薦方式。你可以有一個控制器,在其中你說:

$scope.userLoggedIn = autService.getLoggedIn(); 

,然後在您的視圖:

ng-show="userLoggedIn" 

您也可以看看這個plunkr:

http://plnkr.co/edit/aRhS0h7BgpJJeRNvnosQ?p=preview