无法使用嵌套的ng-repeat和ng-if重复正确的项目

时间:2015-02-09 20:10:52

标签: javascript angularjs angularjs-ng-repeat

我有以下html:

            <div ng-repeat="tab in tabs" ng-if="tabIsActive(tab, $index)">

                  <ul ng-repeat="section in tab.sections">

                     <h2 ng-class="productTitle" ng-repeat="child in section.children" ng-if="sideTabIsActive(section, $index)">
                        <img ng-src="{{ child.productImageURL }}"/>
                        <li>{{ child.title }}</li>
                  </ul>
             </div>

这就是&#34;标签&#34; javascript对象看起来像:

Screenshot of tabs object in debugger

我想要的输出是选择该部分时为每个部分列出的子类别标题(例如,children0.title)和图像(例如,children0.productImageURL)。

示例所需输出:

点击分析天平时

 (ML image) //which is section0.child0.productImageURL
 ML         //which is section0.child0.title

 (XS image) //which is section0.children1.productImageURL
 XS         //which is section0.child1ren.title

目前,我显示了这个:

点击分析天平时:

 (ML image) //which is section0.children0.productImageURL
 ML         //which is section0.children0.title

 (XPE image) //which is section1.children0.productImageURL
 XPE         //which is section1.children0.title

如何根据选择的部分(selectedSideIndex)列出每个部分的子项(及相关图像)?

除了上面的HTML,这里还有我在尝试获得所需输出时使用的相关HTML和javascript:

    $scope.toggleSideSelect = function(ind){
            $scope.selectedSideIndex = ind;

    }


$scope.sideTabIsActive = function (tab, $index) {
            var selectedIndexTest = $scope.selectedSideIndex
            return $index==$scope.selectedSideIndex;

}

            <div ng-repeat="tab in tabs" ng-if="tabIsActive(tab, $index)">

                  <ul ng-repeat="section in tab.sections" ng-click="toggleSideSelect($index)">
                     <li>{{ section.title }}</li>
                     <ul  ng-repeat="child in section.children">
                        <li>{{ child.title }}</li>
                     </ul>
                  </ul>
             </div>

1 个答案:

答案 0 :(得分:0)

你几乎就在那里:)

您需要做的是:

<div ng-repeat="tab in tabs" ng-if="tabIsActive(tab, $index)">

        <ul ng-repeat="section in tab.sections" ng-init="sectionIndex = $index">

            <h2 ng-class="productTitle" ng-repeat="child in section.children" ng-if="sideTabIsActive(section, sectionIndex)">
              <img ng-src="{{ child.productImageURL }}"/>
              <li>{{ child.title }}</li>
       </ul>
</div>

这样,使用ng-init="sectionIndex = $index"即可保存该部分的$index,并可在嵌套ng-repeat上使用它。也可以使用$parent.$index,但我不推荐它,因为结构可能会改变,你将留下一个bug。

这样,您可以使用该部分的索引来调用ng-if="sideTabIsActive(section, sectionIndex)",只有您的活动部分的孩子才会显示。

修改:您应该更改

的签名

$scope.sideTabIsActive = function (tab, $index)

$scope.sideTabIsActive = function ($index)

由于您实际上没有在函数中使用tab。 (如果你这样做,也不要忘记从视图中更改对该函数的调用)