Changing a class in AngularJS using URL data

I want to change the element class when the page changes and use the location.path () file or something to capture the corresponding fragment of the url.

I use $ routeProvider for routing. The violin does not show it properly, but it works fine in my code. The problem I am facing is that it does not update when the next page loads.

This code picks up the url fragment that I want:

$scope.locationPath = $location.path().replace(/^\/([^\/]*).*$/, '$1'); 

Here is a very simple JSfiddle: http://jsfiddle.net/timothybone/kmBXv/1/

0
angularjs
Nov 20 '12 at 2:21
source share
3 answers

the answer will be almost correct; you must wrap $location.path() in a function so that it runs on each digest, and not just once:

 $scope.$watch(function () { return $location.path(); }, function() { return $location.path().replace(/^\/([^\/]*).*$/, '$1'); }); 

Working fiddle: http://jsfiddle.net/kmBXv/3/

+2
Nov 20
source share

How about something like that?

 $scope.$watch($location.path(), function() { return $location.path().replace(/^\/([^\/]*).*$/, '$1'); } 
0
Nov 20
source share

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: client-side routing that has a working script.

0
Nov 20 '12 at 18:20
source share



All Articles