Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Detecting, stalling, and cancelling route changes

Tags:

angularjs

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.

like image 442
Jim Cote Avatar asked Dec 19 '12 22:12

Jim Cote


2 Answers

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.

like image 119
Mathew Berg Avatar answered Oct 29 '22 23:10

Mathew Berg


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.

like image 35
tilgovi Avatar answered Oct 30 '22 00:10

tilgovi