Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS ng-repeat nested array

I am trying to iterate array using ng-repeat, but not getting proper 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 output:

Index   Items
foo    item1
foo    item2
bar    item1 
bar    item2

Actual output:

Index   Items
foo ["item1","item2"]
bar ["item1","item2"]

Anyone help me out to print the exact key,value of list.

like image 521
Udaya Vani Avatar asked Apr 07 '26 19:04

Udaya Vani


1 Answers

You could create an custom filter or function that will simplify the result. That will also get rid of nested ng-repeat's

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

Demo Plunker

like image 115
Pankaj Parkar Avatar answered Apr 09 '26 13:04

Pankaj Parkar