I want to change the class of an element when I change the page and use location.path() or something to grab the relevant URL fragment.
I am using $routeProvider for routing. The fiddle doesn't properly show it, but it works fine in my code. The problem I am having is that it does not update when I load the next page.
This code picks up the url fragment I want:
$scope.locationPath = $location.path().replace(/^\/([^\/]*).*$/, '$1');
Here is a very simple JSfiddle: http://jsfiddle.net/timothybone/kmBXv/1/
will's answer is almost right; you have to wrap $location.path()
in a function so it's executed on every digest, not just once:
$scope.$watch(function () {
return $location.path();
}, function() {
return $location.path().replace(/^\/([^\/]*).*$/, '$1');
});
Working fiddle: http://jsfiddle.net/kmBXv/3/
How about something like this?
$scope.$watch($location.path(), function() {
return $location.path().replace(/^\/([^\/]*).*$/, '$1');
}
An alternative to using $watch:
<li ng-class="{active:isActiveRoute('edit')}">edit</li>
<li ng-class="{active:isActiveRoute('list')}">list</li>
Then in your controller:
$scope.isActiveRoute = function(route) {
// I added '/' instead of using a regex to remove it from path()
return '/' + route === $location.path();
};
See also AngularJs: stateful client-side routing, which has a working fiddle.