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?
You should use an event (and hook on your own listener)
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With