Set "active" class based on current $location.path

3,013 views
Skip to first unread message

Matias

unread,
May 16, 2012, 2:39:40 PM5/16/12
to ang...@googlegroups.com
Disclaimer: I'm a complete angularjs newbie! Hope you can help me with this simple question.

I have an index.html file with a navigation menu like this:

 <div class="nav-collapse">
                <ul class="nav" ng-controller="NavController">
                    <li class="active">
                        <a href="/search/">Search</a>
                    </li>
                    <li>
                        <a href="/stats/">Stats</a>
                    </li>
                    <li>
                        <a href="/settings/">Settings</a>
                    </li>
                </ul>
</div>
<div id="section-content" ng-view>
</div>

Everything works fine and I can navigate from one section to another, I can even update the url in the navar with the search query if the users runs a search for something, but I can't figure out from the docs or forums which would be the most correct way to set the "active" class in the navigation menu based on the URL or the current section the user is in.

Thanks for your help.


Andy Joslin

unread,
May 16, 2012, 10:26:13 PM5/16/12
to ang...@googlegroups.com
Try putting $location as a $scope instance variable.  Just put in your controller initizliation $scope.location = $location.

Then you can just do this:
<li ng-class="{active: location.path == '/search'}">
  <a href="/search">Search><a/>
</li>
...
Reply all
Reply to author
Forward
0 new messages