1) 按主题对数据进行分组
首先您需要将数据按subject 分组,然后计算每个组中的项目。
您可以使用 angular.filter 模块的 groupBy 过滤器来执行此操作。
1a) 添加对该模块的依赖,如下所示:
var app = angular.module("yourModuleName", ["angular.filter"]);
1b) 然后,您可以在 ng-repeat 指令中对 <tbody> 标记使用 groupBy 过滤器,如下所示:
<tbody ng-repeat="(key, value) in data | groupBy: 'subject'">
1c) 您现在正在处理以下格式的数据。这是key/value 对的对象,其中"maths" 和"history" 都是keys,数组是values
{
"maths": [
{
"rollno": 1,
"name": "abc",
"subject": "maths",
}
],
"history": [
{
"rollno": 4,
"name": "xyz",
"subject": "history",
},
{
"rollno": 2,
"name": "pqr",
"subject": "history",
}
]
}
2) 显示分组数据并统计每组中的项目
使用key 和value 在表格中显示分组数据,如下所示:
<table>
<thead>
<tr>
<th>Subject</th>
<th>Number of Students</th>
<th>Expand/Collapse</th>
</tr>
</thead>
<tbody ng-repeat="(key, value) in data | groupBy: 'subject'">
<tr>
<td>{{ key }}</td>
<td>{{ value.length }}</td>
<td>
<button>
Expand/Collapse
</button>
</td>
</tr>
<tr>
<td colspan="3">
<table>
<thead>
<tr>
<th>Roll Number</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="student in value">
<td>{{ student.rollno }}</td>
<td>{{ student.name }}</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
注意额外的<tr> 和嵌套表与另一个ng-repeat 用于显示学生数据。目前将显示所有嵌套的学生数据,下一步是根据单击的展开/折叠按钮有条件地显示/隐藏嵌套表。
3) 显示/隐藏嵌套的学生数据
3a) 在按钮上添加一个ng-click 指令,以便它将key 传递给控制器上的onExpandClicked 函数:
<button ng-click="onExpandClicked(key)">
Expand/Collapse
</button>
3b) 在控制器中创建onExpandClicked 函数:
$scope.onExpandClicked = function(name){
$scope.expanded = ($scope.expanded !== name) ? name : "";
}
这会在$scope 上设置一个值,该值可在视图中用于决定是否显示/隐藏学生数据的一部分。 key 作为name 参数传递到函数中,$scope.expanded 将设置为name 或重置为"",具体取决于传入的name 是否与当前@987654354 相同@值与否。
3c) 最后,在<tbody> 的第二个<tr> 标记上的ng-if 指令中使用$scope.expanded 变量来显示或隐藏嵌套的学生数据:
<table>
<thead>
<tr>
<!-- Omitted for brevity -->
</tr>
</thead>
<tbody ng-repeat="(key, value) in data | groupBy: 'subject'">
<tr>
<!-- Omitted for brevity -->
</tr>
<tr ng-if="expanded === key">
<!--
Omitted for brevity
-->
</tr>
</tbody>
</table>
演示
CodePen: How to show/hide grouped data created by the angular.filter module's groupBy filter