将json中的类似数据分组并使用angularjs

时间:2017-07-12 09:56:22

标签: javascript angularjs json

我有JSON文件,我使用Angular.js获取JSON数据,但我想根据表格显示结果,如下所示。

我的HTML代码和使用Angular的JavaScript代码我正在获取JSON数据:

这是我的JSON文件:

1 个答案:

答案 0 :(得分:0)

您可以获取控制器中所有组的数组,然后使用ngRepeat为这些组呈现tbody标记。然后在嵌套ng-repeat中,您可以使用自定义getGroupedItems filter来迭代这些项目:



var app = angular.module('myApp', []);
app.controller('ctrl', function($scope) {
    $scope.tableData = [
      {
        "name":"Pro-1",
        "histology":"CLL",
        "id":"1"
      },
      {
        "name":"Pro-2",
        "histology":"CLL",
        "id":"2"
      },
      {
        "name":"Pro-3",
        "histology":"DLBCL",
        "id":"30"
      },
      {
        "name":"Pro-4",
        "histology":"CLL",
        "id":"55"
      },
      {
        "name":"Pro-5",
        "histology":"MCL",
        "id":"1255"
      },
      {
        "name":"Pro-4",
        "histology":"DLBCL",
        "id":"55"
      },
    ];
    
    $scope.getGroups = function (data, prop) {
      var groupsArray = [];
      angular.forEach(data, function (item, idx) {
          if (groupsArray.indexOf(item[prop]) == -1) {
              groupsArray.push(item[prop]);
          }
      });
      return groupsArray;
  };
})
.filter('getGroupedItems', function(){
    return function(items, prop, value){       
       return items.filter(function(element, index, array) {
        return element[prop] === value;
       });        
    }        
})

table {
  width: 100%;
  border-collapse: collapse;
}

table thead {
  text-align: left;
  border-bottom: 1px solid #000;
}

table tbody {
  border-bottom: 1px solid #000;
  border-left: 1px solid #000;
  border-right: 1px solid #000;
  border-collapse: separate;
}

table td {
  padding: 5px;
}

table td.group-col {
  vertical-align: top;
  border-right: 1px solid #000;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl"> 
<table>
  <thead>
    <tr>
      <th></th>
      <th>Name</th>
      <th>Id</th>
    </tr>
  </thead>
  <tbody ng-repeat="group in getGroups(tableData, 'histology') track by $index">
    <tr ng-repeat="(ind, item) in (groupedItems = (tableData | getGroupedItems:'histology':group)) track by item.id">
     <td class="group-col" ng-if="ind == 0" rowspan="{{::groupedItems.length}}">{{::group}}</td>
     <td>{{item.name}}</td>
     <td>{{item.id}}</td>
    </tr>
  </tbody>
</table>
</div>
&#13;
&#13;
&#13;