Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

My Angular app has several views. The index.html file which has the <div ng-view></div> also has a header/navbar that has links to each of these views.

The $routeProvider is configured to load respective views and their controllers.

Considering this setup, where each of the views has its own controller, how do I add CSS class="active" to the appropriate link in the header when navigating within the app?

Extra Info.: I added ng-click="set_page_id(x)" and ng-class={active: active_page_id === x} to the links and realized there's no controller associated with the index.html. I wrote a jQuery function to make this work by listening to click events but it doesn't work when a view itself calls another view. I wonder if there's a better, Angular way.

share|improve this question
1  
The $rootScope object is recognized on the whole application, including the index.html page. Have you tried using that? –  user3063182 Jul 31 '14 at 22:23
    
If I'm not mistaken, that'll provide me a means to share data betwixt controllers. That can be done using a global variable as well. How do I conditionally do something on the index.html page is my problem. –  Kabir Roy Jul 31 '14 at 22:44

1 Answer 1

up vote 3 down vote accepted

You have your main or nav controller with something like:

app.controller('mainCtrl', function($scope, $rootScope, $location) {

  $scope.menu = [
    {label:'Home', route:'/'},
    {label:'About', route:'/about'},
    {label:'Contact', route:'/contact'}
   ]

  $scope.menuActive = '/';

  $rootScope.$on('$routeChangeSuccess', function(e, curr, prev) {
   $scope.menuActive = $location.path();
});

});

Then

<li ng-repeat="item in menu" ng-class="{active: item.route == menuActive }"><a href="#{{item.route}}" >{{item.label}}</a> </li> 

Heres a Plunker

share|improve this answer
    
Thanks Dylan! Works like a charm. –  Kabir Roy Aug 1 '14 at 21:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.