Delaying state change with `beforeLeave`


#1

Currently I’m using $scope.$on('$ionicView.beforeLeave', function() { to process some logic when a user leaves the page. The logic checks to see if values have changes since the user had originally been on the page, and if so opens an $ionicPopup asking them if they would like to save their data.

The issue is that when the $ionicPopup opens, I’m already on the new state, leaving my scope to be useless and not being able to send any information to the server.

Is there a way to delay the changing of states until after the save request has been sent?


#2

Rather than use beforeLeave, I would put the check / popup into whatever event is triggered to move them to the next page (say a button click or navigation click). Then if the values haven’t changed call state.go to navigate to the next state. If they have changed, do your save and then when it’s finished call state.go


#3

The issue is that there’s numerous ways to leave the page.

  • The hardware back button (android)
  • The hardware home button (iOS)
  • The back button (Navbar)
  • Any links in the Side menu.

Considering there’s tons of ways to move to a different page/state, using beforeLeave seems like the best option. Currently I have it saving automatically if any changes were made, but I feel like having the popup would be a nicer approach.


#4

try something like that --> listen on “$stateChangeStart” https://github.com/angular-ui/ui-router/wiki#state-change-events
there you get the event the from- and toState and -params.

  1. There you can check if there are unsafed information.
  2. if so --> use event.preventDefault() to interrupt the statechange.
  3. Open you popup
  4. After Popclosing --> redirect to the toState state with the toState Params

Done :slight_smile: