pbsbr
pbsbr

Reputation: 385

How can I iterate an object using ng-repeat in angular

I am facing problem in iterating an object,in which i have pushed the same property(value) from array of objects.

    {
     id:1,
     id:2,
     id:3
    }

I want to display these id's in different rows of table like: 1 2 3

Any help would be appreciated

Upvotes: 1

Views: 2340

Answers (4)

imazzara
imazzara

Reputation: 430

Try this:

angular.module('myapp', [])
.controller("mycontroller", function($scope) {
    $scope.items = [
      {
        "id": 1        
      }
      ,{
        "id": 2
      }
      ,{
        "id": 3
      }
    ];
  });
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<div ng-app="myapp" ng-controller="mycontroller" class="container">
  <h4>My items</h4>
  <ul class="list-group">
    <li class="list-group-item" ng-repeat="item in items ">{{item.id}}</li>
  </ul>
</div>

Upvotes: 1

htoniv
htoniv

Reputation: 1668

var values = { id:1, id:2, id:3 };
var $scope.objToArr = [];
angular.forEach(values, function(value, key) {
  $scope.objToArr.push(value);
});

in your html

<tr ng-repeat="idval in objToArr">
    <td>{{ idval}}</td>
  </tr>

it works even for different keys also.

Upvotes: 0

Chinni
Chinni

Reputation: 1290

First convert the json object into an array and assign it to a $scope variable and then use ng-repeat to iterate over the array.

Controller code:

var jsonObj = { "id1":1, "id2": 2, "id3": 3 }; // your object

// constructing the array with your object;
$scope.idArray = Object.keys(jsonObj).map(function(k) { return jsonObj[k] });

HTML code:

<table>
    <tr ng-repeat="id in idArray track by $index">
        <td>{{ id }}</td>
    </tr>
</table>

Hope this solves the issue.

Upvotes: 0

Aditi
Aditi

Reputation: 106

Firstly, you can't have the same key repeated in an object. Assuming you have an array of objects called 'idObjects': [{id: 1}, {id: 2}, {id: 3}], you can use ng-repeat on the tr element like this:

<table>
  <tr ng-repeat="idObj in idObjects">
    <td>{{ idObj.id }}</td>
  </tr>
</table>

Upvotes: 1

Related Questions