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.
The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/view change is done.
$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 .
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.
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(); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With