Grouping strings in ngrepeat

I have a json array and I want to create a table from this and want to give a header which is an element of the array. Here is the fiddle showing the script.

<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> 

This will create a simple table with a header from IDTYPE. But I want to group rows with a unique IDTYPE. Therefore, the desired table will be shown in this link .

So, I tried to add the condition ng-show ng-show="$index==0 || items[$index-1].IDTYPE!=items[$index].IDTYPE" , but it does not work properly, as tbody and table will be built for each row. This one is what I tried.

So how to create a table as I wanted in the above description?

+5
source share
1 answer

If you do not want to change the structure of the source data to better fit what you need, you may have to write additional code to change it from javascript. Sort of:

 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]); } } 

From the HTML side, you just need to read the relevant new data:

 <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> 

Fiddle: http://jsfiddle.net/5mpgzdem/

+2
source

Source: https://habr.com/ru/post/1236896/


All Articles