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

我怕爱的太早我们不能终老 提交于 2019-12-01 05:46:33

问题


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>

回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/39860391/angular-ui-bootstrap-tabs-cant-change-tabs-with-a-button-inside-a-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!