AngularJS - Detecting, stalling, and cancelling route changes
Asked Answered
C

3

7

I can see the event $routeChangeStart in my controller, but I don't see how to tell Angular to stay. I need to popup something like "Do you want to SAVE, DELETE, or CANCEL?" and stay on the current "page" if the user selects cancel. I don't see any events that allow listeners to cancel a route change.

Cycloid answered 19/12, 2012 at 22:30 Comment(0)
T
16

You are listening to the wrong event, I did a bit of googling but couldn't find anything in the docs. A quick test of this:

$scope.$on("$locationChangeStart", function(event){
    event.preventDefault();
})

In a global controller prevented the location from changing.

Truculent answered 20/12, 2012 at 1:25 Comment(3)
how to continue changing? For example - show message "Do you want change page?" - Yes - No. On Yes - continue, on "NO" stop.Cutcheon
This is no good if you need access to the routing parameters. Really irritating that the route can't be canceled from the route change start event.Infix
Nope. Does not cancel the route location change at all, AFAICT. The event.preventDefault() appears to do nothing.Patsy
S
2

The documented way of doing this is to use the resolve property of the routes.

The '$route' service documentation says that a '$routeChangeError' event is fired if any of the 'resolve' promises are rejected.1 That means you can use the '$routeProvider' to specify a function which returns a promise that later gets rejected if you would like to prevent the route from changing.

One advantage of this method is that the promise can be resolved or rejected based on the results of asynchronous tasks.

Separates answered 30/1, 2013 at 17:10 Comment(3)
But even when rejected, browser url is changed. How to deal with that?Quantitative
You can change the location back yourself with a service that watches the root scope for $locationChangeSuccess. This is what the $route service uses internally but I don't know if it's completely safe to rely on it staying public in the future. However, you could combine this with $routeChangeError for now to restore the old location. Perhaps it's worth asking the maintainers about.Separates
@Quantitative FYI, the relevant Angular issue to watch is github.com/angular/angular.js/issues/2100Hifalutin
H
0
$scope.$watch("$locationChangeStart", function(event){
    event.preventDefault(); 
});

You can do like this as well. Benefit of doing this way is that it doesn't trigger through if() statement with $on ...as you well see that below code will trigger no matter what the condition is:

if(condition){ //it doesn't matter what the condition is true or false
  $scope.$on("$locationChangeStart", function(event){ //this gets triggered
     event.preventDefault();  
  }); 
}
Hyperkinesia answered 10/2, 2014 at 23:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.