Heath Heath - 1 year ago 77
AngularJS Question

$location not updating after each URL click

I am trying to get a 'help' section to update based on the URL. That is, if I have url.domain/x I want to show information specific to 'x'. If I have url.domain/y I want to show information specific to 'y'.

I have created a controller for now that uses $location.path() as a trigger to display the right information, however after the first URL loads no subsequent URLs change what $location.path() displays. It is a 'one page' app.

All I want to do for now is to have $location update. I have $location in a controller:

app.controller('ctrl', function($scope, $location) {

$scope.help = $location.path();

And in the view I have this to display $scope.help.

<div ng-controller="crtl">

But it only displays the path of $location on load of whatever page I've chosen first. That is, if I click another link it doesn't update $location.path(). What am I doing wrong? And, is there a better way to achieve what I want?

Answer Source

The Idea:

The missing point is that your assignment in the controller only assigns the value once when the controller is loaded. The assignment has no binding. You need to listen to changes of $location and then assign the new value to your variable help.

The way to do this is as follows:

$scope.$on("$locationChangeSuccess", function() {
        $scope.help = $location.path();


  • You create a listener for the event that location changes
  • In this case you assign your variable help the value of the new locations
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download