I am listening for $locationChangeSuccess
in Angular using this code:
$scope.$on('$locationChangeSuccess', function(event) {
console.log('Check, 1, 2!');
});
However, it will only log in the console that the location has changed when I navigate to a new link. Naturally, this makes sense. My question is, how can I make Angular listen for $locationChangeSuccess
in the event that I refresh the page?
The $location service parses the URL in the browser address bar (based on the window. location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.
$route is used for deep-linking URLs to controllers and views (HTML partials). It watches $location. url() and tries to map the path to an existing route definition.
The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/view change is done.
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.
You can't register from within a controller because $locationChangeSuccess occurs before the route is matched and the controller invoked. By the time you register, the event has already been fired.
However, you can subscribe to the event on $rootScope during the application bootstrap phase:
var app = angular.module('app', []);
app.run(function ($rootScope) {
$rootScope.$on('$locationChangeSuccess', function () {
console.log('$locationChangeSuccess changed!', new Date());
});
});
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