Handling state transitions with the back button

Hello!

I’m developing an app for my company and I’ve run into an interesting situation. When the app is opened, the user is shown a login screen where they can sign in, unless their login credentials are already stored. If they are already stored, I use something like this

$scope.$on('$ionicView.beforeEnter', function(e) {
	if (typeof $storage.get("apitoken") != "undefined")
		$state.go('home');
});

in the controller for the login page to take them to the dashboard.
The problem, at least on Android, is that a user cannot exit the app by pressing the back button numerous times. If they’ve been already routed to the ‘home’ state, pressing the back button takes them back to the login state-- which immediately routes them back to the ‘home’ state. The user is stuck. What’s the best way to get around this?

Thanks.

What if your application user wants to do that?

Disable hardware back button in your home view:

$ionicPlatform.registerBackButtonAction(function(event) {
	if (true) { // your check here
	  $ionicPopup.confirm({
		title: 'System warning',
		template: 'are you sure you want to exit?'
	  }).then(function(res) {
		if (res) {
		  ionic.Platform.exitApp();
		}
	  })
	}
  }, 100);

Do you see number 100 in the last line of my example? It’s a priority number, depending on the method will prevent different features. If you set it to 101 it will prevent back button change view action on a certain view, or even whole app if used inside a .run(.

You don’t even need to disable it, maybe your user wants to do that. In that case use above code, just don’t forget to clean stored credentials before you change views.

###Click here for a working example plus tutorial.

1 Like

multiple ways, but the easiest way is that:

instead of only $state.go(‘home’) use

$state.go('home', {}, {location: 'replace'});

so the current state gets replaced in state history with the home-view.

1 Like

Thanks for the reply! This seems perfect for me but I can’t get it to work for some reason. I’ll fiddle some more.