angularjsclosuresangular-ui-bootstrapangular-ui-tabset

AngularJS - Set active tabset after delete some one


I have a code that contains a button with a ng-click that when is pressed It add a new tab to the tabs array.

<div class="btn btn-primary" ng-click="add()">Add</div>

$scope.add = function()
  {
     $scope.tabs.push({heading: 'new', content: 'ddddddd'});

     $timeout(function ()
    {
        $scope.active = $scope.tabs.length;
    });
  }

Then, the array is populated and showd in the view:

 <uib-tabset active="active">
    <uib-tab ng-repeat="tab in tabs" index="$index + 1">
      <uib-tab-heading>{{ tab.heading }} - <a ng-click="remove($index)">remove</a></uib-tab-heading>
        {{tab.content}}
      </uib-tab>
  </uib-tabset>

Also, each tab have a remove link that calls this function:

  $scope.remove = function(index)
  {
    $scope.tabs.splice(index, 1);
    $scope.active = $scope.tabs.length;
  }

The problem is that when I delete some tab that is not the last added tab, the active tab and index are not the same. There is a plunkr to demonstrate the problem: http://plnkr.co/edit/02Lll7oPYyvAxcKu5GkK?p=preview As you can see, when a tab (no the last) is deleted, "Tabs" and "Index" variables are not the same.

Any ideas please?


Solution

  • Currently the angular bootstrap doesn't support generating tab dynamically. But if you want $timeout solution worked. you can read more from here

    You need to define one function for timeout which will take care to make tab selected whenever you going to add new tab or remove any existing one. Its take id of the tab which is last one in the tab list.

    function callTimeOut(tabNoIndex) {
    
            $timeout(function() {
              $scope.active = tabNoIndex;
            }, 0);
          }
    

    Your tab array should look like this one with tabNo as closure property. This will track no of tab created till now as uitab does not re-arranged the tab id once it is removed or added.You have to take care of this one.

    $scope.tabs.push({
              heading: 'new',
              content: 'ddddddd',
              id: ++tabNo
            });
    

    Your add and remove function should look like this one.

    $scope.add = function() {
            $scope.tabs.push({
              heading: 'new',
              content: 'ddddddd',
              id: ++tabNo
            });
    
            callTimeOut($scope.tabs.length);
    
          }
    
    
          $scope.remove = function(index) {
            $scope.tabs.splice(index, 1);
    
            var tabIndex = $scope.tabs[$scope.tabs.length - 1].id;
            callTimeOut(tabIndex);
          }
    

    here is the working Plunker