Rajesh GK
Rajesh GK

Reputation: 67

ng-repeat loop through object is not behaving properly

In my Angularjs ng-repeat is have following only one object, fields are reduced actually i have more than 40 in this object. if i have 40 fields then 40 empty output is rendering (see below outout).

{"Name": "Raj", "Gender":"M", "Country": "India"} (ONLY ONE OBJECT)

Angular View

<table ng-repeat="emp in model.Employee">
<tr>
<td><strong>Name:</strong></td>
<td>{{emp.Name}}</td>
</tr>
<tr>
<td><strong>Gender:</strong></td>
<td>{{emp.Gender}}</td>
</tr>
</table>

Excepted output is

Name: Raj 
Gender: M

But the actual out put is rendering three time without value.

Name: 
Gender: 

Name: 
Gender: 

Name: 
Gender: 

Upvotes: 0

Views: 68

Answers (2)

Hadi
Hadi

Reputation: 17289

you can use (key,value) for this purpose.

var app = angular.module("app",[])
app.controller('ctrl',['$scope', function($scope){
        $scope.data ={"Name": "Raj", "Gender":"M", "Country": "India"};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
<div class="item item-checkbox">
      <table >
<tr ng-repeat="(key,value) in data" ng-if="key != 'Country'">
  <td>{{key}}</td>
<td>{{value}}</td>
</tr>
</table> 
</div>

Upvotes: 0

Tarun Dugar
Tarun Dugar

Reputation: 8971

This is happening because you are iterating over an object instead of an array. So, the ngRepeat loop will run as many times as there are keys in your object. Since, there are three keys in the object, the loop is being run thrice. Also, emp(the iterable) is the key('Name', 'Gender', 'Country') instead of the complete object.

Change to :

[{"Name": "Raj", "Gender":"M", "Country": "India"}]

Upvotes: 2

Related Questions