R
R
rakro2015-05-29 20:30:06
Angular
rakro, 2015-05-29 20:30:06

Active menu item in Angular?

How to correctly assign a class to the active menu item in Angular?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Tartmin, 2015-05-31
@baskerville42

Here is the code for the standard ngRoute

<ul>
    <li ng-repeat="link in menu" ng-class="{ active: isActive(\'{{ link.href }}\') }">
        <a ng-href="{{ link.href }}" href="">{{ link.title }}</a>
    </li>
</ul>

The following services need to be injected into the controller: $scope, $location
$scope.menu = [{
    "title": "title1",
    "href": "href1"
}, {
    "title": "title2",
    "href": "href2"
}, {
    "title": "title3",
    "href": "href3"
}];

$scope.isActive(location) {
    return location === $location.path()
}

The logic is this: with nrRepeat, you knock on the isActive function each time, passing it the link that is used in the menu as an argument. The function checks the current url against the one you passed to it and returns true or false. Next, ngClass substitutes the active class where the isActive function returned true.

_
_ _, 2015-05-29
@AMar4enko

If ui-router and the menu item (or within it) has a ui-sref, then ui-sref-active="desired_class"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question