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

5
我做了一些调查,似乎找不到最佳的模式来递归使用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>

JS代码:

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

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

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

我已经实现了树形遍历,但当递归到下层时会丢失<tr>标签,转而呈现为<span>

我猜测,当ng-repeat运行在那个<div>上时,它为那些trtd创建了一个单独的作用域,这是不合法的(因为必须绑定到table元素)。

div更改为tabletbodytr也不起作用(即使我也不想这样嵌套表)。


也许这是一个愚蠢的问题,但你正在使用<tbody>元素进行ng-repeat。这合法吗?我期望一个<table>只有一个<tbody>,但也许我很傻 :) 另一个愚蠢的问题,什么是“深表”? - Sunil D.
1
一点也不傻。表格中的tbody和div是问题所在。 - Anthony Chu
1个回答

6
浏览器不支持多个 tbody 和行之间的 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>

实时演示 - Fiddle


是的,在<td>之外插入<div>这个想法很好...而且你还友好地提供了解决方案。 - Sunil D.
谢谢回复。然而,这仍然有点不幸,因为我们正在嵌套“table”元素。考虑一下如果我们在表格上放置边框会发生什么... http://jsfiddle.net/V9a2Z/1/ - user2857125
嗨@Anthony,我知道已经有一段时间了,但是如果有一个带有多个<th>的表格,你会怎么做呢?您会将包含ng-include的<table>放在哪里? - Hugo Nakamura

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接