Friday, April 29, 2016

ng-repeat in Angularjs

It is quite common to display records in grid format in applications. In this article, we will discuss how we can do this in angular js.

Angular js uses the concept of directives(which extends the html attributes), to bind data to records which can be displayed in html controls. In this discussion, we will see how we can use the ng-repeat directive in angular js to display data in grid format.

To start with, we will create a angular controller and add some data in an array. So our code will look like the following:


var app = angular.module("myApp", []);  
        app.controller('ngRepeatExampleController', function ($scope, $http) {  
  
            $scope.Users = [];  
  
            $scope.Users.push({ UserId: 1, UserName: 'User X' });  
            $scope.Users.push({ UserId: 2, UserName: 'User Y' });  
            $scope.Users.push({ UserId: 3, UserName: 'User Z' });  
  
        });  

Next step is to bind the controller we created, with a parent div in html. For this we use ng-controller directive. To bind the data in the table format from the array, we will apply the ng-repeater element at the table row level. It will be simply how we use the foreach loop in C#. The difference is that we do not have an intellisense help here. So our code will look like the following:


 <div ng-app="myApp" data-ng-controller="ngRepeatExampleController">  
       <table border="1" style="width: 200px">  
           <thead>  
               <th>User Id</th>  
               <th>User Name</th>   
           </thead>  
           <tr data-ng-repeat="User in Users">  
               <td>{{ User.UserId }}</td>  
               <td>{{ User.UserName }}</td>   
           </tr>  
       </table>   
   </div>  

Run the application and we can see the data getting displayed in grid format.


Hope you enjoyed reading it. Happy coding...!!!

No comments:

Post a Comment