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:
After I add a new tab it shows the active one correctly:
When I add another one nothing becomes selected and activeTabIndex variable becomes undefined:
And on the 3rd one it starts working again:
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With