带角度指令的嵌套树列表

Nested tree list with a directive in angular

本文关键字:嵌套 列表 指令      更新时间:2023-09-26

我在使用Angular的嵌套列表指令时遇到问题。每次我尝试运行代码时,当我递归调用指令时,浏览器都会崩溃。

如果数据中的children属性中有项,我想输出一个新的列表项。

这是我的代码,我删除了对自己的指令调用,这样它就不会破坏浏览器。http://jsfiddle.net/8p3bf4ec/

JS:

var jsonData = {
    "title": "Home",
    "author": "Mary",
    "children": [
        {
            "title": "Clothing",
            "author": "Robert",
            "children": [
                {
                    "title": "Shirts",
                    "author": "Bill",
                    "children": []
                }
            ]
        },
        {
            "name": "Electronics",
            "author": "William",
            "children": []
        }
    ]
};
angular.module('myApp', []);
angular.module('myApp').directive('itemList', function() {
    return {
        scope: true,
        templateUrl: 'itemListTemplate.html',
        controller: function($scope) {
            $scope.nodes = jsonData;
            console.log($scope.nodes);
        }
    };
});

模板:

<div ng-app="myApp">
    <item-list></item-list>
    <script type="text/ng-template" id="itemListTemplate.html">
        <ul>
            <li ng-repeat="node in nodes">
                {{node.title}}
            </li>
        </ul>
        <!-- Removed this because it makes the browser crash
        <item-list></item-list>
        -->
    </script>
</div>

这是因为您无限迭代jsonData,而不是每个节点的子节点。我想您根本不应该在这里使用指令,因为并没有太多的逻辑,它增加了不必要的复杂性。只需使用ng-include而不是directive。类似这样的东西:

<script type="text/ng-template" id="tree-view">
<ul>
    <li ng-repeat="item in items">
        <!-- any data you want to display from item itself -->
        <div
            ng-if="item.children && item.children.length"
            ng-init="items=item.children"
            ng-include="'tree-view'">
        </div>
    </li>
</ul>
</script>
<div class="tree-view" ng-include="'tree-view'"></div>