Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs - cancel route change event

How do I cancel route change event in AngularJs?

My current code is

$rootScope.$on("$routeChangeStart", function (event, next, current) {  // do some validation checks if(validation checks fails){      console.log("validation failed");      window.history.back(); // Cancel Route Change and stay on current page    } }); 

with this even if the validation fails Angular pulls the next template and associated data and then immediately switches back to previous view/route. I don't want angular to pull next template & data if validation fails, ideally there should be no window.history.back(). I even tried event.preventDefault() but no use.

like image 975
R Arun Avatar asked May 02 '13 17:05

R Arun


People also ask

Which event defined by the route service is triggered after the route has changed?

The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/view change is done.

What event is broadcast if the same instance of a route is being reused?

$routeUpdate Broadcasted if the same instance of a route (including template, controller instance, resolved dependencies, etc.) is being reused. This can happen if either reloadOnSearch or reloadOnUrl has been set to false .

What is route in AngularJS?

Routing in AngularJS is used when the user wants to navigate to different pages in an application but still wants it to be a single page application. AngularJS routes enable the user to create different URLs for different content in an application.


1 Answers

Instead of $routeChangeStart use $locationChangeStart

Here's the discussion about it from the angularjs guys: https://github.com/angular/angular.js/issues/2109

Edit 3/6/2018 You can find it in the docs: https://docs.angularjs.org/api/ng/service/$location#event-$locationChangeStart

Example:

$scope.$on('$locationChangeStart', function(event, next, current) {     if ($scope.form.$invalid) {        event.preventDefault();     } }); 
like image 59
Mathew Berg Avatar answered Oct 13 '22 05:10

Mathew Berg