Reputation: 559
I have an object like below on which I am trying to do ng-repeat and create table
var data = {
"1": [
{
"row": "1",
"name": "Acc"
},
{
"row": "1",
"name": "Eco"
},
{
"row": "1",
"name": "Mono"
},
{
"row": "1",
"name": "Mini"
}
],
"2": [
{
"row": "2",
"name": "Mono"
},
{
"row": "2",
"name": "Eco"
}
]
}
I have tried below code where I want row wise data but all the values are getting displayed column wise http://jsfiddle.net/g92zLqa1/2/
The excepted output is
<!--Expected Output -->
<br/><br/>
<h3><b>Expected Output</b></h3>
<table border="1">
<tr>
<th>1</th>
<th>2</th>
</tr>
<tr>
<td>Acc</td>
<td>Mono</td>
</tr>
<tr>
<td>Eco</td>
<td>Eco</td>
</tr>
<tr>
<td>Mono</td>
<td></td>
</tr>
<tr>
<td>Mini</td>
<td></td>
</tr>
</table>
Any help on this will be really appreciated.
Upvotes: 0
Views: 132
Reputation: 9301
Added logic here :
http://jsfiddle.net/aviboy2006/0pgaLqf2/25/
function TableController($scope) {
let newdata = [];
let tablerow;
let finaltable = [];
for (let key in data) {
let value = data[key];
newdata.push(value.length);
}
console.log(newdata);
let no_of_row = Math.max.apply(null, newdata);
for(i=0;i<no_of_row;i++){
tablerow = [];
for(let key in data){
if(typeof data[key][i] === 'undefined') {
tablerow.push('');
}
else{
tablerow.push(data[key][i]['name']);
}
}
finaltable.push(tablerow);
}
console.log(finaltable);
$scope.finaltable = finaltable;
$scope.rows = data;
}
<div ng-app="" ng-controller="TableController">
<table>
<tr>
<th ng-repeat='(key, value) in rows'>{{key}}</th>
</tr>
<tr ng-repeat='row in finaltable'>
<td ng-repeat='cell in row'>{{cell}}</td>
</tr>
</table>
</div>
Upvotes: 0
Reputation: 33
Remove the nest and use the ng repeat on the array with the longest lengths for the rows and add the table elements using the indexOf the ng-repeat on the Array
<div ng-app="" ng-controller="TableController">
<table>
<tr>
<th ng-repeat='(key, value) in rows'>{{key}}</th>
</tr>
<tr ng-repeat='row in rows.1'>
<td >{{row.name}}</td>
<td >{{rows.2[rows.1.indexOf(row)].name}}</td>
</tr>
</table>
this is assuming your data will only have 2 rows as given, but you can use a variable if there are more
Upvotes: 0