How to Set Bootstrap Navbar Active Class with Angular Js

How to set bootstrap navbar active class with Angular JS?

A very elegant way is to use ng-controller to run a single controller outside of the ng-view:

<div class="collapse navbar-collapse" ng-controller="HeaderController">
<ul class="nav navbar-nav">
<li ng-class="{ active: isActive('/')}"><a href="/">Home</a></li>
<li ng-class="{ active: isActive('/dogs')}"><a href="/dogs">Dogs</a></li>
<li ng-class="{ active: isActive('/cats')}"><a href="/cats">Cats</a></li>
</ul>
</div>
<div ng-view></div>

and include in controllers.js:

function HeaderController($scope, $location) 
{
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
}

How to set Bootstrap navbar active class in Angular 2?

If you use the new 3.0.0. component router ( https://github.com/angular/vladivostok ) you can use the routerLinkActive directive. No further javascript required.

<ul class="nav navbar-nav">
<li [routerLinkActive]="['active']"> <a [routerLink]="['one']">One</a></li>
<li [routerLinkActive]="['active']"> <a [routerLink]="['second']">Second</a></li>
</ul>

I used "@angular/router": "^3.0.0-alpha.7"

add Bootstrap active class based on route change in Angular

Since we found what was wrong in the comments I'll take the time to write an answer for future reference, The problems were:

- spelling error in controller, changed $rootscope into $rootScope,

- wrong use of ng-class syntax, removed nav-item.

- mistake in the expression of ng-class, location==='#!/path' changed into location==='/path'.

Kudos to @dfsq

AngularJS set initial active class

All you have to do is put an ng-class directive on the tab and tab pane that you would like active initially. You can change the expression from $index == 0 in the ng-class directive to whatever you would like. This could use a function or variable in your scope.

Here is a JS Fiddle showing how to do this:
http://jsfiddle.net/digitalzebra/qqPZd/

And here is the final code... notice the ng-class directives:

<div ng-app>
<div ng-init="names = [{name:'one'}, {name:'two'}, {name:'three'}, {name:'four'}, {name:'five'}]">
<ul class="nav nav-tabs">
<li ng-repeat="name in names" ng-class="{active: $index == 0}">
<a href="#tab{{$index + 1}}" data-toggle="tab">Week {{acute.Week}}</a>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in" id="tab{{$index + 1}}" ng-repeat="name in names" ng-class="{active: $index == 0}">
<p>{{$index + 1}}</p>
</div>
</div>
</div>
</div>


Related Topics



Leave a reply



Submit