Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting active tab on dynamically created tabs with Angular UI Bootstrap

I have a dynamic tabset that generates the tabs from an array which starts out blank. When I add a new item to the array it appears as a new tab. I want the last added tab to be the active one. I set the active index every time I add an item to the array

HTML:

<uib-tabset active="activeTabIndex">
    <uib-tab ng-repeat="tab in tabs" heading="{{tab.title}}">Some content</uib-tab>
</uib-tabset>

JavaScript:

$scope.activeTabIndex = 0
$scope.tabs = [];

$scope.addTab = function() {
    var newTab = {  title: 'Tab ' + ($scope.tabs.length + 1) };
    $scope.tabs.push(newTab); 
    $scope.activeTabIndex = ($scope.tabs.length - 1);
    console.log($scope.activeTabIndex);
};

Here's the Plunk for the full source code of the demo: https://plnkr.co/edit/TX6ek4R62AfM2zUXcoC3?p=preview

The problem is it seems to be working with odd number of tabs only. Here's what I mean:

On initial load it looks like this:

enter image description here

After I add a new tab it shows the active one correctly:

enter image description here

When I add another one nothing becomes selected and activeTabIndex variable becomes undefined:

enter image description here

And on the 3rd one it starts working again:

enter image description here

So for even active index numbers (0, 2) it works fine. But somehow instead of Acitve Index: 1 it shows blank and doesn't set the active tab. I write the variable to console and it displays all the values correctly.

Any help/pointers/ideas are welcome.

Thanks.

like image 242
Volkan Paksoy Avatar asked Apr 05 '16 07:04

Volkan Paksoy


1 Answers

According to docs:

active (Default: Index of first tab) - Active index of tab. Setting this to an existing tab index will make that tab active.

Ensure the tabs array contains the active one, I think you should add a $timeout there:

      $scope.addTab = function() {
        var newTab = {  title: 'Tab ' + ($scope.tabs.length + 1) };
        $scope.tabs.push(newTab); 
        $timeout(function(){
          $scope.activeTabIndex = ($scope.tabs.length - 1);
        });
        console.log($scope.activeTabIndex);
      };

https://plnkr.co/edit/q4QP7zoB0HXSjn3MplE4?p=preview

like image 136
huan feng Avatar answered Oct 17 '22 06:10

huan feng