Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can AngularJS listen for $locationChangeSuccess on refresh?

Tags:

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?

like image 309
Jordan Thornquest Avatar asked Apr 24 '13 19:04

Jordan Thornquest


People also ask

What is the purpose of the$ location service in AngularJS?

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.

Which is the function of the$ route service?

$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.

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 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

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());
    });
});
like image 95
Sylvain Avatar answered Sep 17 '22 17:09

Sylvain