我有这样的数组
$scope.orderno=[
{"orderno":1254,"weight":25875,"group":5},
{"orderno":56787,"weight":25875,"group":5},
{"orderno":567,"weight":25875,"group":3},
{"orderno":123254,"weight":25875,"group":3}
];
现在我想以如下所示的html格式显示
我试过了但是没办法。我在下面附上了我试过的代码。
<div ng-app>
<table ng-controller="MainCtrl">
<thead>
<div>
<tr>
<td>orderno</td>
<td>weight</td>
<td rowspan={{orderwt}}>group</td>
</tr>
</div>
</thead>
<tbody ng-repeat="item in orderno">
<tr>
<td></td>
<td></td>
<td rowspan="{{orderno.length}}">{{item.group}}</td>
</tr>
<tr>
<td>{{item.orderno}}</td>
<td>{{item.weight}}</td>
</tr>
</tbody>
</table>
</div>
我尝试过,但找不到正确答案
答案 0 :(得分:1)
您应该做的第一件事是将您的数据转换为更易于迭代的格式。例如,您可以使用array.reduce()
帮助您创建一个新的对象,该对象以组号为键。然后,您可以遍历此对象以创建表。
请参阅下面的示例片段,并附上注释:
// This is your original data array
let arr = [{
"orderno": 1254,
"weight": 25875,
"group": 5
},
{
"orderno": 56787,
"weight": 25875,
"group": 5
},
{
"orderno": 567,
"weight": 25875,
"group": 3
},
{
"orderno": 123254,
"weight": 25875,
"group": 3
}
], // Use reduce and Object.create to make a new object keyed by group number
result = arr.reduce(function(r, a) {
r[a.group] = r[a.group] || [];
r[a.group].push(a);
return r;
}, Object.create(null));
let app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.groups = result;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<table border="1">
<thead>
<td>Group</td>
<td>Order No</td>
<td>Weight</td>
</thead>
<tbody ng-repeat="(key, value) in groups"> <!-- Outer loop -->
<tr ng-repeat="group in value"> <!-- Inner loop -->
<td ng-if="$index == 0" rowspan="{{ value.length }}">{{ group.group }}</td>
<!-- the above is so we only add the rowspan once -->
<td>{{ group.orderno }}</td>
<td>{{ group.weight }}</td>
</tr>
</tbody>
</table>
</div>