我正在编写一个小型 AngularJS 应用程序,它有一个登录 View 和一个主视图,配置如下:
$routeProvider
.when('/main' , {templateUrl: 'partials/main.html', controller: MainController})
.when('/login', {templateUrl: 'partials/login.html', controller: LoginController})
.otherwise({redirectTo: '/login'});
我的 LoginController 检查用户/密码组合并在 $rootScope 上设置一个属性来反射(reflect)这一点:
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.";
}
}
一切正常,但如果我访问http://localhost/#/main
,我最终会绕过登录屏幕。我想写一些类似“每当路由更改时,如果 $rootScope.loggedUser 为 null 则重定向到/login”
...
...等等。我可以以某种方式监听路线变化吗?无论如何,我都会发布这个问题并继续寻找。
最佳答案
在深入研究了一些文档和源代码之后,我想我已经成功了。也许这对其他人有用?
我将以下内容添加到我的模块配置中:
angular.module(...)
.config( ['$routeProvider', function($routeProvider) {...}] )
.run( function($rootScope, $location) {
// register listener to watch route changes
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
if ( $rootScope.loggedUser == null ) {
// no logged user, we should be going to #login
if ( next.templateUrl != "partials/login.html" ) {
// not going to #login, we should redirect now
$location.path( "/login" );
}
}
});
})
看起来奇怪的一件事是我必须测试部分名称 (login.html
),因为“下一个”Route 对象没有 url 或其他内容。也许有更好的方法?
关于angularjs - 根据条件重定向到特定路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11541695/