drozzy drozzy - 3 months ago 40
AngularJS Question

How to highlight a current menu item?

Does AngularJS help in any way with setting an

active
class on the link for the current page?

I imagine there is some magical way this is done, but I can't seem to find.

My menu looks like:

<ul>
<li><a class="active" href="/tasks">Tasks</a>
<li><a href="/actions">Tasks</a>
</ul>


and I have controllers for each of them in my routes:
TasksController
and
ActionsController
.

But I can't figure out a way to bind the "active" class on the
a
links to the controllers.

Any hints?

Answer

on view

<a ng-class="getClass('/tasks')" href="/tasks">Tasks</a>

on controller

$scope.getClass = function (path) {
  return ($location.path().substr(0, path.length) === path) ? 'active' : '';
}

With this the tasks link will have the active class in any url that starts with '/tasks'(e.g. '/tasks/1/reports')

Comments