Angular Nested array JS ng-repeat
I am trying to iterate over an array using ng-repeat, but I am not getting the correct output.
<table>
<tr>
<th>Index</th>
<th>Items</th>
</tr>
<tr ng-repeat="li in list">
<td ng-repeat="(key,value) in li">{{key}}</td>
<td ng-repeat="(key,value) in li">{{value}}</td>
</tr>
</table>
$scope.list = [
{"foo": ["item1", "item2"]},
{"bar": ["item1", "item2"]}
];
Expected Result:
Index Items
foo item1
foo item2
bar item1
bar item2
Actual conclusion:
Index Items
foo ["item1","item2"]
bar ["item1","item2"]
Anyone can help me print out the exact key, list value.
+3
source to share
2 answers
You can create a custom filter or function that will simplify the result. It will also save you nestedng-repeat
$scope.simplyfiedList = [];
$scope.list.forEach(function(item){
Object.keys(item).map(function(key){
item[key].map(function(i){
$scope.simplyfiedList.push({key: key, value: i});
})
})
});
Html
<table class="table table-responsive">
<tr>
<th>Index</th>
<th>Items</th>
</tr>
<tr ng-repeat="item in simplyfiedList">
<td>{{item.key}}</td>
<td>{{item.value}}</td>
</tr>
</table>
+4
source to share
Given the structure of your data, you probably have to do something like this.
<div ng-repeat="li in list">
<div ng-repeat="(key, itemArray) in li">
<tr ng-repeat="item in itemArray">
<td>{{key}}</td>
<td>{{item}}</td>
</tr>
</div>
</div>
I have not tested it and I would not recommend it. I would rather write a function that flattens the data.
0
source to share