Angularjs ng-repeat example

AngularJS tutorial:

ng-repeat is a angular js directive which is often used to display data in tables. It is widely used directive. It works very much similar to java for each loop.

Syntax:


{{ con.name }} {{ con.capital }}

Here countries is json array defined in app.js.

Lets understand with example .

Copy below text , open notepad , paste it and save it as angularJSExample.html and open it in the browser.




Angular js





Name Captial
{{ con.name }} {{ con.capital }}

app.js

var app = angular.module('myApp', []);
 app.controller('java2blogContoller', function($scope) {

      $scope.countries=
        [
        {"name": "India" , "capital" : "delhi"},
         {"name": "England" , "capital" : "London"},
         {"name": "France" , "capital" : "Paris"},
         {"name": "Japan" , "capital" : "Tokyo"}

      ];

 });

Output:

When you open html file in browser, you will get following output:

Image

Some other properties:

There are some properties which is accessible to local scope which we can use in ng-repeat directly.

Variable
Type
Description
$index
number
It carries index of repeated element
$first

boolean

true if repeated element is first element
$middle
boolean
true if repeated element is middle element
$last
boolean
true if repeated element is last element
$even
boolean
It depends on $index.
true if $index is even
$odd
boolean
It depends on $index.
true if $index is odd

Lets change color of odd and even rows of table using $even and $odd.




Angular js





Name Captial
{{ con.name }} {{ con.name }} {{ con.capital }} {{ con.capital }}

app.js

var app = angular.module('myApp', []);
 app.controller('java2blogContoller', function($scope) {

      $scope.countries=
        [
        {"name": "India" , "capital" : "delhi"},
         {"name": "England" , "capital" : "London"},
         {"name": "France" , "capital" : "Paris"},
         {"name": "Japan" , "capital" : "Tokyo"}

      ];

 });

Output:

When you open html file in browser, you will get following output:

Image

Live demo:

Angular js on jsbin.com

As you can see, we have used $even to check even row and $odd to check odd row. ng-if is another angular directive which is used for checking if condition. We are going to use ng-repeat in many other examples.
Reference: 
https://docs.angularjs.org/api/ng/directive/ngRepeat
[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.