使用groupBy进行多次ng-repeat

时间:2016-11-04 23:24:28

标签: javascript angularjs json nested ng-repeat

我很困惑如何使用ng-repeat渲染此对象以获得下面所需的结果。

    var object = [{'category':'A', 'subcategory': 'aa', 'status': 'expected', 'points':5},
                  {'category':'B', 'subcategory': 'bb', 'status': 'complete', 'points':10},
                  {'category':'C', 'subcategory': 'c1', 'status': 'expected', 'points':10},
                  {'category':'C', 'subcategory': 'c2', 'status': 'expected', 'points':5},
                  {'category':'C', 'subcategory': 'c3', 'status': 'complete', 'points':10},
                  {'category':'C', 'subcategory': 'c4', 'status': 'complete', 'points':15},
                  {'category':'D', 'subcategory': 'd1', 'status': 'complete', 'points':10},
                  {'category':'D', 'subcategory': 'd2', 'status': 'expected', 'points':15},
                  {'category':'E', 'subcategory': 'ee', 'status': 'complete', 'points':20}];

我想将类似的类别分组,但是单独显示每条记录。

HTML尝试:

    <table class"table">
        <thead>
          <tr>
             <th>Category</th>
             <th>Status</th>
             <th>Points</th> </tr> </thead>
        <tbody>
           <tr ng-repeat="(key, value) in products | groupBy: 'category'">
              <td>{{key}}
                    <!--WANT TO ACHIEVE BELOW-->
                  <div ng-if="multipleLines">{{value.subcategory}}</div></td>

              <td ng-if="multipleLines"></td> <!--LEAVE BLANK IF MULTIPLE LINES OF SAME CATEGORY -->
              <td ng-if="multipleLines"></td> <!--LEAVE BLANK IF MULTIPLE LINES OF SAME CATEGORY -->
              <td ng-if="!multipleLines">{{value.status}}</td>
              <td ng-if="!multipleLines">{{value.points}}</td>

期望的结果:

enter image description here

目前,控制器仅使用promise检索数据。首先,使用ng-repeat这种类型的数据是否有可能实现这一结果?如果是这样,怎么样?如果没有,我将如何分离数据,以便我可以实现所需的表?

提前致谢!

2 个答案:

答案 0 :(得分:1)

我认为使用过滤器组的正确方法是:

<ul ng-repeat="key, value) in products | groupBy: 'category'">
  Group name: {{ key }}
  <li ng-repeat="product in value">
    player: {{ product.subcategory }} 
  </li>
</ul>

答案 1 :(得分:1)

会有更好的方法,但我认为下面的方法也适合你。

<table class="table">
    <thead>
    <tr>
     <th>Category</th>
     <th>Status</th>
     <th>Points</th>
    </tr> 
    </thead>
    <tbody>
    <tr ng-repeat-start="(key, value) in products | groupBy:'category'">
      <td>{{key}}</td>
      <td ng-if="value.length == 1" ng-repeat-start="(k,product) in value">{{product.status}}</td>
      <td ng-if="value.length == 1" ng-repeat-end>{{product.points}}</td>
    </tr>
    <tr ng-if="value.length > 1" ng-repeat-end ng-repeat="product in value">
      <td align="right">{{product.subcategory}}</td>
      <td>{{product.status}}</td>
      <td>{{product.points}}</td>
    </tr>
    </tbody>
    </table>

JS Fiddle