Is it possible to listen for route changes AND onwindowunload both to confirm page leave without saving changes?
Use cases:
If the user clicks 'cancel' stop the page / route change.
I've seen a few different examples but none worked quite right.
In order to detect route change at any moment in AngularJS, this can be achieved by using the $on() method. The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/view change is done. Syntax: $rootScope.
Demo: http://plnkr.co/edit/Aq8uYg
In the demo, if you change the value of input, you will be noticed when trying to go back.
Listen to $locationChangeStart
and use event.preventDefault()
to cancel the location change if changes not confirmed.
This method has one advantage over $route.reload()
: current controller and models will not be re-instantiated. thus all of your variables are kept the same as user click the "Back" button.
You'll find the $locationChangeStart
is an event you can listen for to detect for a route change.
Try something like
$rootScope.$on('$locationChangeStart', function (event, next, current) {
/* do some verification */
});
$route.reload()
will prevent the route change from going through.
The distinction between user clicking back or changing the url etc will not make a difference. As browsers don't reload any resources when you alter the url past the #
it's all still contained in your angular logic. This means all these methods should trigger the $locationChangeStart
event.
@Jon pointed out that the $route
service will definitely be of use to you. the .reload()
method will prevent the route change from completing but there is much more you can do with the $route
service if you look into it - see documentation.
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