angularjstabsangular-ui-bootstrapangular-ui-bootstrap-tab

Angular UI-Bootstrap tabs: not set active tab


I have this plunkr that have a system to add tabs dynamically.

When I add a new tab, it is setted as active tab. The problem becomes when I add two tabs, clicks on a first tab and add a new tab. With this order, the new inserted tab is not setted as active.

This is the html code:

<div ng-controller="TabsDemoCtrl">
  {{activeTabIndex}}
  <uib-tabset active="activeTabIndex">
    <uib-tab ng-repeat="tab in tabs" index="tab.id">

        <uib-tab-heading>{{ tab.title }} <a ng-click="removeTab(tab.id)" href=''>(del)</a> </uib-tab-heading>

        {{tab.content}}

    </uib-tab>
  </uib-tabset>

  <div ng-controller="BtnCtrl">
    <div class="btn btn-primary" ng-click="addTab()">Add</div>
  </div>

</div>

And the controller:

angular.module('ui.bootstrap.demo', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);

angular.module('ui.bootstrap.demo').controller('TabsDemoCtrl', function ($rootScope, $scope) {

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

  //Close tab
  $scope.removeTab = function(index)
  {
      var tabsLength = $scope.tabs.length -1;

      for (var i=0; i < $scope.tabs.length; i++)
      {
          if ($scope.tabs[i].id == index)
          {
              $scope.activeTabIndex = $scope.tabs[tabsLength].id;
              $scope.tabs.splice(i, 1);

          }
      }
  };

})

angular.module('ui.bootstrap.demo').controller('BtnCtrl', function ($timeout, $scope, $rootScope) {

  //Add new tabs
  $scope.addTab = function()
  {
    var newTab = {
        title: 'new tab',
        content: 'content here',
        id: makeid()
    };

    $rootScope.tabs.push(newTab);

    $timeout(function() 
    {
        $rootScope.activeTabIndex = newTab.id;
    });

  }

  function makeid()
  {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
  }

});

Solution

  • Here is a working plunker: https://plnkr.co/edit/pucttzsZNMvaZJY13IOq?p=preview

    I think the issue is that you are referencing activeTabIndex in your template without $root proceeding it like this:

    active="$root.activeTabIndex"
    

    What this actually equates too, outside of the template is $scope.$root.activeTabIndex which is a convenience method for $rootScope from inside a template. Even though $rootScope is above all other scopes, when you access a variable in a template that's in an isolate scope it's always assumed to be a property of $scope. uib-tab is probably creating an isolate scope which makes $rootScope unavailable to the directive.