maxime1992
maxime1992

Reputation: 23793

UI-bootstrap - Add a tab and select it by default

I'm trying to make a tab system using ui-bootstrap.

It's nearly fine but I'm still having trouble with the last tab when I add one. Adding one tab is OK, but if I want to select it automatically once it's created, I've got a weird behaviour : One tab added : fine One tab added : not selected One tab added : fine One tab added : not selected and so on ...

I've made a plunkr to demonstrate my bug, just click multiple times on the "+" button and have a look to which tab is selected.

Here's the JS code :

angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('TabsDemoCtrl', function($scope) {

  $scope.tabs = [{
    title: 'Dynamic Title 1',
    content: 'Dynamic content 1',
    active: false
  }, {
    title: 'Dynamic Title 2',
    content: 'Dynamic content 2',
    active: false
  }];

  $scope.addTab = function() {
    $scope.tabs.push({
      title: 'Dynamic Title ' + ($scope.tabs.length + 1),
      content: 'Dynamic content ' + ($scope.tabs.length + 1)
    });

    $scope.active = $scope.tabs.length - 1;
  };

});

Here's the HTML code :

  <div ng-controller="TabsDemoCtrl">
    <p>Select a tab by setting active binding to true:</p>
    <p>
      <button type="button" class="btn btn-default btn-sm" ng-click="active = 1">Select second tab</button>
      <button type="button" class="btn btn-default btn-sm" ng-click="active = 2">Select third tab</button>
    </p>
    <p>
      <button type="button" class="btn btn-default btn-sm" ng-click="tabs[1].disabled = ! tabs[1].disabled">Enable / Disable third tab</button>
    </p>
    <hr />

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

    <br /><br />

    <button ng-click="addTab()">plus</button>

  </div>

Any help on this would be nice,

Cheers

Upvotes: 1

Views: 2172

Answers (1)

CHAZTATS
CHAZTATS

Reputation: 114

You have to use a timeout, uibootstrap doesn't technically support dynamically generated tabs.

$timeout(function() {
   $scope.active = $scope.tabs.length - 1;
}, 0);

See this thread. https://github.com/angular-ui/bootstrap/issues/5656

Upvotes: 1

Related Questions