AngularJS CRUD Operations With Web API 2 Using Nhibernate - Part Two

Introduction

In this post, we will learn how we can use AngularJS Framework with Web API2 to call HTTP Services implemented in Part 1. I hope, you will like this.

In this part, we are going to-

  • Implement module, routing, service and controller.
  • Create different HTML pages to perform CRUD operations.

Implement module, routing, service and controller

First of all, we need to add 3 JS files respectively- AppEmployee.js, EmployeeService.js and EmployeeController.js

controller

For doing this, right click on AppEmployee folder> Add > JavaScript file.

controller

AppEmployee.js

  1. var app = angular.module('myApp', ['ngRoute']);  
  2. app.config(['$routeProvider', function($routeProvider) {  
  3.   
  4.     $routeProvider.when('/EmployeeGrid', { //route to get EmployeeGrid.html page  
  5.   
  6.         templateUrl: '/AppEmployee/Views/EmployeeGrid.html',  
  7.         controller: 'EmployeeController'  
  8.   
  9.     }).when('/AddEmployee', { //route to get AddEmployee.html page  
  10.         templateUrl: '/AppEmployee/Views/AddEmployee.html',  
  11.         controller: 'EmployeeController'  
  12.   
  13.     }).when('/EditEmployee/:Id', { //route to get UpdateEmployee.html page  
  14.         templateUrl: '/AppEmployee/Views/UpdateEmployee.html',  
  15.         controller: 'EmployeeController'  
  16.   
  17.     }).when('/DeleteEmployee/:Id', { //route to get DeleteEmployee.html page  
  18.         templateUrl: '/AppEmployee/Views/DeleteEmployee.html',  
  19.         controller: 'EmployeeController'  
  20.   
  21.     }).otherwise({  
  22.         controller: 'EmployeeController'  
  23.     });  
  24. }]);  
  25. // This is just a sample script. Paste your real code (javascript or HTML) here.  
  26.   
  27. if ('this_is' == /an_example/) {  
  28.     of_beautifier();  
  29. } else {  
  30.     var a = b ? (c % d) : e[f];  
  31. }  
In order to ensure routing, we have injected ngRoute module, which gives access to use $routeProvider for configuring routes, as shown above.

Once configuring routes are finished, it’s time to implement all the Services required, which should be used to perform CRUD operations.

EmployeeService.js
  1. app.factory('EmployeeFactory', function($http, $q, $timeout) {  
  2.   
  3.     var factory = {  
  4.   
  5.         EmployeeList: [],  
  6.   
  7.         //Get Employee List  
  8.         getEmployeeList: function() {  
  9.   
  10.             var deferred = $q.defer();  
  11.             $http.get('api/Employee/GetListEmployee').success(function(data) {  
  12.   
  13.                 factory.EmployeeList = data;  
  14.                 $timeout(function() {  
  15.   
  16.                     deferred.resolve(factory.EmployeeList);  
  17.   
  18.                 }, 2000);  
  19.             }).error(function() {  
  20.   
  21.                 deferred.reject('Error !');  
  22.   
  23.             });  
  24.   
  25.             return deferred.promise;  
  26.         },  
  27.   
  28.         //Add New Employee  
  29.         addNewEmployee: function(newEmployee) {  
  30.   
  31.             var deferred = $q.defer();  
  32.             $http.post('api/Employee/AddNewEmployee', newEmployee).success(function(data) {  
  33.   
  34.                 deferred.resolve(newEmployee);  
  35.   
  36.             }).error(function() {  
  37.                 deferred.reject('Error !');  
  38.             });  
  39.   
  40.             return deferred.promise;  
  41.   
  42.         },  
  43.   
  44.         //Details Employee  
  45.         detailsEmployee: function(id) {  
  46.   
  47.             var deferred = $q.defer();  
  48.             $http.get('api/Employee/DetailsEmployee/' + id).success(function(data) {  
  49.   
  50.                 $timeout(function() {  
  51.   
  52.                     deferred.resolve(data);  
  53.   
  54.                 }, 2000);  
  55.   
  56.             }).error(function() {  
  57.                 deferred.reject('Error !');  
  58.             });  
  59.   
  60.             return deferred.promise;  
  61.   
  62.         },  
  63.         //Update Employee  
  64.         updateEmployee: function(Employee) {  
  65.   
  66.             var deferred = $q.defer();  
  67.             $http.put('api/Employee/UpdateEmployee', Employee).success(function(data) {  
  68.   
  69.                 deferred.resolve(data);  
  70.   
  71.             }).error(function() {  
  72.                 deferred.reject('Error !');  
  73.             });  
  74.   
  75.             return deferred.promise;  
  76.   
  77.         },  
  78.   
  79.         //Delete Employee  
  80.         deleteEmployee: function(id) {  
  81.   
  82.             var deferred = $q.defer();  
  83.             $http.delete('api/Employee/DeleteEmployee/' + id).success(function(data) {  
  84.   
  85.                 deferred.resolve(data);  
  86.   
  87.             }).error(function() {  
  88.                 deferred.reject('Error !');  
  89.             });  
  90.   
  91.             return deferred.promise;  
  92.         }  
  93.   
  94.   
  95.     };  
  96.     return factory  
  97.   
  98. });  
For implementing services, I have chosen Factory but you can also use Service or provider to achieve our requirement.

 Function Description
 getEmployeeList()  It Is used to retrieve all the data from the database table.
 addNewEmployee()  It Is defined to add new employee in our database.
 detailsEmployee(id)  Performs to get back data related to each employee. This function takes an Id as a parameter.
 updateEmployee()  It Is used to modify information’s employee.
 deleteEmployee(id)  This function deletes an employee, based on his Id.

Note 
  • $http- It is a core Angular Service, which facilities the communication with the remote HTTP Servers via the Browser’s XMLHttpRequest object or via JSONP.
  • $q- It helps you to run functions asynchronously and use their return values (or exceptions), when they are done processing.

EmployeeController.js

  1. app.controller('EmployeeController', ['$scope', 'EmployeeFactory', '$location', '$routeParams', function($scope, EmployeeFactory, $location, $routeParams) {  
  2.   
  3.     $scope.EmployeeList;  
  4.   
  5.   
  6.   
  7.     //Get all Employee  
  8.     EmployeeFactory.getEmployeeList().then(function(data) {  
  9.   
  10.         $scope.EmployeeList = data;  
  11.     }, function(msg) {  
  12.   
  13.         console.log(msg);  
  14.   
  15.     });  
  16.   
  17.     //Add new Employee  
  18.     $scope.AddNewEmployee = function() {  
  19.   
  20.         var employee = {  
  21.             FirstName: $scope.FirstName,  
  22.             LastName: $scope.LastName,  
  23.             Gender: $scope.Gender,  
  24.             Designation: $scope.Designation,  
  25.             Salary: $scope.Salary,  
  26.             City: $scope.City,  
  27.             Country: $scope.Country  
  28.         };  
  29.         //debugger;  
  30.   
  31.         EmployeeFactory.addNewEmployee(employee).then(function(data) {  
  32.   
  33.             $location.path('/EmployeeGrid');  
  34.   
  35.         }, function() {  
  36.             console.log('Error');  
  37.         });  
  38.   
  39.     };  
  40.   
  41.     //mapping Employee  
  42.     function mappingEmployee(employee) {  
  43.   
  44.         $scope.EmployeeID = employee.EmployeeID;  
  45.         $scope.FirstName = employee.FirstName;  
  46.         $scope.LastName = employee.LastName;  
  47.         $scope.Gender = employee.Gender;  
  48.         $scope.Designation = employee.Designation;  
  49.         $scope.Salary = employee.Salary;  
  50.         $scope.City = employee.City;  
  51.         $scope.Country = employee.Country;  
  52.     }  
  53.   
  54.     if ($routeParams.Id) {  
  55.   
  56.         var id = $routeParams.Id;  
  57.         EmployeeFactory.detailsEmployee(id).then(function(data) {  
  58.   
  59.             mappingEmployee(data);  
  60.   
  61.         }, function() {  
  62.   
  63.             console.log('Error');  
  64.         });  
  65.   
  66.     }  
  67.   
  68.     //Update Employee  
  69.     $scope.UpdateEmployee = function() {  
  70.   
  71.         var employee = {  
  72.             EmployeeID: $scope.EmployeeID,  
  73.             FirstName: $scope.FirstName,  
  74.             LastName: $scope.LastName,  
  75.             Gender: $scope.Gender,  
  76.             Designation: $scope.Designation,  
  77.             Salary: $scope.Salary,  
  78.             City: $scope.City,  
  79.             Country: $scope.Country  
  80.         };  
  81.         //debugger;  
  82.   
  83.         EmployeeFactory.updateEmployee(employee).then(function(data) {  
  84.   
  85.             $location.path('/EmployeeGrid');  
  86.   
  87.         }, function() {  
  88.             console.log('Error');  
  89.         });  
  90.     }  
  91.   
  92.     //Delete Employee  
  93.     $scope.DeleteEmployee = function() {  
  94.   
  95.         var Id = $scope.EmployeeID;  
  96.   
  97.         EmployeeFactory.deleteEmployee(Id).then(function(data) {  
  98.   
  99.             $location.path('/EmployeeGrid');  
  100.   
  101.         }, function(msg) {  
  102.   
  103.             console.log(msg);  
  104.   
  105.         })  
  106.   
  107.     }  
  108.   
  109.   
  110.   
  111. }]);  
Now, we are going to inject our factory in Employee controller which allow us to call different services implemented as explained previously.

In Employee controller, I have used the same logic based on 2 steps,
  • Calling your Service (ex: EmployeeFactory.getEmployeeList()).
  • Using then (function(data){$scope.EmployeeList = data; }) expression, if the Service has been executed will be successful, else Function(msg){console.log(msg)}, if the error has been thrown.

Note

Don’t forget to call the following libraries inside Layout.cshtml

Layout cshtml

Create different html pages to perform CRUD operations

Now, add new folder from Solution Explorer and inside it, we are going to add 4 HTML files.

Layout cshtml

EmployeeGrid.html

  1. <ahrefahref="#/AddEmployee" class="btn btn-default btn-sm">Add New Employee</a>  
  2.     <br/>  
  3.     <divclassdivclass="table-responsive">  
  4.         <tableidtableid="mytable" class="table table-bordred table-striped">  
  5.             <thead>  
  6.                 <th>EmployeeID</th>  
  7.                 <th>First Name</th>  
  8.                 <th>Last Name</th>  
  9.                 <th>Gender</th>  
  10.                 <th>Designation</th>  
  11.                 <th>Salary</th>  
  12.                 <th>City</th>  
  13.                 <th>Country</th>  
  14.                 <th>Edit</th>  
  15.                 <th>Delete</th>  
  16.             </thead>  
  17.   
  18.   
  19.             <tbody>  
  20.                 <trng-repeattrng-repeat="iteminEmployeeList">  
  21.                     <td>{{item.EmployeeID}}</td>  
  22.                     <td>{{item.FirstName}}</td>  
  23.                     <td>{{item.LastName}}</td>  
  24.                     <td>{{item.Gender}}</td>  
  25.                     <td>{{item.Designation}}</td>  
  26.                     <td>{{item.Salary}}</td>  
  27.                     <td>{{item.City}}</td>  
  28.                     <td>{{item.Country}}</td>  
  29.   
  30.                     <td>  
  31.                         <aclassaclass="btn btn-primary btn-success" href="#/EditEmployee/{{item.EmployeeID}}">  
  32.                             Edit  
  33.                             </a>  
  34.                     </td>  
  35.   
  36.                     <td>  
  37.                         <aclassaclass="btn btn-warning" href="#/DeleteEmployee/{{item.EmployeeID}}">  
  38.                             Delete  
  39.                             </a>  
  40.                     </td>  
  41.   
  42.                     </tr>  
  43.             </tbody>  
  44.   
  45.   
  46.             </table>  
  47.   
  48.             </div>  
In EmployeeGrid page, we have defined a simple table, using bootstrap, which displays all the data from the database table. To fetch data , we need to use ng-repeatdirective.

Now, you can run your Application. Don’t forget to change the URL address, given below-

http://localhost:55192/#/EmployeeGrid


Let’s see the output, given below-

<ahref="#/AddEmployee" class="btn btn-default btn-sm" />Add New Employee</a> <br/>
<divclass="table-responsive">
<tableid="mytable" class=
  1. EmployeeID First Name Last Name Gender Designation Salary City Country Edit Delete {  
  2.     {  
  3.         item.EmployeeID  
  4.     }  
  5. } {  
  6.     {  
  7.         item.FirstName  
  8.     }  
  9. } {  
  10.     {  
  11.         item.LastName  
  12.     }  
  13. } {  
  14.     {  
  15.         item.Gender  
  16.     }  
  17. } {  
  18.     {  
  19.         item.Designation  
  20.     }  
  21. } {  
  22.     {  
  23.         item.Salary  
  24.     }  
  25. } {  
  26.     {  
  27.         item.City  
  28.     }  
  29. } {  
  30.     {  
  31.         item.Country  
  32.     }  
  33. }  
  34. Edit Delete ">  
AddEmployee.html
  1. <formmethodformmethod="post">  
  2.     <h4> Add New Employee </h4>  
  3.     <divclassdivclass="form-group">  
  4.         <labelforlabelfor="InputFirstName">FirstName</label>  
  5.             <inputtypeinputtype="text" class="form-control" id="InputFirstName" placeholder="First Name" ng-model="FirstName">  
  6.                 </div>  
  7.   
  8.                 <divclassdivclass="form-group">  
  9.                     <labelforlabelfor="InputLastName">Last Name</label>  
  10.                         <inputtypeinputtype="text" class="form-control" id="InputLastName" placeholder="Last Name" ng-model="LastName">  
  11.                             </div>  
  12.   
  13.                             <divclassdivclass="form-group">  
  14.                                 <labelforlabelfor="InputGender">Gender</label>  
  15.                                     <inputtypeinputtype="text" class="form-control" id="InputGender" placeholder="Gender" ng-model="Gender">  
  16.                                         </div>  
  17.   
  18.                                         <divclassdivclass="form-group">  
  19.                                             <labelforlabelfor="InputDesignation">Designation</label>  
  20.                                                 <inputtypeinputtype="text" class="form-control" id="InputDesignation" placeholder="Designation" ng-model="Designation">  
  21.                                                     </div>  
  22.   
  23.                                                     <divclassdivclass="form-group">  
  24.                                                         <labelforlabelfor="InputSalary">Salary</label>  
  25.                                                             <inputtypeinputtype="text" class="form-control" id="InputSalary" placeholder="Salary" ng-model="Salary">  
  26.                                                                 </div>  
  27.   
  28.                                                                 <divclassdivclass="form-group">  
  29.                                                                     <labelforlabelfor="InputCity">City</label>  
  30.                                                                         <inputtypeinputtype="text" class="form-control" id="InputCity" placeholder="City" ng-model="City">  
  31.                                                                             </div>  
  32.   
  33.                                                                             <divclassdivclass="form-group">  
  34.                                                                                 <labelforlabelfor="InputCountry">Country</label>  
  35.                                                                                     <inputtypeinputtype="text" class="form-control" id="InputCountry" placeholder="Country" ng-model="Country">  
  36.                                                                                         </div>  
  37.   
  38.   
  39.                                                                                         <buttontypebuttontype="submit" class="btn btn-primary" ng-click="AddNewEmployee()">Save Employee</button>  
  40.                                                                                             </form>  
Here, we have defined a Form with all the required fields to add a new employee.

Let’s see the output, given below-

output
UpdateEmployee.html
  1. <formmethodformmethod="post">  
  2.     <h4> Update Employee </h4>  
  3.     <divclassdivclass="form-group">  
  4.         <labelforlabelfor="InputFirstName">FirstName</label>  
  5.             <inputtypeinputtype="text" class="form-control" id="InputFirstName" placeholder="First Name" ng-model="FirstName">  
  6.                 </div>  
  7.   
  8.                 <divclassdivclass="form-group">  
  9.                     <labelforlabelfor="InputLastName">Last Name</label>  
  10.                         <inputtypeinputtype="text" class="form-control" id="InputLastName" placeholder="Last Name" ng-model="LastName">  
  11.                             </div>  
  12.   
  13.                             <divclassdivclass="form-group">  
  14.                                 <labelforlabelfor="InputGender">Gender</label>  
  15.                                     <inputtypeinputtype="text" class="form-control" id="InputGender" placeholder="Gender" ng-model="Gender">  
  16.                                         </div>  
  17.   
  18.                                         <divclassdivclass="form-group">  
  19.                                             <labelforlabelfor="InputDesignation">Designation</label>  
  20.                                                 <inputtypeinputtype="text" class="form-control" id="InputDesignation" placeholder="Designation" ng-model="Designation">  
  21.                                                     </div>  
  22.   
  23.                                                     <divclassdivclass="form-group">  
  24.                                                         <labelforlabelfor="InputSalary">Salary</label>  
  25.                                                             <inputtypeinputtype="text" class="form-control" id="InputSalary" placeholder="Salary" ng-model="Salary">  
  26.                                                                 </div>  
  27.   
  28.                                                                 <divclassdivclass="form-group">  
  29.                                                                     <labelforlabelfor="InputCity">City</label>  
  30.                                                                         <inputtypeinputtype="text" class="form-control" id="InputCity" placeholder="City" ng-model="City">  
  31.                                                                             </div>  
  32.   
  33.                                                                             <divclassdivclass="form-group">  
  34.                                                                                 <labelforlabelfor="InputCountry">Country</label>  
  35.                                                                                     <inputtypeinputtype="text" class="form-control" id="InputCountry" placeholder="Country" ng-model="Country">  
  36.                                                                                         </div>  
  37.   
  38.   
  39.                                                                                         <buttontypebuttontype="submit" class="btn btn-primary" ng-click="UpdateEmployee()">Update Employee</button>  
  40.                                                                                             </form>  
Let’s see the output, given below-


<formmethod="post" />
<h4> Update Employee </h4>
<divclass="form-group"> <labelfor="inputfirstname">FirstName</label> <inputtype="text" class=
Last Name Gender Designation Salary City Country Update Employee ">

DeleteEmployee.html
  1. <divclassdivclass="panel panel-default">  
  2.     <divclassdivclass="panel-heading">Delete Employee Panel</div>  
  3.         <divclassdivclass="panel-body">  
  4.             <div>Do you want to delete <b>{{FirstName}}</b> ??</div><br/><br/>  
  5.   
  6.             <buttontypebuttontype="submit" class="btn btn-info" ng-click="DeleteEmployee()">  
  7.                 <spanclassspanclass="glyphicon glyphicon-ok-sign">  
  8.                     </span> Delete Employee </button>  
  9.   
  10.                     </div>  
  11.                     </div>  
Let’s see the output, given below-

output
Happy coding.

That’s all, Please send your feedback and queries in comments box.
 


Similar Articles