0 votes
1 view
in Web Technology by (47.8k 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 (107k 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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...