Search code examples
angularjsangularjs-scopeangularjs-serviceangularjs-routing

How to stop execution of Controller with $routeChangeStart in angularjs


I am setting session on login and after that I am preventing LoginCtrl to be called as it is resetting session. I have a setup of routes where if any undefined route is called it takes to /login But to avoid this on login I am redirecting using the following code, which seems to be not working

I am also using event.preventDefault(); but no use. LoginCtrl is unstoppable and regardless of $location.path() being changed to some other controller it is still executed.

app.run(['$rootScope', '$location', 'SessionService', function ($rootScope, $location, sessionService) {
    $rootScope.$on('$routeChangeStart', function (event, next) {
//      if((next.redirectTo == '/login' || next.originalPath == '/login') && sessionService.isLogin()){
      if((next.templateUrl == 'views/login.html') && sessionService.isLogin()){
          event.preventDefault();
          $location.path('/settings/resetpassword');
          return;
        }

    });
}]);

Following is LoginCtrl.

angular.module('myApp')
.controller('LoginCtrl', function ($scope, $location, loginService, SessionService, ShowApiErrors) {
    $scope.init = function () {
      SessionService.resetMySession();
    };
    $scope.init();

});

Router :-

$routeProvider
      .when('/', {
        redirectTo: '/login'
     })
    ....
     .otherwise({
        redirectTo: '/login'
      });

Solution

  • After a bit of more hard googling I found this url It tells that I should rather use $locationChangeStart It has the ability to stop the execution right away and I redirected back to my intended route.

    $rootScope.$on('$locationChangeStart', function (event, next) {
          if(next.match('/login') && sessionService.isLogin()){
            $location.path('/after-login-path');
          }
        });