Angular ui-router: warn user when exiting 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 $locationChangeStart in the page controller, where I want to warn the user, it will work even when it comes to the page, which is undesirable.

If I use it on the parent controller, it will run everywhere, and I need to add a complex if / else or switch structure to basically say that it never starts unless the user leaves this particular state.

How to determine that the user is actually leaving (and only leaving) from a particular state using a UI router?

+6
source share
1 answer

You must use the event (and connect to your interlocutor)

$ stateChangeStart

Called when a state transition begins. You can use event.preventDefault() to prevent the transition, and then the promise of the transition will be rejected with a value prevented by the transition.

...

Example:

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

This Q and A has a detailed explanation and a working plunker:

+4
source

All Articles