Learner
Learner

Reputation: 315

statechangestart prevent from navigating

$rootScope.$on('$stateChangeStart', function(event, toState  , toParams
                                                   , fromState, fromParams) {
     if(fromState.name=='home' && toState.name == 'search'){
         event.preventDefault();
     }
});

I am trying to prevent the state transitioning from happening.

event.preventDefault() 

is not doing that. I want the state to remain in the current one.

Upvotes: 3

Views: 5366

Answers (1)

Radim Köhler
Radim Köhler

Reputation: 123861

What you require, should be working out of the box. I created a plunker, showing your requirement in action. There are these three sample states

$stateProvider
    .state('home', {
        url: '/home',
        template: '<div>home</div>',
      })
    .state('search', {
        url: '/search',
        template: '<div>search</div>',
      })
    .state('index', {
        url: '/index',
        template: '<div>index</div>',
      })

And this (the same as in question) condition DISABLES navigation from HOME to SEARCH:

$rootScope.$on('$stateChangeStart',
   function(event, toState  , toParams
                   , fromState, fromParams) 
    {
      var isFromHome = fromState.name =='home' ;
      var isToSearch = toState.name == 'search';
      if(isFromHome && isToSearch)
      {
        event.preventDefault();
      }
    });

Check it here

Upvotes: 4

Related Questions