Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ui-router: warn user when leaving a specific page

In my angular app, I need to warn the user before he leaves a specific page, not every page.

If I use a $locationChangeStart within the controller of the page where I want to warn the user, it will trigger even when coming to the page, which is not desired.

If I use it on the parent controller, it will trigger everywhere and I have to add a complex if/else or switch structure to basically tell it to never trigger unless a user is abandoning that specific state.

How do I detect that a user is actually leaving (and only leaving) a specific state using UI-Router?

like image 985
Tiago Avatar asked Sep 15 '15 14:09

Tiago


1 Answers

You should use an event (and hook on your own listener)

$stateChangeStart

Fired when the state transition begins. You can use event.preventDefault() to prevent the transition from happening and then the transition promise will be rejected with a 'transition prevented' value.

...

Example:

$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
    event.preventDefault();
    // transitionTo() promise will be rejected with
    // a 'transition prevented' error
})

There is a detailed explanation and working plunker in this Q & A:

  • Confusing $locationChangeSuccess and $stateChangeStart
  • Angularjs ui-router. How to redirect to login page
  • Angular ui router - Redirection doesn't work at all
like image 186
Radim Köhler Avatar answered Sep 21 '22 19:09

Radim Köhler