Steps to detect route change in Angular application Urls. Import Router, Event, NavigationStart, NavigationEnd, NavigationError from '@angular/router'. And inject router in the constructor. Subscribe to the NavigationStart, NavigationEnd, NavigationError events of the router.
The $routeParams service allows you to retrieve the current set of route parameters. Requires the ngRoute module to be installed. The route parameters are a combination of $location 's search() and path() . The path parameters are extracted when the $route path is matched.
$stateProvider is used to define different states of one route. You can give the state a name, different controller, different view without having to use a direct href to a route. There are different methods that use the concept of $stateprovider in AngularJS.
Note: This is a proper answer for a legacy version of AngularJS. See this question for updated versions.
$scope.$on('$routeChangeStart', function($event, next, current) {
// ... you could trigger something here ...
});
The following events are also available (their callback functions take different arguments):
See the $route docs.
There are two other undocumented events:
See What's the difference between $locationChangeSuccess and $locationChangeStart?
If you don't want to place the watch inside a specific controller, you can add the watch for the whole aplication in Angular app run()
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.$on("$locationChangeStart", function(event, next, current) {
// handle route changes
});
});
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
//..do something
//event.stopPropagation(); //if you don't want event to bubble up
});
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
//if you want to interrupt going to another location.
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