I have a form-like page with some data. And want to show a popup/alert when a user clicks the browser back button, asking \"if they want to go back or stay on the same page\
Similar to syraz37's answer, but for the new $transition
API:
angular
.module('app')
.run(function($rootScope, $transitions) {
// Track "previous state" to be used elsewhere to determine if the user
// goes "back".
$transitions.onStart({}, (transition) => {
if ($rootScope._previousState === transition.$to().name) {
$rootScope._isPreviousState = true;
} else {
$rootScope._isPreviousState = false;
}
$rootScope._previousState = transition.$from().name;
});
});
Then in any controller, you can check if it's being loaded as the "previous state":
if ($rootScope._isPreviousState) {
// ...reload some aspect of the controller state...
}
This falls to the caveat pointed out by ninjaPixel above where you could go to state A, then state B, then state A again (all in a forward direction) and it would think the user has gone "back", but for our needs this works.