angularjsangular-ui-bootstrapangular-ui-bootstrap-tab

Angular UI bootstrap tabs - Can't change tabs with a button inside a tab


I'm trying to change my active tab with a button inside the tab directive uib-tabset, but the button is only working OUTSIDE this directive.

What am I doing wrong?

Here's the code:

<button type="button" class="btn btn-default btn-sm" ng-click="active = 0">Select first tab - exterior button</button>

<div class="tabs-container">
    <uib-tabset active="active">
        <uib-tab index="0" heading="tab one">
            tab one
        </uib-tab>
        <uib-tab index="1" heading="tab two">
            tab two
            <button type="button" class="btn btn-default btn-sm" ng-click="active = 0">Select first tab - internal button</button>
        </uib-tab>
        <uib-tab index="2" heading="tab three">
            tab three
        </uib-tab>
    </uib-tabset>
</div>

Solution

  • ng-click within uib-tab directive in your case is trying to write to outer scope primitive variable, but creates local variable with the same name (active) on the local scope, thus breaking connection to outer scope. The easiest way is to add $parent.$parent to your inner click:

    ng-click="$parent.$parent.active = 0"
    

    which will reach correct outer scope (outer scope -> uib-tabset -> uib-tab) and then modify its variable,

    another better solution is to use objects and modify its property (like model.active) when interacting between parent - child scopes:

    <button type="button" 
            class="btn btn-default btn-sm" 
            ng-click="model.active = 0">
      Select first tab - exterior button
    </button>
    
    <div class="tabs-container">
      <uib-tabset active="model.active">
        <uib-tab index="0" heading="tab one">
            tab one
        </uib-tab>
        <uib-tab index="1" heading="tab two">
            tab two
            <button type="button" 
                    class="btn btn-default btn-sm" 
                    ng-click="model.active = 0">
              Select first tab - internal button
            </button>
        </uib-tab>
        <uib-tab index="2" heading="tab three">
            tab three
        </uib-tab>
      </uib-tabset>
    </div>