Simran Kaur
Simran Kaur

Reputation: 1101

urlRouteProvider.otherwise leads to infinite loop in angular

Routing in my angular app looks like this:

.config(function($stateProvider,$urlRouterProvider){
  $stateProvider
  .state('Login',{
    url:'/login',
    templateUrl:'templates/login.html',
    controller:'LoginCtrl'

  })

  .state('Deployment',{
    url:'/deployment',
    templateUrl:'templates/deployment.html'
  })
  .state('Bill',{
    url:'/bills',
    templateUrl:'templates/bills.html'
  })

$urlRouterProvider.otherwise(function ($injector) {
           var $state = $injector.get('$state');
            $state.go('Login');
        });
//This line is the culprit. This does not happen if I change state to go to Deployment but I need it to be Login

});

I basically need to skip Login state and jump to Deployment state if $localstorage has userIfo.

Login.html 

<form name="loginform" ng-if="showForm()"></form>

$scope.showForm looks like this:

$scope.showForm = function(){
  console.log("called")
  if($localStorage.userInfo === null || $localStorage.userInfo === undefined){
   return true;
  }else{
    $scope.signInUser();
   return false;
  }
}

but the problem is that $scope.showForm keeps on getting called.

However, it does not happen if I change the urlRouterProvider.otherwise to Deployment state.

How do I solve the issue? Honestly I have tried almost everything but have not been able to sort it.

Upvotes: 0

Views: 119

Answers (1)

Kia Raad
Kia Raad

Reputation: 1335

ngIf directive gets called on every angular digest cycle. So instead of calling the showForm function in an ngIf directive, I suggest you do that in the onEnter event of the Login state.

$stateProvider
  .state('Login',{
    url:'/login',
    onEnter:["$state","$localStorage",function($state,$localStorage){
       if($localStorage.userInfo)
            $state.go("Deployment");
    }],
    templateUrl:'templates/login.html',
    controller:'LoginCtrl'

  })

Although there are lots of other (and maybe even better) ways to implement this feature, one may be using a parent abstract state which decides weather to dispatch the routing to Login state or not.

Upvotes: 1

Related Questions