Heath
Heath

Reputation: 69

$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">
{{help}}
</div>

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?

Upvotes: 1

Views: 102

Answers (1)

Fuzzzzel
Fuzzzzel

Reputation: 1773

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();
});

Explanation:

  • You create a listener for the event that location changes
  • In this case you assign your variable help the value of the new locations

Upvotes: 1

Related Questions