Javascript 分组ngrepeat中的行
我有一个json数组,我想从中创建一个表,并给出一个标题,它是数组的一个元素。下面显示的是场景Javascript 分组ngrepeat中的行,javascript,css,angularjs,Javascript,Css,Angularjs,我有一个json数组,我想从中创建一个表,并给出一个标题,它是数组的一个元素。下面显示的是场景 <div ng-repeat="products in items"> <div>{{products.IDTYPE}}</div> <div> <table border=1> <thead> <th>primkey</
<div ng-repeat="products in items">
<div>{{products.IDTYPE}}</div>
<div>
<table border=1>
<thead>
<th>primkey</th>
<th>userid</th>
</thead>
<tbody>
<tr>
<td>{{products.PRIMKEY}}</td>
<td>{{products.USERID}}</td>
</tr>
</tbody>
</table>
</div>
{{products.IDTYPE}
普里姆基
用户ID
{{products.PRIMKEY}
{{products.USERID}
这将从IDTYPE创建带有标题的简单表。但是我想用唯一的IDTYPE对行进行分组。因此,所需的表格将如图所示
因此,我尝试添加一个ng show条件ng show=“$index==0 | | items[$index-1].IDTYPE!=items[$index].IDTYPE”
,但它无法正常工作,因为将为每一行构造tbody和table。这就是我尝试过的
那么,如何按照我在上述描述中的要求生成表呢?如果您不希望更改源数据结构以更好地满足您的需要,您可能需要编写一些额外的代码来从javascript方面对其进行更改。比如:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.items = [...]; //your original data
// Here the transformation begins...
$scope.newItems = {};
for (var i = 0; i < $scope.items.length; i++) {
// We'll make it look like a map
// Each IDTYPE will have an array associated to it
if (!$scope.newItems[$scope.items[i].IDTYPE]) {
$scope.newItems[$scope.items[i].IDTYPE] = [];
}
$scope.newItems[$scope.items[i].IDTYPE].push($scope.items[i]);
}
}
var myApp=angular.module('myApp',[]);
函数MyCtrl($scope){
$scope.items=[…];//原始数据
//在这里,转变开始了。。。
$scope.newItems={};
对于(变量i=0;i<$scope.items.length;i++){
//我们会让它看起来像一张地图
//每个IDTYPE都有一个关联的数组
if(!$scope.newItems[$scope.items[i].IDTYPE]){
$scope.newItems[$scope.items[i].IDTYPE]=[];
}
$scope.newItems[$scope.items[i].IDTYPE].push($scope.items[i]);
}
}
在HTML方面,您只需相应地读取新数据:
<div ng-repeat="products in newItems">
<div>{{products[0].IDTYPE}}</div>
<div>
<table border=1>
<thead>
<th>primkey</th>
<th>userid</th>
</thead>
<tbody>
<tr ng-repeat="productItem in products">
<td>{{productItem.PRIMKEY}}</td>
<td>{{productItem.USERID}}</td>
</tr>
</tbody>
</table>
</div>
</div>
{{products[0].IDTYPE}
普里姆基
用户ID
{{productItem.PRIMKEY}
{{productItem.USERID}
小提琴:是的。重组数据将很容易解决问题,但我想知道不重组如何解决问题?@Navaneeth,如果它解决了您的问题,请不要忘记将其标记为有效答案;-)