邻居列表或无限嵌套列表上的ng-repeat

时间:2015-11-10 22:28:28

标签: angularjs ng-repeat

我正在创建一个重复的标题列表,其中可以包含无限量的嵌套标题。我的测试数据如下:

enter image description here

使用ng-repeat我试图让表单看起来像这样:

WebDriverWait wait = new WebDriverWait(driver, timeOut);
wait.until(ExpectedConditions.elementToBeClickable(locator));

我想出了代码JSFiddle当我运行它时,我得到一个无限循环。感谢您是否可以获得有关如何获得上述结果的帮助,请提前感谢!

我的JsFiddle。 JsFiddle

1 个答案:

答案 0 :(得分:2)

您可以通过以下两个关键步骤完成此操作:

  1. 处理控制器中的数据以创建嵌套的递归数据结构。
  2. 使用递归ng-include呈现此嵌套结构
  3. 这是标记:

    <div ng-controller="mainCtrl">
        <button ng-click="listFn()">Generate list</button>
        <ul>
            <li ng-repeat="heading in headings" ng-include="'subheader'"></li>
        </ul>      
    </div>
    <script type="text/ng-template" id="subheader">
        <span class="number">{{heading.id}}</span>
        <span class="heading">{{heading.text}}</span>
        <ul>
            <li ng-repeat="heading in heading.children" ng-include="'subheader'"></li>
        </ul>
    </script>
    

    这是控制器代码。请注意,我使用功能强大的Lodash库来简化这一过程:

    function mainCtrl($scope) {
        $scope.data = [{
            head_id: 'Background',
            parent_head_id: 0,
            sort_order: 1
        },
        // ... more here ...
        {
            head_id: 'State Legal Requirements',
            parent_head_id: 'Legal Requirements',
            sort_order: 1
        }]
        $scope.listFn = function () {
            var byParentHeadId = _.groupBy($scope.data, 'parent_head_id');
    
            function headingLevel(parent_head_id, levelPrefix) {
                return _.chain(byParentHeadId[parent_head_id])
                    .sortBy('sort_order')
                    .map(function (heading, index) {
                        var id = levelPrefix ? levelPrefix + '.' + (index + 1) : '' + (index + 1);
                        return {
                            id: id,
                            text: heading.head_id,
                            children: headingLevel(heading.head_id, id)
                        };
                    })
                    .value();
            }
    
            $scope.headings = headingLevel(0, '');
        }
    }
    

    您可以在行动in this jsFiddle中看到它。