angularjstabsangularjs-scopebootstrap-tabs

angularjs bootstrap tabs are not changing after first time dynamically


<ul class="nav nav-tabs nav-tabs-simple" role="tablist">
  <li class="nav-item">
    <a href="#" ng-class="{active: activeTab =='a'}" data-toggle="tab" role="tab" data-target="#atab">A</a>
  </li>
  <li class="nav-item">
    <a href="#" ng-class="{active: activeTab =='b'}"  data-toggle="tab" role="tab" data-target="#btab">B</a>
  </li>
  <li class="nav-item">
    <a href="#" ng-class="{active: activeTab =='c'}" data-toggle="tab" role="tab" data-target="#ctab">C</a>
  </li>
</ul>

And then the actual tabs:

<div class="tab-pane" ng-class="{'active': activeTab =='main'}" id="atab">
</div>
<div class="tab-pane" ng-class="{'active': activeTab =='main'}" id="btab">
</div>
<div class="tab-pane" ng-class="{'active': activeTab =='main'}" id="ctab">
</div>

So this is working for me the first time, I'm able to switch to the 2nd tab programatically:

$scope.activeTab = 'b';

But when I go back manually to tab 'a' and fire a command which calls the same function the active class remains on the first tab and is not changing programmatically.

So, I want to know what am I doing wrong, and why I'm able to navigate only the first time but not after that.


Solution

  • First, the active class should be applied to the li element, NOT the a anchor tag. Also, you have set all your divs to activate when activeTab is "main", and not the corresponding letters:

    <li class="nav-item" ng-class="{active: activeTab =='a'}">
      <a href="#" data-toggle="tab" role="tab" data-target="#atab">A</a>
    </li>
    
    <div class="tab-pane" ng-class="{'active': activeTab =='a'}" id="atab">
    </div>
    <div class="tab-pane" ng-class="{'active': activeTab =='b'}" id="btab">
    </div>
    <div class="tab-pane" ng-class="{'active': activeTab =='c'}" id="ctab">
    </div>
    

    Secondly, the tab functionality of plain Bootstrap uses jQuery to change classes. jQuery operates completely outside of AngularJS's "digest cycle". This means AngularJS has no control or knowledge over things that happen whey you click the tab headers. This will cause some unexpected behavior.

    That is why this library was created to take full advantage of Bootstrap and AngularJS integration: https://angular-ui.github.io/bootstrap/#!#tabs

    Here is a semi-working example of your code, that illustrates the jQuery/AngularJS digest cycle problems: https://plnkr.co/edit/tBgvPjJ9HVvSj1SIrWhG?p=preview