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

嘉泰科技

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

在此处输入图片说明

我正在尝试使用ng-repeat获得一个如下所示的表单:

1 - Background
2 - Legal Requirements
2.1 - State Legal Requirements
2.1.1 - Regulations
4 - Quiz
3 - Site Security

我想出了JSFiddle代码,当我运行它时,我遇到了一个无限循环。谢谢您能获得上述结果方面的帮助,在此先感谢您!

我的JsFiddle。JsFiddle

格雷格

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

  1. 在控制器中处理数据以创建嵌套的递归数据结构。
  2. 使用递归ng-include来呈现此嵌套结构

这是标记:

<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, '');
    }
}

您可以在此jsFiddle中看到它的运行情况

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章