angularjs – 根据条件重定向到某个路由

前端之家收集整理的这篇文章主要介绍了angularjs – 根据条件重定向到某个路由前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我写了一个小的AngularJS应用程序,它有一个登录视图和主视图,配置如下:
$routeProvider
 .when('/main',{templateUrl: 'partials/main.html',controller: MainController})
 .when('/login',{templateUrl: 'partials/login.html',controller: LoginController})
 .otherwise({redirectTo: '/login'});

我的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.";
    }
}

一切正常,但如果我访问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" ) {
          // already going to #login,no redirect needed
        } else {
          // not going to #login,we should redirect now
          $location.path( "/login" );
        }
      }         
    });
 })

一个似乎奇怪的事情是,我不得不测试部分名称(login.html),因为“下一个”Route对象没有url或其他东西。也许有更好的方法

原文链接:https://www.f2er.com/angularjs/147499.html

猜你在找的Angularjs相关文章