7

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?

Tiago
  • 4,233
  • 13
  • 46
  • 70

1 Answers1

6

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:

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Might need to add a: event.returnValue = 'something'; below event.preventDefault(); for the alert to show. – zenw0lf Feb 10 '17 at 19:10
  • 3
    Is this still viable? According to ui-router docs: "State change events are deprecated, DISABLED and replaced by Transition Hooks as of version 1.0." – Tom Nijs Mar 01 '17 at 15:18