使用ng-show时,ui-bootstrap选项卡显示错误的选项卡内容

时间:2016-05-15 05:52:31

标签: angularjs angular-ui-bootstrap angular-ui-bootstrap-tab

我有标签,其中一些是ng-show动态显示的标签。问题是如果未显示第一个选项卡,则第二个选项卡应为活动选项卡。但这不是这样的。似乎第一个选项卡仍处于活动状态,导致选项卡1内容位于选项卡2中。

enter image description here

首次加载标签时,我需要的是以下内容

enter image description here

在下面的代码中,如果我为active="1"设置了ui-tabset,那么它会按预期工作

<uib-tabset active="1">

但我不能这样做,因为这需要是动态的。可以显示或不显示第一个标签。我试图为active属性使用绑定值(如下面的代码所示),但这不起作用。它仍然与上面的第一张图片具有相同的结果。

我有以下MCVE(也是Plunker

HTML

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
    <script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.3.2.min.js"></script>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>
  <body ng-app="exampleApp">
    <div ng-controller="TabsDemoCtrl">
      <uib-tabset active="initialActive">
        <uib-tab ng-repeat="tab in tabs" heading="{{tab.title}}" ng-show="tab.show" 
                 active="tab.active" index="$index">
          {{tab.content}}
        </uib-tab>
      </uib-tabset>
    </div>
  </body>
</html>

脚本

angular.module('exampleApp', ['ui.bootstrap'])
  .controller('TabsDemoCtrl', function($scope) {

    $scope.tab1Show = false;
    $scope.initialActive = $scope.tab1Show ? "0" : "1";

    $scope.tabs = [
      { title: 'Tab 1', content: 'Tab 1 Content', active: false, show: $scope.tab1Show },
      { title: 'Tab 2', content: 'Tab 2 Content', active: true, show: true },
      { title: 'Tab 3', content: 'Tab 2 Content', active: false, show: false },
      { title: 'Tab 4', content: 'Tab 2 Content', active: false, show: true },
      { title: 'Tab 5', content: 'Tab 2 Content', active: false, show: true }
    ];

  });

修改

标签content中存在拼写错误,但它并不会真正影响问题和结果,因为问题实际上只与标签2内容有关,这是正确的。

2 个答案:

答案 0 :(得分:2)

使用ng-if代替ng-show Plunker

  <uib-tabset active="initialActive">
    <uib-tab ng-repeat="tab in tabs" heading="{{tab.title}}" index="$index" ng-if='tab.show'>
      {{tab.content}}
    </uib-tab>
  </uib-tabset>

答案 1 :(得分:1)

使用ng-if代替ng-showng-show只隐藏其他标签(标签2之前的标签),而实际上它们已经被渲染到dom中。

根据ui-tabs的实现,渲染到dom中的第一个选项卡是活动的选项卡。因此,第一个呈现的li [tab item]是活动的,并且css类active应用于它 - 这为活动状态创建了良好的边界,如下所示。

enter image description here

当你使用ng-show时,该项被创建,应用了active css类,然后由于ng-show(它在该元素上应用了一个css类而被隐藏)除了应用规则display: none !important)之外什么都不做。

ng-if确保元素没有被渲染到dom中,因此渲染的第一个元素是tab 2,并且之前没有其他元素,所以逻辑上active class附加到它上面,你会看到预期的边框和设计。