Programmatically click to change the current tab in UI-Bootstrap

6.9k views Asked by At

I want to activate the tabs programmatically but could not find a way.

Here is a plunker for this. HTML:

<tabset>
<tab id="a1" heading="Static 1">Static 111</tab>
<tab id="a2" heading="Static 2" ng-attr-active="{{nd}}">Static 222</tab>
</tabset>

JS:

$scope.nd = true;

ps:"tabs and their content should not be defined in a js file".

2

There are 2 answers

0
Asqan On BEST ANSWER
        $scope.st = true;
        $scope.nd = false;

       $scope.goToSecond= function () {
            $scope.st = false;
            $scope.nd = true;
        };
        $scope.goToFirst= function () {
            $scope.nd = false;
            $scope.st = true;
        };

where

<tabset>
 <tab heading="Static title" ng-attr-active="st">"; </tab>
 <tab heading="Static 2" ng-attr-active="nd">"; </tab>
</tabset>
2
Neil D'Souza On

I have just struggled for something on similar lines. In fact I almost erroneously drew the conclusion that static tabs cannot be changed programatically. But they can be.

 <tabset>
        <tab heading="Tab 1"  ng-attr-active="tabs[0].active">
              Tab 1 content
        </tab>
        <tab heading="Tab 2"  ng-attr-active="tabs[1].active">
              Tab 2 content
        </tab>
        <tab heading="Tab 3"  ng-attr-active="tabs[2].active">
              Tab 3 content
        </tab>
 </tabset>
 <button ng-click="make_tab3_active()">Make Tab 3 Active </button>

In Javascript you need

$scope.tabs = [{active: true}, {active: false}, {active: false}];
$scope.make_tab3_active = function() {
    $scope.tabs[2].active = true;
}

So just to point out - single variables will not do. They should be in an array - as outlined above. Although the docs give an example on similar lines, it's not clear because the 2 static tabs don't have active on them, and this can confuse you.

I spent a significant amount of time, before finding the answer on this thread: https://github.com/angular-ui/bootstrap/issues/611