Reputation: 29683
Newbie in angularjs
. Trying to learn some new stuffs.
I have a simple page and when the user navigates to different page I need to set active
class on respective li
of the menuitem
. Below is the way I have added routes.
angular.module('home', ["ngRoute"]).
config(function ($routeProvider, $locationProvider) {
$routeProvider.
when('/home', { templateUrl: 'partials/home.html', controller: "homeController", activetab: "home" }).
when('/about', { templateUrl: 'partials/about.html', activetab: "about" }).
when('/gallery', { templateUrl: 'partials/gallery.html', activetab: "gallery" }).
when('/contact', { templateUrl: 'partials/contact.html', activetab: "contact" }).
when('/services', { templateUrl: 'partials/services.html', activetab: "services" }).
when('/house', { templateUrl: 'partials/house.html', activetab: "house" }).
otherwise({ redirectTo: '/home', templateUrl: 'partials/home.html', activetab: "home" });
$locationProvider.html5Mode(true);
}).controller("homeController", function ($scope, $http, $route) {
$scope.$route = $route;
});
And I will have only homecontroller
which is binded only when user visits home page. Other pages will have only static data.
I've added ng-app
to my html
as below:
<html ng-app="home">
Below is how I've tried to add active
class to li
.
<ul class="nav navbar-nav">
<li ng-class="{'active': $route.current.activetab == 'home'}"><a href="home">Home <span class="sr-only">(current)</span></a></li>
<li ng-class="{'active': $route.current.activetab == 'about'}"><a href="about">About</a></li>
<li ng-class="{'active': $route.current.activetab == 'services'}"><a href="services">Services</a></li>
<li ng-class="{'active': $route.current.activetab == 'house'}"><a href="house">The house</a></li>
<li ng-class="{'active': $route.current.activetab == 'gallery'}"><a href="gallery">Gallery</a></li>
<li ng-class="{'active': $route.current.activetab == 'contact'}"><a href="contact">Contact</a></li>
</ul>
But I had no luck in completing this. Even though navigation happens the active class does not gets added. I've followed answer mentioned in this post. Please let me know how else I can achieve this or what is my mistake here?
Upvotes: 2
Views: 3465
Reputation: 1057
try this jsfiddle example I made, the reason it does not work is after you switch state, you do not have access to the $route
. the $route
is only accessible in your homecontroller
's $scope
, which I assume only applying to your home page.
Upvotes: 5