Monday, August 24, 2015

Ng-Repeat in Angular Js

Ng-Repeat in Angular Js

In this blog, I’m explaining about the ng-repeat directive in angularjs.

Ng-Repeat Directive

The ng-repeat directive clones HTML elements once for each item in a collection. It is very similar to foreach loop.

Step 1:  

First create a javascript file called app.js and create an angular module in it.

var app = angular.module("myApp", []);

Now create an array:

var arr = [
        name: "Steve Benson",
        age: 24,
        designation: ".Net Developer",
        salary : 24000
    }, {
        name: "Mark David",
        age: 26,
        designation: "Java Developer",
        salary: 42000
    }, {
        name: "John Smith",
        age: 32,
        designation: "Php Developer",
        salary: 20000
    }, {
        name: "Mary Jameson",
        age: 22,
        designation: ".Net Developer",
        salary: 28000
    }, {
        name: "Arthur Jones",
        age: 29,
        designation: "Java Developer",
        salary: 30000

Ng-repeat directive will be used to iterate the objects of this array.

Next we will add the controller in app.js file like this:

app.controller("myController", function () {
    this.heading = "Employee Details"
    this.emps = arr;

    this.showSalary = function (emp) {
        alert( + " salary is " + emp.salary);

In this controller, we have two properties first is heading : this will show the heading on our html page and the second is emps : this will have the array.

We also created one method in the controller named showSalary() : this will show the salary of the employee.

Now in our html page add the reference of the angular file and the app.js file like this:

<html ng-app="myApp">
    <title>Ng-Repeat In Angular Js</title>
    <link href="~/bootstrap.min.css" rel="stylesheet" />
    <script src="~/angular.min.js"></script>
    <script src="~/app.js"></script>

Also add the ng-app directive in the <html> tag.

Next in the <body> tag

<body ng-controller="myController as ctrl">
    <div class="well">
        <table class="table">
            <tr ng-repeat="emp in ctrl.emps">
                <td><a href="" ng-click="ctrl.showSalary(emp)">Show Salary</a></td>

In the body tag add the ng-controller and give the name of our controller named “myController” and also gives an alias name “ctrl”, this alias name we will use to reference the “myController”.

In the <tr> tag add the ng-repeat like this:
  <tr ng-repeat="emp in ctrl.emps">
This will iterate the elements of the array one by one.

You can also see that I have used the ng-click directive here:
<td><a href="" ng-click="ctrl.showSalary(emp)">Show Salary</a></td>

When you click the Show  Salary : this will show the salary of the corresponding employee.


Run the application:

And when you click on the Show Salary:

No comments:

Post a Comment