Generate Data using GenFu and binding using nested ng-repeat in AngularJS

Rajnilari2015
Posted by in AngularJS category on for Beginner level | Points: 250 | Views : 736 red flag
Rating: 5 out of 5  
 1 vote(s)

Test data generation is often needed in the project. GenFu is one of such kind of test and prototype data generation library for .NET apps that provides real time value.
In this article, we will look into the data generation using Genfu , exposing that using WebAPI and finally binding the same using AngularJS.


 Download source code for Generate Data using GenFu and binding using nested ng-repeat in AngularJS

Recommendation
Read Read Json and display the records using AngularJS Expression before this article.

Introduction

Test data generation is often needed in the project. GenFu is one of such kind of test and prototype data generation library for .NET apps that provides real time value.

In this article, we will look into the data generation using Genfu , exposing that using WebAPI and finally binding the same using AngularJS.

Using the code

Let us first add GenFu either through the packet manager as under

Install-Package GenFu

Or from the Nuget Package Installer

Let us first create the data structure

public class Employee
{
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public decimal Salary { get; set; }
    public string EmailAdress { get; set; }
    public string PhoneNumber { get; set; }
    public DateTime DOJ { get; set; }
    public List<ResidentialAddress> EmployeeResidences { get; set; }
}

public class ResidentialAddress
{
    public string State { get; set; }
    public string City { get; set; }
    public int ZipCode { get; set; }
}

This is a simple Employee Class which has some scalar properties like EmployeeID,FirstName,LastName,Salary,EmailAdress,PhoneNumber,Date Of Joining (DOJ) and a collection nameEmployeeResidences of type ResidentialAddress. The ResidentialAddress Class again has some scalar properties like State,City,ZipCode.

Now let us write the below code for populating the data using GenFu and exposing of the same using WebAPI

using GenFu;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebAPI2.Controllers
{
    public class EmployeeController : ApiController
    {

        [Route("EmployeeData")]
        public List<Employee> GetEmployeeData()
        {
            var employees = A.ListOf<Employee>(2); //fill two employee records
            var address = A.ListOf<ResidentialAddress>(4); //fill 4 addresses

            Enumerable
                .Range(0, 2)
                .ToList()
                .ForEach
                    (i =>
                        {
                            switch (i)
                            {
                                case 0:
                                    employees[i].EmployeeResidences = address.Take(2).ToList(); //pick up the first 2 addresses
                                    employees[i].DOJ = DateTime.Now.AddYears(-2);
                                    break;
                                case 1:
                                    employees[i].EmployeeResidences = address.Skip(2).Take(2).ToList(); //pick up the last 2 addresses
                                    employees[i].DOJ = DateTime.Now.AddYears(-1);
                                    break;
                            }
                        }
                    );

            return employees;
        }
    }
}

The method A.ListOf

var employees = A.ListOf<Employee>(2);

populates the Employee with some random values. Since we want to populate 2 records, so we specified the number.If not specified, then the value with be 25 by default.We have further associated two records from the Address to the first Employee Record and the 3rd and 4th to the second Employee record.

When we ran this in PostMan, we receive the below JSON

[
    {
        "employeeID": 84,
        "firstName": "Nathaniel",
        "lastName": "Harris",
        "salary": 51.38,
        "emailAdress": "Danielle.Bell@microsoft.com",
        "phoneNumber": "(434) 554-4693",
        "doj": "2014-04-04T11:35:32.8874711+05:30",
        "employeeResidences": [
            {
                "state": " Massachusetts",
                "city": "Laureles",
                "zipCode": 48
            },
            {
                "state": " Ohio",
                "city": "Pomona",
                "zipCode": 21
            }
        ]
    },
    {
        "employeeID": 46,
        "firstName": "Kevin",
        "lastName": "Timms",
        "salary": 85.69,
        "emailAdress": "Ashley.Ratzlaff@hotmail.com",
        "phoneNumber": "(366) 342-5136",
        "doj": "2015-04-04T11:35:32.8874711+05:30",
        "employeeResidences": [
            {
                "state": " Rhode Island",
                "city": "Caddo Mills",
                "zipCode": 13
            },
            {
                "state": " Louisiana",
                "city": "The Hills",
                "zipCode": 58
            }
        ]
    }
]

Now, it's time to consume the web services through AngularJS and to bind the data.

Let us look into the employeeController.js

//creating an application module
var employeeAppModule = angular.module("employeeApp", []);

//The below code will read the data from student.json file and will pass to the $scope variable 
employeeAppModule.controller("EmployeeCtrl", function($scope, $http){ 

			//invoke the service            
            //var promiseGet = $http.get("http://localhost:60422/EmployeeData");

			$http.get("http://localhost:60422/EmployeeData") //reading the data from Web API
			
				.success (function(data){
					console.log(data);
						$scope.employees = data; // binding the data to the $scope variable
					})
				.error(function(data, status) {
  						console.error('failure loading the employee record', status, data);
  						$scope.employees = { }; //return blank record if something goes wrong
				});
				
	});//end controller

The code pattern is a typical MVC one. At first we are creating the employeeAppModule.It is an Application Module that is use to initialize the application with controller which is EmployeeCtrl in our case.

Next we have created a controller module EmployeeCtrl by using the Application Module.controller function (i.e. employeeAppModule.controller).

For reading data from the Web API, we are using $http.get function where in the success case we are setting the data to the $scope.employees variable and if anything goes wrong while reading the data, we are setting the $scope.employees = { } as empty.

The $scope.employees variable acts as a glue for carrying the data from the controller to the view (i.e. html part).

Now comes the binding part.If we observe, we have multiple employee records and for each employee record, we have a collection of employeeResidences. This reminds us to perform a nested looping in the Json data which can be done using nested ng-repeat.

Let us now look into the code

<!DOCTYPE html>
<html>
<head>
  <script data-require="angular.js@1.4.0-beta.6" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js">
  </script> 
 <script src="employeeController.js"></script>
</head>

<body ng-app="employeeApp">
		<div align="center"><b><u><font size="8px">Employee Details</font></u></b></div>
		<div ng-controller="EmployeeCtrl" align="center">  
		<table border="1">
			<tr bgcolor="yellow">					  
			  <td>EmployeeID</td>	
			  <td>FirstName</td>				 
			  <td>LastName</td>
			  <td>Salary</td>
			  <td>Email</td>
			  <td>PhoneNumber</td>
			  <td>Date Of Joining</td>
			  <td colspan="2">Employee Residential Address</td>
			</tr>
			<tr ng-repeat="employee in employees">
			  <td><span>{{employee.employeeID}}</span></td>	
			  <td><span>{{employee.firstName}}</span></td>	
			  <td><span>{{employee.lastName}}</span></td>	
			  <td><span>{{employee.salary}}</span></td>	
			  <td><span>{{employee.emailAdress}}</span></td>	
			  <td><span>{{employee.phoneNumber}}</span></td>					 
			  <td><span>{{employee.doj}}</span></td>
			  <td ng-repeat="a in employee.employeeResidences">
			  	<table border="1">
			  		<tr bgcolor="pink">
			  			<td>State</td>
			  			<td>City</td>
			  			<td>Zip Code</td>
			  		</tr>
			  		<tr>
			  			<td><span>{{a.state}}</span></td>	
			  			<td><span>{{a.city}}</span></td>
			  			<td><span>{{a.zipCode}}</span></td>
			  		</tr>
			  	</table>
			  </td>			  				  
			</tr>				
		</table>
		</div>		
	</body>
</html>

Let us observe the below piece of code

Here, we are looping through the first collection which is employees and inside every employee object, there is the employeeResidences associated with it which again we are looping through using ng-repeat

The final output is as under

References

AngularJS How to Tips & Tricks at Techfunda

AngularJS Developer Guide

Conclusion

Hope this will be helpful. Thanks for reading.Zipped file is attached herewith.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Posted by: Sheonarayan on: 4/6/2016 | Points: 25
What is A here like A.ListOf, is it an object that exists in GenFu namespace?
Posted by: Rajnilari2015 on: 4/6/2016 | Points: 25
@Sheonarayan Sir, yes
Posted by: Sheonarayan on: 4/7/2016 | Points: 25
Great!, nice.
Posted by: Celinachristi on: 4/19/2016 | Points: 25
I have used this approach and I think it's the simplest way to do.

Login to post response

Comment using Facebook(Author doesn't get notification)