【问题标题】:Using ng-repeat with ng-include to create a recursive table使用 ng-repeat 和 ng-include 创建递归表
【发布时间】:2014-09-14 05:26:56
【问题描述】:

我已经做了一些研究,但我似乎找不到递归使用ng-repeat 来创建深层table 的最佳模式。用户 mgdelmonte 有一些值得注意的提及 here 关于该主题,但很遗憾,没有解决方案。

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/

这绝对是我用它最远的地方。它可以很好地遍历树,但是当它向下递归时我丢失了&lt;tr&gt; 标签。相反,它正在渲染&lt;span&gt;s。

我的直觉告诉我,当ng-repeat&lt;div&gt; 上运行时,它为trs 和tds 创建了一个单独的范围,我猜这是非法的(因为它们必须是绑定到table 元素)。

div 更改为tabletbodytr 也是无操作的(我什至不想像那样嵌套表格)。

【问题讨论】:

  • 也许这是一个愚蠢的问题,但您正在使用 &lt;tbody&gt; 元素进行 ng-repeat。那合法吗?我希望&lt;table&gt; 恰好有一个&lt;tbody&gt;,但也许我很笨:) 另一个愚蠢的问题,什么是“深表”?
  • 一点也不笨。表格内的 tbody 和 div 是问题所在。

标签: angularjs ng-repeat angularjs-ng-include


【解决方案1】:

浏览器不喜欢行之间的多个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>

Live Demo - Fiddle

【讨论】:

  • 是的,很好地呼吁 &lt;div&gt; 被插入到 &lt;td&gt; 之外......并且足够好以提供解决方案。
  • 感谢您的回复。然而,这仍然有点不幸,因为我们嵌套了table 元素。考虑一下如果我们在表格上设置边框会发生什么...jsfiddle.net/V9a2Z/1
  • 嗨@Anthony 我知道这已经有一段时间了,但是你会如何处理一张有多个&lt;th&gt; 的桌子呢?您会将包含 ng-include 的 &lt;table&gt; 放在哪里?
猜你喜欢
  • 2017-11-24
  • 2018-03-27
  • 2017-01-17
  • 2017-02-02
  • 2014-10-12
  • 2017-02-11
  • 2014-01-22
  • 1970-01-01
  • 2015-04-17
相关资源
最近更新 更多