Thursday, 16 March 2017

How to use ng-repeat directive ?


EXAMPLE 1. ng-repeat
JS
var app = angular.module('module1', []);

app.controller("myController", function ($scope) {
   var employees = [ 

        { name : "Shaan", gender : "Male", salary : 55000 },
        { name : "Renu",  gender : "Female", salary : 80000 },
        { name : "Rahul", gender : "Male", salary : 77000 }
  
]
   $scope.employees = employees;
});


HTML
<body ng-app="module1">
<div ng-controller="myController"> 
  <table>
     <thead>
        <tr> <th>Name</th> <th>Gender/th> <td>Salary</td> </tr>
     </thead>
     <tbody>
        <tr ng-repeat="employee in employees">             
           <td> {{ employee.name }} </td>
           <td> {{ employee.gender }} </td>
 
           <td> {{ employee.salary }} </td>

        </tr>
     </tbody>
  </table> 
</div>


It will display a table with 3 columns : Name, gender and salary with the data


EXAMPLE 2. NESTED ng-repeat
JS
var app = angular.module('module1', []);

app.controller("myController", function ($scope) {
   var courses = [ 

    { name : "BCA",  
      subjects : [
        {name : "Fundamentals"}, {name : "C"}, {name : "C++"}
      ]
    },
    { name : "MCA",  
      subjects : [
        {name : "Java"}, {name : "VB"}, {name : "Oracle"}, {name : "Networking"}
      ]
    },
    { name : "PGDCA",  
      subjects : [
        {name : "DTP"}, {name : "C++"}, {name : "MS Office"}
      ]
    }
   ];
 
   $scope.courses = courses;

});


HTML
<body ng-app="module1">
<div ng-controller="myController"> 
  <ul>
     <li ng-repeat="course in courses">
         {{ course.name }}

        <ul>
          <li ng-repeat="subject in course.subjects">
                {{ subject.name }}
          </li>
        </ul>

     </li>
  </ul>
</div>
It will display main bullet "course name" and sub bullets "subjects" under the courses.




No comments:

Post a Comment

Note: only a member of this blog may post a comment.