使用ng-repeat和ng-include创建递归表

use*_*125 5 angularjs ng-repeat angularjs-ng-include

我已经做了一些研究,我似乎无法找到最好的模式来ng-repeat递归使用来创建一个深度table.用户mgdelmonte在这里有一些值得注意的关于这个主题的提及,但是唉,没有解决方案.

HTML和模板:

<body ng-app="myApp">
    <div ng-controller="myAppController">

<script type="text/ng-template"  id="tree_item.html">
    <tr style="width:100%">        
        <td>{{data.name}}</td>
    </tr>
    <div ng-repeat="data in data.nodes" ng-include="'tree_item.html'">

    </div>
</script>

<table class="table table-striped">
     <thead>
        <tr>
            <th style="width:30px;">Test</th>
        </tr>
    </thead>
    <tbody ng-repeat="data in treeData" ng-include="'tree_item.html'">

    </tbody>
</table>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)

JS:

angular.module('myApp', []);

function myAppController($scope) {
    $scope.treeData = [{
        "name": "Root",
        "nodes": [{
            "name": "Level 1",
            "nodes": [{
                "name": "Level 2"
            }]
        }]
    }];
}
Run Code Online (Sandbox Code Playgroud)

这是我的jsfiddle:http://jsfiddle.net/8f3rL/86/

这是我得到的绝对最远的.它可以很好地遍历树,但是<tr>当它递归时,我正在丢失标签.而是它的渲染<span>.

我的直觉告诉我,当它ng-repeat运行时<div>,它正在为那些trs和tds 创建一个单独的范围,我猜这是非法的(因为它们必须绑定到一个table元素).

更改div为a tabletbodyor tr也是no-op(不是我甚至想要像这样嵌套表).

Ant*_*Chu 6

浏览器不喜欢行之间的多个tbodys和div标记.试试这个...

<body ng-app="myApp">
    <div ng-controller="myAppController">

<script type="text/ng-template"  id="tree_item.html">
    <td>{{data.name}}
        <table style="margin-left: 20px">
            <tr ng-repeat="data in data.nodes" ng-include="'tree_item.html'"></tr>
        </table>
    </td>
</script>

<table class="table table-striped">
     <thead>
        <tr>
            <th style="width:30px;">Test</th>
        </tr>
    </thead>
    <tbody>
        <tr style="width:100%" ng-repeat="data in treeData" ng-include="'tree_item.html'"></tr>
    </tbody>
</table>
</div>
Run Code Online (Sandbox Code Playgroud)

现场演示 - 小提琴