1

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.

2
  • 1
    The $rootScope object is recognized on the whole application, including the index.html page. Have you tried using that? Commented Jul 31, 2014 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. Commented Jul 31, 2014 at 22:44

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.