ng-repeat:基于对象中的分组值来渲染表

时间:2016-07-23 18:47:32

标签: angularjs json

我的json数据看起来像这样:

{'A': 'L', 'B': 'L', 'C': 'G', 'D': 'L', 'E': 'G', 'F': 'L' }

我想使用ng-repeat,

绘制这样的表格
L   G
A   C
B   E
D
F

在此,我根据keysvalues进行分组。

这就是我的尝试,但我没有得到我想要的东西。

<table class="table table-hover">
  <thead>
    <tr>
      <th>L</th>
      <th>G</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="(key, val) in intlist track by $index">
      <td ng-if="val=='L'">{{ key }}</td>
      <td ng-if="val=='K'">{{ key }}</td>
    </tr>
  </tbody>
</table>

1 个答案:

答案 0 :(得分:4)

将数据映射到可以重复的新阵列数组,然后在每个单元格内重复

var app = angular.module('angularTest', []);

app.controller('MainCtrl', ['$scope',
  function($scope) {
    var data = {'A': 'L', 'B': 'L', 'C': 'G', 'D': 'L', 'E': 'G', 'F': 'L' };
    
    var tmp = {};
    // map values to arrays of keys in tmp
    for (var key in data) {
      if (!tmp[data[key]]) {
        tmp[data[key]] = [];
      }
      tmp[data[key]].push(key);
    }
    // create array of headings from `tmp` keys
    var headings = Object.keys(tmp);
    // get longest array
    var res = headings
       .reduce(function(a, c) {
            return tmp[c].length > a.length ? tmp[c] : a;          
       }, [])
        // use longest to map results array
       .map(function(_, i) {
            // iterate headings
            return headings.map(function(heading) {
                // return array element if it exists or empty string           
                return tmp[heading][i] || '';
            });
       });

    $scope.headings = headings;
    $scope.list = res;

  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"></script>
<div ng-app="angularTest" ng-controller="MainCtrl">
  <h4>List Data</h4>
  <pre>{{list}}</pre>
  <h4>View Table</h4>   
<table class="table table-hover" border="1">
  <thead>
    <tr>
      <th  ng-repeat="heading in headings">{{heading }}</th>          
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="arr in list">
      <td ng-repeat="item in arr">{{item}}</td>
    </tr>

  </tbody>
</table>
</div>