Manjula D Manjula D - 22 days ago 6
AngularJS Question

Unable to iterate

I have got issue when I work out on the ng-repeat directive, since I am a beginner , unable to resolve it on my own.



var myModule = angular.module("myFirst",[]);

myModule.controller("cont", function($scope){
var employees = [
{name: "Manju", age :"23", rank:"2"},
{name: "SivaSankari", age :"23", rank:"1"},
{name: "Gayathri", age :"23", rank:"1"},
];
$scope.employees = employees;
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="myFirst">
<head>
<title> My workout|ngRepeat
</head>
<body>
<div ng-controller="cont">
<table>
<thead>
<th>Name</th>
<th>Age</th>
<th>Postions</th>
</thead>
<tbody>
<tr ng-repeat="x in employees">
<td>{{employees.name}}</td>
<td>{{employees.age}}</td>
<td>{{employees.position}}</td>
</tr>
</tbody>
</table>

</div>

</body>
<html>





Also I have doubt on key that is x. Is ok to give any key value ?
Can any one please help me to resolve and understand ?
Thanks.

Answer

First

You have to use x instead of employees because employees is your array and x the current item

Second

You were trying to access the property position that is not existing inside your object. You should call rank

var myModule = angular.module("myFirst", []);

myModule.controller("cont", function($scope) {
  var employees = [{
    name: "Manju",
    age: "23",
    rank: "2"
  }, {
    name: "SivaSankari",
    age: "23",
    rank: "1"
  }, {
    name: "Gayathri",
    age: "23",
    rank: "1"
  }, ];
  $scope.employees = employees;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="myFirst">

<body>
  <div ng-controller="cont">
    <table>
      <thead>
        <th>Name</th>
        <th>Age</th>
        <th>Postions</th>
      </thead>
      <tbody>
        <tr ng-repeat="x in employees">
          <td>{{x.name}}</td>
          <td>{{x.age}}</td>
          <td>{{x.rank}}</td>
        </tr>
      </tbody>
    </table>

  </div>

</body>
<html>