3

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.

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

Given the structure of your data you'd 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 didn't test it and also I wouldnt recommend it. I'd rather write a function that flattens the data.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.