In this example, We will learn how to redirecting to a certain route based on condition in AngularJS After some diving through some documentation and source code, I think I got it working. Perhaps this will be useful for someone else?
I added the following to my module configuration:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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" ); } } }); }) |
The one thing that seems odd is that I had to test the partial name (login.html) because the “next” Route object did not have a url or something else. Maybe there’s a better way.
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.