Angular UI bootstrap tabs - Can't change tabs

2020-03-26 05:27发布

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>

2条回答
兄弟一词,经得起流年.
2楼-- · 2020-03-26 05:35

Reasonably sure there is some miscommunication between the two scopes on the page (uib-tabset is likely creating it's own scope that doesn't track your scopes active variable as well as we might like).

Check out this working plunker - you'll note it uses ctrl as syntax to more explicitly define which scopes variable to set with ng-click.

Here is a question regarding 2-way-binding issues within the uib-tabset scope found here that is the likely cause of the issue. I would suggest using ctrl as or you could bind to a $scope function to set $scope.active instead of binding to the active variable itself.

查看更多
可以哭但决不认输i
3楼-- · 2020-03-26 05:36

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>
查看更多
登录 后发表回答