Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I'm writing a small AngularJS app that has a login view and the main view, configured like so:

$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:

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. I wanted to write something like "whenever the route changes if $rootScope.loggedUser is null then redirect to /login"

1 Answer

0 votes
by (106k points)

For redirecting to a certain route based on condition you can add the following to my module configuration:-

angular.module(...) 

.config( ['$routeProvider', function($routeProvider) {...}] ) .run( function($rootScope, $location) { 

$rootScope.$on( "$routeChangeStart", function(event, next, current) {

if ( $rootScope.loggedUser == null ) { 

if ( next.templateUrl != "partials/login.html" ) { 

$location.path( "/login" ); 

   } 

 } 

}); 

})

Related questions

Browse Categories

...