使用angularjs在表中呈现嵌套数据

时间:2016-01-14 23:00:02

标签: html angularjs angularjs-ng-repeat

使用角度1.4.7

我有以下javascript对象

var parents = [
    {"name" : "John", 
         childs:[{ "name" : "Child1", age:"4"},{"name" : "Child2",age:"8"}]},
    {"name" : "Peter", 
         childs:[{ "name" : "Child3", age:"5"},{"name" : "Child", age:"12"}]}
]

我希望将以下输出作为html表



<table>
    <tr>
        <td>John</td>
        <td>Child1</td>
        <td>4</td>
    </tr>
    <tr>
        <td></td>
        <td>Child2</td>
        <td>8</td>
    </tr>
    <tr>
        <td>Peter</td>
        <td>Child3</td>
        <td>5</td>
    </tr>
    <tr>
        <td></td>
        <td>Child3</td>
        <td>12</td>
    </tr>
</table>
&#13;
&#13;
&#13;

我一直在尝试使用ng-repet-start在子循环中插入一个新行(</tr><tr>)。

<tr ng-repeat-start="parent in parents">
    <td >
        {{parent.name}}
    </td>
    <td ng-repeat-start="child in parent.childs">
        {{child.name}}
    </td>
    <td>
        {{child.age}}
<!--new row within child loop and -->
</tr>
<tr>
     <td></td>
     <td ng-repeat-end></td>
<tr ng-repeat-end></tr>

我在控制台中遇到的错误是:

  

未终止的属性,找到&ng-ng-repeat-start&#39;但没有匹配的&#39; ng-repeat-end&#39;找到。

如果我取出</tr><tr>我没有错误,但也没有得到所需的输出。

2 个答案:

答案 0 :(得分:0)

请改为尝试:

$scope.example13model = [items[0], items[4]];

这与您所需的输出的唯一区别是显示所有<tbody ng-repeat="parent in parents"> <tr ng-repeat="child in parent.childs"> <td>{{parent.name}}</td> <td > {{child.name}} </td> <td>{{child.age}}</td> </tr> </tbody> 的{​​{1}}

答案 1 :(得分:0)

此代码几乎可以为您提供所要求的输出(此处有一些额外的<tbody>个标记,但它仍然有效html):

<table>
    <tbody ng-repeat="parent in parents">
      <tr ng-repeat="child in parent.childs">
        <td ng-if = "$index == 0">{{parent.name}}</td>
        <td ng-if = "$index != 0"></td>
        <td >
          {{child.name}}
        </td>
        <td>{{child.age}}</td>
      </tr>
    </tbody>
</table>

这是有效的Plunk

我应该说,实施非常难看。我会用<td rowspan="number_of children">来获得类似的视觉效果。请参阅实现hererowspan和一些引导程序。

<table class = "table table-condensed">
    <tbody ng-repeat="parent in parents">
      <tr ng-repeat="child in parent.childs">
        <td ng-if="$index == 0" rowspan="{{parent.childs.length}}">{{parent.name}}</td>
        <td>
          {{child.name}}
        </td>
        <td>{{child.age}}</td>
      </tr>
    </tbody>
</table>

enter image description here

编辑:已更新Plunker

使用&#39;孙子&#39;

的数据实施很糟糕
$scope.withGrandChildren = [ 
{"name" : "John", 
  childs:[ 
    { "name" : "Child1", 
      age:"42", 
      grandchildrens:[
        {"name":"Graddchildren1_1", age:"12"} , 
        {"name":"Grandchildren1_2", age:"17"}
      ] 
    }, 
    { "name" : "Child2", 
      age:"38", 
      grandchildrens:[
        {"name":"Graddchildren2_1", age:"19"} 
      ] 
    } 
  ]
}, 
{"name" : "Peter", 
  childs:[
    { "name" : "Child3", age:"45"},
    {"name" : "Child", age:"12"}
  ]
} 
]

enter image description here