Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  126] [ 7]  / answers: 1 / hits: 99586  / 11 Years ago, thu, may 2, 2013, 12:00:00

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.


More From » angularjs

 Answers
31

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();
}
});

[#78470] Tuesday, April 30, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
Thu, Mar 31, 22, 00:00, 2 Years ago
Thu, Jul 1, 21, 00:00, 3 Years ago
Sat, Dec 12, 20, 00:00, 4 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
;