Search code examples
angularjstwitter-bootstrapangularjs-routing

How to determine path/route in AngularJS to indicate current view in menu


I'm writing a small AngularJS app that uses Bootstrap. I'm using Boostraps Nav component and I want to highlight the current page's menu item.

I need to be able to determine the path/route associated with the current view so I can set the CSS class for my Boostrap Nav links.

<ul class="nav navbar-nav">
    <li data-ng-class="{'active': true}">
        <a href="#">Home <span class="sr-only" data-ng-show="false">(current)</span></a>
    </li>
    <li data-ng-class="{'active': false}">
        <a href="#/about">About Us <span class="sr-only" data-ng-show="false">(current)</span></a>
    </li>
    <li data-ng-class="{'active': false}">
        <a href="#/services">Services <span class="sr-only" data-ng-show="false">(current)</span></a>
    </li>
    <li data-ng-class="{'active': false}">
        <a href="#/testimonials">Testimonials <span class="sr-only" data-ng-show="false">(current)</span></a>
    </li>
    <li data-ng-class="{'active': false}">
        <a href="#/contact">Contact <span class="sr-only" data-ng-show="false">(current)</span></a>
    </li>
</ul>

I want to replace the "true/false" values in the data-ng-class of the LI elements to be an expression that evaluates to true when LI matches the currently displayed view, and also data-ng-show evaluates to true under the same circumstances.

Is that the best way to achieve this?


Solution

  • I don't think there is any other way to achieve that. Following is the tentative code.

    Add a function say isActive() in your controller as follows,

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

    In your HTML, replace the true/false value with the function in ng-class as follows,

    <ul class="nav navbar-nav">
        <!-- use the `isActive()` function here in `ng-class` -->
        <li data-ng-class="{'active': isActive('/')}">
            <a href="#">Home <span class="sr-only" data-ng-show="false">(current)</span></a>
        </li>
       <li data-ng-class="{'active': isActive('/about')}">
           <a href="#/about">About Us <span class="sr-only" data-ng-show="false">(current)</span></a>
        </li>
    
        ...
    </ul>
    

    Once please check what is $location.path() is returning in the controller and change the argument value for isActive() function in the HTML code. It will change depending whether you are using html5 mode or not (include # or not).