問題:
I'm writing a small AngularJS app that has a login view and a main view, configured like so: 我正在編寫一個小的AngularJS應用,該應用具有登錄視圖和主視圖,其配置如下:
$routeProvider
.when('/main' , {templateUrl: 'partials/main.html', controller: MainController})
.when('/login', {templateUrl: 'partials/login.html', controller: LoginController})
.otherwise({redirectTo: '/login'});
My LoginController checks the user/pass combination and sets a property on the $rootScope reflecting this: 我的LoginController檢查用戶/密碼組合,並在$ rootScope上設置一個屬性,以反映此情況:
function LoginController($scope, $location, $rootScope) {
$scope.attemptLogin = function() {
if ( $scope.username == $scope.password ) { // test
$rootScope.loggedUser = $scope.username;
$location.path( "/main" );
} else {
$scope.loginError = "Invalid user/pass.";
}
}
Everything works, but if I access http://localhost/#/main
I end up bypassing the login screen. 一切正常,但是如果我訪問http://localhost/#/main
我最終將繞過登錄屏幕。 I wanted to write something like "whenever the route changes, if $rootScope.loggedUser is null then redirect to /login" 我想寫一些類似的內容,“每當路由更改時,如果$ rootScope.loggedUser爲null,則重定向到/ login”
... ...
... wait. ...等等。 Can I listen to route changes somehow? 我可以聽路線變化嗎? I'll post this question anyway and keep looking. 無論如何,我都會發布這個問題並繼續尋找。
解決方案:
參考一: https://en.stackoom.com/question/mQWN參考二: https://stackoom.com/question/mQWN