在AngularJS中,要实现数据的分组和行跨度,可以使用ng-repeat
指令结合自定义的过滤器和样式
angular.module('myApp', []).filter('groupBy', function () {
return function (items, field) {
var groups = {};
var result = [];
angular.forEach(items, function (item) {
var groupKey = item[field];
if (!groups[groupKey]) {
groups[groupKey] = [];
}
groups[groupKey].push(item);
});
angular.forEach(groups, function (groupItems, groupKey) {
result.push({
groupKey: groupKey,
items: groupItems,
});
});
return result;
};
});
ng-repeat
遍历经过分组的数据,并使用rowspan
属性来实现行跨度。<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="myController">
<table border="1">
<tr ng-repeat-start="group in data | groupBy: 'groupField'">
<td rowspan="{{group.items.length}}">{{group.groupKey}}</td>
<td>{{group.items[0].name}}</td>
</tr>
<tr ng-repeat-end ng-repeat="item in group.items.slice(1)">
<td>{{item.name}}</td>
</tr>
</table>
</body>
</html>
angular.module('myApp').controller('myController', function ($scope) {
$scope.data = [
{ groupField: 'A', name: 'Item 1' },
{ groupField: 'A', name: 'Item 2' },
{ groupField: 'B', name: 'Item 3' },
{ groupField: 'B', name: 'Item 4' },
{ groupField: 'C', name: 'Item 5' },
];
});
领取专属 10元无门槛券
手把手带您无忧上云