Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS confirm before route change

Is it possible to listen for route changes AND onwindowunload both to confirm page leave without saving changes?

Use cases:

  • User clicks Back
  • User presses back button in browser
  • User types in a different URL

If the user clicks 'cancel' stop the page / route change.

I've seen a few different examples but none worked quite right.

like image 829
amcdnl Avatar asked Dec 30 '13 21:12

amcdnl


People also ask

How to detect route change in AngularJS?

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.


2 Answers

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.

like image 166
Daiwei Avatar answered Oct 14 '22 06:10

Daiwei


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.

like image 12
Lawrence Jones Avatar answered Oct 14 '22 05:10

Lawrence Jones