AngularJS set initial active class

*爱你&永不变心* 提交于 2020-01-12 05:35:12

问题


I'm using Bootstrap tabs with an Angular ng-repeat.

The problem I'm running into is that the first li and the first div.tab-pane each need an active class. Bootstrap takes care of that after a tab is clicked but, as you can see, not on load.

My question is, how can I set an active class on the first li and div.tab-pane?

Demo:

http://jsfiddle.net/FQgHx/


回答1:


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>


来源:https://stackoverflow.com/questions/16838612/angularjs-set-initial-active-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!