使用rowspan对分层数据进行分组

时间:2014-01-14 01:49:31

标签: javascript angularjs

是否可以在使用angularjs呈现的表中对数据进行分组(使用rows here})。数据是分层的,state有很多counties,每个县有多个zipcodes。我想要一个只包含州,县,邮政等列的表(所以给集合的长度为rowpan)。我不确定ng-repeat-startng-repeat-end可用于实现此目的。请参阅初学者模板here

 <table>
    <thead>
      <tr>
        <th>State</th>
        <th>County</th>
        <th>Zip</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat='st in states'>
        <td>{{st.name}}</td>
        <td></td>
        <td></td>
      </tr>
    </tbody>
  </table>

数据

 var oh_counties = [
    {name: "Franklin", zips: [111,222,333,444,555]},
    {name: "Adams", zips: [111,222,333,444]},
    {name: "Allen", zips: [111,222,333]}
    ],
    wi_counties = [
    {name: "Dane", zips: [111]},
    {name: "Adams", zips: [111,222,333,444]}
    ]

    $scope.states = [
      {name: "OH", counties: oh_counties},
      {name: "WI", counties: wi_counties},
      ];

编辑:

所需输出的手工版本在http://plnkr.co/edit/T7toND0odx6qr8mVC121?p=preview

4 个答案:

答案 0 :(得分:22)

这是Holly Cummins回答的变种。重复会移至tr ng-repeat-startng-repeat-end,以防止tbody被重复。还使用稍微不同的方法来隐藏第一行。

<tbody>
    <tr ng-repeat-start='st in states'>
      <th rowspan="{{st.counties.length}}">{{st.name}}</th>
      <td>{{st.counties[0].name}}</td>
    </tr>
    <tr ng-repeat-end ng-repeat='county in st.counties' ng-hide="$first">
       <td>{{county.name}}</td>
    </tr>
</tbody>

答案 1 :(得分:9)

KayakDave的这个变体的答案通过拉出第一个嵌套行来共享标题的<tr>来改进结构:

<tbody ng-repeat='st in states'>
    <tr>
      <th rowspan="{{st.counties.length}}">{{st.name}}</th>
      <td>{{county[0].name}}</td>
    </tr>
    <tr ng-repeat='county in st. counties' ng-show="$index > 0">
       <td>{{county.name}}</td>
    </tr>
</tbody>

答案 2 :(得分:4)

不确定。就像你想到的那样:

<tbody ng-repeat='st in states'>
    <td rowspan="{{st.counties.length+1}}">{{st.name}}</td>
    <tr ng-repeat='county in st.counties'>
       <td>{{county.name}}</td>
    </tr>
</tbody>

我保持这个例子简单,嵌套2深。但是在下面的小提琴中,我已经嵌套3深(所以它包括拉链)。

demo fiddle

答案 3 :(得分:0)

这可能很有用

<table>
    <tbody ng-repeat='st in states'>
        <tr>
            <th >{{st.name}}</th>
            <td>
                <table>
                    <tr ng-repeat='county in st.counties'>
                        <td>{{county.name}}</td>
                        <td>
                            <table>
                                <tr ng-repeat='zip in county.zips'>
                                    <td>{{zip}}</td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>

    </tbody>
</table>