How To Perform CRUD Operation Using JSON File With Sorting And Paging In Angular - Part Two

Today, in this article, I will explain performing CRUD operations in AngularsJS. In my previous article, I have shown how to retrieve records from JSON file with sorting and paging. Now, I will explain how to Insert, Update, and Delete data in Angular.js with required field validation. So, let us go through step by step.

Part1: We have seen retrieval of records from JSON file in the previous part. Check this link for that.

In Part2, I will perform Insert, Update, and Delete operations.

Step 1

We have already created app.js and service file in JS.

AngularJS

Step2

We will go to service.js file and write the service code for Insert, Update, Delete operations.

  1. AngularExample.factory('MyService'function () {  
  2.     return {  
  3.         EmployeesUri: '/JsonData/Employee.json'  
  4.     }  
  5. });  
  6.   
  7. //$Http Services  
  8. AngularExample.factory('Service',  
  9.     ["$http",  
  10.         function ($http) {  
  11.             return {  
  12.   
  13.                 get: function (url) {  
  14.                     var promise = $http.get(url)  
  15.                     .success(function (data, status) {  
  16.                         return data;  
  17.                     })  
  18.                     .error(function (data, status) {  
  19.                         return { "status"false };  
  20.                     });  
  21.                     //$scope.isLoading = false;  
  22.                     return promise;  
  23.                 },  
  24.   
  25.                 getById: function (url, object) {  
  26.                     var promise = $http({  
  27.                         method: "POST",  
  28.                         url: url,  
  29.                         data: object  
  30.                     })  
  31.                         .success(function (data, status) {  
  32.                             return data;  
  33.                         })  
  34.                         .error(function (data, status) {  
  35.                             return { "status"false };  
  36.                         });  
  37.                     return promise;  
  38.                 },  
  39.                 add: function (url, object) {  
  40.                     var promise = $http({  
  41.                         method: "POST",  
  42.                         url: url,  
  43.                         data: object  
  44.                     })  
  45.                         .success(function (data, status) {  
  46.                             return data;  
  47.                         })  
  48.                         .error(function (data, status) {  
  49.                             return { "status"false };  
  50.                         });  
  51.                     return promise;  
  52.                 },  
  53.                 edit: function (url, object) {  
  54.                     var promise = $http({  
  55.                         method: "POST",  
  56.                         url: url,  
  57.                         data: object  
  58.                     })  
  59.                         .success(function (data, status) {  
  60.                             return data;  
  61.                         })  
  62.                         .error(function (data, status, headers) {  
  63.                             return { "status"false };  
  64.                         });  
  65.                     return promise;  
  66.                 },  
  67.                 del: function (url, object) {  
  68.                     var promise = $http({  
  69.                         method: "POST",  
  70.                         url: url,  
  71.                         data: object  
  72.                     })  
  73.                         .success(function (data, status) {  
  74.                             return data;  
  75.                         })  
  76.                         .error(function (data, status) {  
  77.                             return { "status"false };  
  78.                         });  
  79.                     return promise;  
  80.                 }  
  81.             }  
  82.   
  83.         }]);  

Step 3

Now, let's go to app.js and write two directives - The first one is for reading the pictures while we upload that. And, the second one is for performing the required filed validation while uploading the picture.

  1. (function () {  
  2.     AngularExample.directive("fileread", [function () {  
  3.   
  4.         return {  
  5.             scope: {  
  6.                 fileread: "="  
  7.             },  
  8.             link: function (scope, element, attributes) {  
  9.                 element.bind("change"function (changeEvent) {  
  10.                     var reader = new FileReader();  
  11.                     reader.onload = function (loadEvent) {  
  12.                         scope.$apply(function () {  
  13.                             scope.fileread = loadEvent.target.result;  
  14.                         });  
  15.                     }  
  16.                     var value = changeEvent.target.files[0].name;  
  17.                    
  18.                     reader.readAsDataURL(changeEvent.target.files[0]);  
  19.                     
  20.                     $("#txtImage").val(value);  
  21.                      
  22.                 });  
  23.             }  
  24.         }  
  25.     }]);  
  26. })();  

And another directive,

  1. //Required field Validation of the all pages  
  2. AngularExample.directive('showErrors'function ($timeout) {  
  3.     return {  
  4.         restrict: 'A',  
  5.         require: '^form',  
  6.         link: function (scope, el, attrs, formCtrl, $invalid) {  
  7.             // find the text box element, which has the 'name' attribute  
  8.             var inputEl = el[0].querySelector("[name]");  
  9.             // convert the native text box element to an angular element  
  10.             var inputNgEl = angular.element(inputEl);  
  11.             // get the name on the text box  
  12.             var inputName = inputNgEl.attr('name');  
  13.   
  14.             // only apply the has-error class after the user leaves the text box  
  15.             var blurred = false;  
  16.             inputNgEl.bind('blur'function () {  
  17.                 blurred = true;  
  18.                 el.toggleClass('has-error', formCtrl[inputName].$invalid);  
  19.             });  
  20.   
  21.             scope.$watch(function () {  
  22.                 if (formCtrl[inputName] && formCtrl[inputName] != null) {  
  23.                     return formCtrl[inputName].$invalid  
  24.                 }  
  25.             }, function (invalid) {  
  26.                 if (!blurred && invalid) { return }  
  27.                 el.toggleClass('has-error', invalid);  
  28.             });  
  29.   
  30.             scope.$on('show-errors-check-validity'function () {  
  31.                 el.toggleClass('has-error', formCtrl[inputName].$invalid);  
  32.             });  
  33.   
  34.             scope.$on('show-errors-reset'function () {  
  35.                 $timeout(function () {  
  36.                     el.removeClass('has-error');  
  37.                 }, 0, false);  
  38.             });  
  39.         }  
  40.     }  
  41. });  

Step 4

Now, we will go to EmployeesController and write the insert and update related code.

  1.  $scope.submit = function () {  
  2.       
  3.        
  4.         if ($scope.FormPostType == "edit") {  
  5.   
  6.             
  7.          $index = $scope.Employees.Employees.indexOf(filterFilter($scope.Employees.Employees, { id: $scope.employee.id })[0])  
  8.          alert($index);  
  9.          $scope.Employees.Employees[$index] = angular.copy($scope.employee);  
  10.                  
  11.                 $('#myModal').modal('hide');  
  12.                 $(".commontext").removeClass('has-error');  
  13.             
  14.   
  15.         }  
  16.         else {  
  17.             $(".commontext").removeClass('has-error');  
  18.              
  19.                 $scope.employee.id = $scope.generateId();  
  20.                 $scope.employee.image = $('#txtImage').val();  
  21.               $scope.Employees.Employees.push($scope.employee);  
  22.                 $('#myModal').modal('hide');  
  23.                 $(".commontext").removeClass('has-error');  
  24.               
  25.         }  
  26.         $scope.totalItems = $scope.Employees.Employees.length;  
  27.     };  
  28.   
  29. //method to generate ID  
  30.     $scope.generateId = function () {  
  31.         var date = new Date();  
  32.         $scope.second = ((date.getSeconds() < 10 ? '0' : '') + date.getSeconds());  
  33.         $scope.randomnumber = Math.floor((Math.random() * 6) + 50);  
  34.         return parseFloat($scope.randomnumber) + parseFloat($scope.second);  
  35.     };  

In the above code, I wrote both theinsert and update code according to the condition.

Step 5

Now, we will go to our HTML file and write the code or design for opening the popup.

  1.    <div class="modal fade modalcompetition " id="myModal" role="dialog">  
  2.             <form ng-submit="submit()" name="CreateEmployee">  
  3.                 <div class="modal-dialog btn-info">  
  4.                     <!-- Modal content-->  
  5.                     <div class="modal-content btn-primary">  
  6.                         <div class="modal-header btn-primary">  
  7.                             <button type="button" class="close" data-dismiss="modal">×</button>  
  8.                             <h4 class="modal-title right-data">Create/Edit Employee</h4>  
  9.                         </div>  
  10.                         <div class="modal-body btn-primary">  
  11.                             <input type="hidden" ng-model="employee.id" />  
  12.                             <div class="row">  
  13.                                 <div class="col-md-6 col-sm-6 commontext" show-errors>  
  14.                                     <label for="lblFirstName" class="right-data">First Name</label>  
  15.                                     <input type="text" name="firstName" id="txtFirstName" ng-model="employee.firstName" class="form-control" required />  
  16.                                 </div>  
  17.                                 <div class="col-md-6 col-sm-6 commontext" show-errors>  
  18.                                     <label for="name" class="right-data">Address</label>  
  19.                                     <input type="text" class="form-control" ng-model="employee.address" placeholder="Employee Address" required />  
  20.                                 </div>  
  21.                             </div>  
  22.                             <div class="row">  
  23.                                 <div class="col-md-6 col-sm-6 commontext" show-errors>  
  24.                                     <label for="exampleSelect1" class="right-data">Last Name</label>  
  25.                                     <input type="text" name="lastName" id="txtLastName" ng-model="employee.lastName" class="form-control date-input calendar" required />  
  26.                                 </div>  
  27.   
  28.                          
  29.   
  30.                                 <div class="col-md-6 commontext modal-logo-padding" show-errors>  
  31.                                     <label class="right-data">Photo</label><br />  
  32.                                     <input type="file" id="fileUpload" name="filepath" ng-model="employee.image" fileread="employee.image" accept="image/*" multiple app-filereader class="custom-file-upload-hidden" >  
  33.                                     <span class="file-upload-button">{{Browse}}</span>  
  34.                                     <input type="text" id="txtImage" ng-model="employee.image" class="file-upload-input right-data form-control" readonly />  
  35.                                      
  36.                                 </div>  
  37.   
  38.                             </div>  
  39.                             <div class="row">  
  40.                                 <div class="col-md-6 col-sm-6 commontext" show-errors>  
  41.                                     <label for="exampleSelect1" class="right-data">Birth Date</label>  
  42.                                     <input type="text" name="txtDateOfBirth" id="dateOfBirth" ng-bind="employee.dateOfBirth" ng-model="employee.dateOfBirth" class="form-control" required />  
  43.                                 </div>  
  44.   
  45.                                 <div class="col-md-6 col-sm-6 commontext" show-errors>  
  46.                                     <label for="exampleSelect1" class="right-data">Email Id</label>  
  47.                                     <input type="text" name="emailId" id="txtEmailId" ng-bind="employee.emailId" ng-model="employee.emailId" class="form-control" required />  
  48.                                    
  49.                                 </div>  
  50.   
  51.                             </div>  
  52.                             <div class="row">  
  53.                                 <div class="col-md-6 col-sm-6 commontext" show-errors>  
  54.                                     <label for="exampleSelect1" class="right-data">Phone Number</label>  
  55.                                     <input type="text" name="phoneNumber" id="txtPhone" ng-model="employee.phoneNo" class="form-control date-input" required />                                    
  56.                                 </div>                              
  57.                             </div>  
  58.                         </div>  
  59.                         <div class="footer btn-primary">  
  60.                             <input type="submit" class="btn btn-default" ng-click="save()" value="Save" />  
  61.                             <button class="btn btn-default" data-dismiss="modal" ng-click="reset()">Cancel</button>  
  62.                             
  63.                         </div>  
  64.                     </div>  
  65.   
  66.                 </div>  
  67.             </form>  
  68.         </div>  
  69.   
  70.   
  71. //This belove code for use date picker in birthdate  
  72.   
  73. <script>  
  74.     
  75.         $("#dateOfBirth").datetimepicker({  
  76.             changeMonth: true,  
  77.             dateFormat: "yy-mm-dd",  
  78.             format: 'Y/m/d',  
  79.             timepicker: false  
  80.         });  
  81.      
  82. </script>  

Also, we have to write the HTML code for Add, Edit, and Delete buttons.

  1. <span class="col-lg-2"><a href="" data-toggle="modal" data-target="#myModal" ng-click="addEmployee('add')" class="icon-plus">Add New Employee</a></span>  
  2. <span class="col-lg-2"><a ng-disabled="disableEdit()" class="icon-pencil" data-toggle="modal" data-target="#myModal" ng-click="editEmployee('edit')" value="Edit Employee">Edit Employee</a></span>  
  3. <span class="col-lg-2"><a class="deleteicon" ng-disabled="disableDelete()" value="Delete Employee" ng-model="selected" ng-click="remove()">Delete Employee</a></span>  

AngularJS

Now, let's see our design.

AngularJS 

See the output after clicking "Save".

AngularJS

Step 6

Now, we will perform Edit operations. For this, I am using checkbox. Just check the checkbox and click Edit button. Here, we have already given the option that you have to update only one record at a time.

But before that, we have to write the code for selecting the checkbox.

  1. //check/uncheck record checkbox and 'selectall' checkbox  
  2.       $scope.UnCheckMain = function () {  
  3.           var result = 0;  
  4.           var items = 0;  
  5.   
  6.           for (var i = $scope.end - 1; i >= $scope.begin; i--) {  
  7.               if ($scope.Employees.Employees[i]) {  
  8.                   var items = items + 1;  
  9.                   if ($scope.Employees.Employees[i].selected) {  
  10.                       var result = result + 1;  
  11.                   }  
  12.               }  
  13.           }  
  14.   
  15.           if (result && result == items) {  
  16.               $scope.selectedAll = true;  
  17.               var currentpageid = filterFilter($scope.pageArray, { currentPage: $scope.currentPage });  
  18.               if (currentpageid.length <= 0 || currentpageid == null) {  
  19.                   $scope.pageArray.push({ currentPage: $scope.currentPage, selected: $scope.selectedAll });  
  20.               }  
  21.               else {  
  22.                   $index = $scope.pageArray.indexOf(filterFilter($scope.pageArray, { currentPage: $scope.currentPage })[0])  
  23.                   $scope.pageArray[$index] = angular.copy({ currentPage: $scope.currentPage, selected: $scope.selectedAll });  
  24.               }  
  25.               items = 0;  
  26.               result = 0;  
  27.           } else {  
  28.               $scope.selectedAll = false;  
  29.   
  30.               var currentpageid = filterFilter($scope.pageArray, { currentPage: $scope.currentPage });  
  31.               if (currentpageid.length <= 0 || currentpageid == null) {  
  32.                   $scope.pageArray.push({ currentPage: $scope.currentPage, selected: $scope.selectedAll });  
  33.               }  
  34.               else {  
  35.                   $index = $scope.pageArray.indexOf(filterFilter($scope.pageArray, { currentPage: $scope.currentPage })[0])  
  36.                   $scope.pageArray[$index] = angular.copy({ currentPage: $scope.currentPage, selected: $scope.selectedAll });  
  37.               }  
  38.               items = 0;  
  39.               result = 0;  
  40.           }  
  41.   
  42.           $scope.disableEdit();  
  43.       };  
  44.   //check/uncheck 'SelectAll' Checkbox  
  45.       $scope.checkAll = function () {  
  46.           if ($scope.pageArray && $scope.pageArray.length > 0) {  
  47.               $scope.checkcurrentpage = [];  
  48.               $scope.checkcurrentpage = filterFilter($scope.pageArray, { currentPage: $scope.currentPage });  
  49.               if (($scope.checkcurrentpage && $scope.checkcurrentpage.length > 0)) {  
  50.   
  51.                   $scope.selectedAll = $scope.checkcurrentpage[0].selected;  
  52.                   if ($scope.checkcurrentpage[0].selected) {  
  53.                       event.target.value = 1;  
  54.                   }  
  55.                   else {  
  56.                       event.target.value = 0;  
  57.                   }  
  58.               }  
  59.               else {  
  60.                   event.target.value = 0;  
  61.               }  
  62.           }  
  63.   
  64.           if (event.target.value == 0) {  
  65.               $scope.selectedAll = true;  
  66.               event.target.value = 1;  
  67.           }  
  68.           else {  
  69.               $scope.selectedAll = false;  
  70.               event.target.value = 0;  
  71.           }  
  72.   
  73.   
  74.           for (var i = $scope.begin; i < $scope.end; i++) {  
  75.               if ($scope.Employees.Employees[i]) {  
  76.                   $index = $scope.Employees.Employees.indexOf($scope.Employees.Employees[i]);  
  77.                   $scope.Employees.Employees[$index].selected = $scope.selectedAll;  
  78.               }  
  79.           }  
  80.   
  81.           var currentpageid = filterFilter($scope.pageArray, { currentPage: $scope.currentPage });  
  82.           if (currentpageid.length <= 0 || currentpageid == null) {  
  83.               $scope.pageArray.push({ currentPage: $scope.currentPage, selected: $scope.selectedAll });  
  84.           }  
  85.           else {  
  86.               $index = $scope.pageArray.indexOf(filterFilter($scope.pageArray, { currentPage: $scope.currentPage })[0])  
  87.               $scope.pageArray[$index] = angular.copy({ currentPage: $scope.currentPage, selected: $scope.selectedAll });  
  88.           }  
  89.       };  

In the above code, I used all the code related to checkbox.

  1. We check or uncheck
  2. We select on header check box then all check box automatic check
  3. Any Uncheck on data row check box the header automatically uncheck
  4. Here is paging so we can check or uncheck only the current page. It does affect some other pages.

Now, we have to write to open the edit records option according to Employee number.

  1. //Take a copy of record to edit in model pop-up   
  2. $scope.editEmployee = function (postType) {  
  3.     $scope.errMessageCurrDate = '';  
  4.     $scope.errMessage = '';  
  5.     $scope.FormPostType = postType;  
  6.     for (var i = $scope.end - 1; i >= $scope.begin; i--) {  
  7.         if ($scope.Employees.Employees[i] && $scope.Employees.Employees[i].selected) {  
  8.             $index = $scope.Employees.Employees.indexOf($scope.Employees.Employees[i]);  
  9.             $scope.employee = angular.copy($scope.Employees.Employees[$index]);  
  10.         }  
  11.     }  
  12. }  

Now, we will go to our HTML page and add the code for editing in EmployeeController.js.

  1. //Take a copy of record to edit in model pop-up   
  2.      $scope.editEmployee = function (postType) {  
  3.          $scope.errMessageCurrDate = '';  
  4.          $scope.errMessage = '';  
  5.          $scope.FormPostType = postType;  
  6.          for (var i = $scope.end - 1; i >= $scope.begin; i--) {  
  7.              if ($scope.Employees.Employees[i] && $scope.Employees.Employees[i].selected) {  
  8.                  $index = $scope.Employees.Employees.indexOf($scope.Employees.Employees[i]);  
  9.                  $scope.employee = angular.copy($scope.Employees.Employees[$index]);  
  10.              }  
  11.          }  
  12.      }  
  13.   
  14.   
  15.   
  16. //Enable or desable of edite button  
  17.      $scope.disableEdit = function () {  
  18.          var result = 0;  
  19.          for (var i = $scope.end - 1; i >= $scope.begin; i--) {  
  20.              if ($scope.Employees.Employees[i] && $scope.Employees.Employees[i].selected) {  
  21.                  var result = result + 1;  
  22.              }  
  23.          }  
  24.          if (result && result == 1) {  
  25.              $('.icon-pencil').addClass('checked');  
  26.              $('.icon-pencil').removeClass('anchordisabled');  
  27.              result = 0;  
  28.              return false;  
  29.          } else {  
  30.              $('.icon-pencil').removeClass('checked');  
  31.              $('.icon-pencil').addClass('anchordisabled');  
  32.              result = 0;  
  33.              return true;  
  34.          }  
  35.      };  

Now, let's add code for generating checkbox in HTML file.

First, we will add a checkbox in header part.

  1. <th id="checkClass">  
  2.                           <input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />  
  3.                       </th> 

Second, we will add a check box in row part.

  1. <td><input type="checkbox" ng-model="employee.selected" ng-checked="employee.selected" ng-click="UnCheckMain()" /></td>  

AngularJS

After that, see the result.

AngularJS

Step 7

Now, we have to perform the Delete operation. For this, let's go to EmployeeController.js file and write the code.

  1. //Deactivate selected/all Employee  
  2. $scope.remove = function () {  
  3.     if (confirm("Are you sure to Delete ?")) {  
  4.         for (var i = $scope.end - 1; i >= $scope.begin; i--) {  
  5.             if ($scope.Employees.Employees[i] && $scope.Employees.Employees[i].selected) {  
  6.                 $index = $scope.Employees.Employees.indexOf($scope.Employees.Employees[i]);  
  7.                 $scope.Employees.Employees.splice($index, 1);  
  8.             }  
  9.         };  
  10.         $scope.totalItems = $scope.Employees.Employees.length;  
  11.     }  
  12. };  

After that, just click the Delete button in UI and select the checkbox of the row we have to delete. We can also delete multiple rows at a time.

AngularJS

After that, click OK. In the last, I am giving the code of whole Controller part and the complete stylesheet of the design as well.

EmployeeController.js

AngularExample 

  1. .controller("EmployeeController", ['$scope''Service''MyService','filterFilter','config'function ($scope, Service, MyService,filterFilter, config) {  
  2.   
  3.     $scope.data = [];  
  4.     $scope.Employees = [];  
  5.     $scope.employee = {};  
  6.     $scope.FormPostType;  
  7.   
  8.     //Http Services Get Data  
  9.     Service.get(MyService.EmployeesUri)  
  10.     .then(function (response) {  
  11.         $scope.Employees = response.data;  
  12.         $scope.totalItems = $scope.Employees.Employees.length;  
  13.        
  14.         $scope.currentPage = 1;  
  15.         $scope.numPerPage = config.paginationItemsPerPage;  
  16.           
  17.         //Pagination control  
  18.         $scope.paginate = function (value) {  
  19.             if ($scope.pageArray && $scope.pageArray.length > 0) {  
  20.                 $scope.checkcurrentpage = [];  
  21.                 $scope.checkcurrentpage = filterFilter($scope.pageArray, { currentPage: $scope.currentPage });  
  22.                 if (($scope.checkcurrentpage && $scope.checkcurrentpage.length > 0)) {  
  23.                     $scope.selectedAll = $scope.checkcurrentpage[0].selected;  
  24.                 }  
  25.                 else {  
  26.                     $scope.selectedAll = false;  
  27.                 }  
  28.             }  
  29.   
  30.   
  31.             $scope.begin = ($scope.currentPage - 1) * $scope.numPerPage;  
  32.             $scope.end = $scope.begin + $scope.numPerPage;  
  33.             index = $scope.Employees.Employees.indexOf(value);  
  34.             return ($scope.begin <= index && index < $scope.end);  
  35.   
  36.         };  
  37.     });  
  38.   
  39.   
  40.   
  41.     //check/uncheck record checkbox and 'selectall' checkbox  
  42.     $scope.UnCheckMain = function () {  
  43.         var result = 0;  
  44.         var items = 0;  
  45.   
  46.         for (var i = $scope.end - 1; i >= $scope.begin; i--) {  
  47.             if ($scope.Employees.Employees[i]) {  
  48.                 var items = items + 1;  
  49.                 if ($scope.Employees.Employees[i].selected) {  
  50.                     var result = result + 1;  
  51.                 }  
  52.             }  
  53.         }  
  54.   
  55.         if (result && result == items) {  
  56.             $scope.selectedAll = true;  
  57.             var currentpageid = filterFilter($scope.pageArray, { currentPage: $scope.currentPage });  
  58.             if (currentpageid.length <= 0 || currentpageid == null) {  
  59.                 $scope.pageArray.push({ currentPage: $scope.currentPage, selected: $scope.selectedAll });  
  60.             }  
  61.             else {  
  62.                 $index = $scope.pageArray.indexOf(filterFilter($scope.pageArray, { currentPage: $scope.currentPage })[0])  
  63.                 $scope.pageArray[$index] = angular.copy({ currentPage: $scope.currentPage, selected: $scope.selectedAll });  
  64.             }  
  65.             items = 0;  
  66.             result = 0;  
  67.         } else {  
  68.             $scope.selectedAll = false;  
  69.   
  70.             var currentpageid = filterFilter($scope.pageArray, { currentPage: $scope.currentPage });  
  71.             if (currentpageid.length <= 0 || currentpageid == null) {  
  72.                 $scope.pageArray.push({ currentPage: $scope.currentPage, selected: $scope.selectedAll });  
  73.             }  
  74.             else {  
  75.                 $index = $scope.pageArray.indexOf(filterFilter($scope.pageArray, { currentPage: $scope.currentPage })[0])  
  76.                 $scope.pageArray[$index] = angular.copy({ currentPage: $scope.currentPage, selected: $scope.selectedAll });  
  77.             }  
  78.             items = 0;  
  79.             result = 0;  
  80.         }  
  81.   
  82.         $scope.disableEdit();  
  83.     };  
  84.   
  85.     //Add new Record / Save Edited Records  
  86.     $scope.submit = function () {  
  87.       
  88.        
  89.         if ($scope.FormPostType == "edit") {  
  90.   
  91.             
  92.          $index = $scope.Employees.Employees.indexOf(filterFilter($scope.Employees.Employees, { id: $scope.employee.id })[0])  
  93.          alert($index);  
  94.          $scope.Employees.Employees[$index] = angular.copy($scope.employee);  
  95.                  
  96.                 $('#myModal').modal('hide');  
  97.                 $(".commontext").removeClass('has-error');  
  98.             
  99.   
  100.         }  
  101.         else {  
  102.             $(".commontext").removeClass('has-error');  
  103.              
  104.                 $scope.employee.id = $scope.generateId();  
  105.                 $scope.employee.image = $('#txtImage').val();  
  106.               $scope.Employees.Employees.push($scope.employee);  
  107.                 $('#myModal').modal('hide');  
  108.                 $(".commontext").removeClass('has-error');  
  109.               
  110.         }  
  111.         $scope.totalItems = $scope.Employees.Employees.length;  
  112.     };  
  113.     //check/uncheck 'SelectAll' Checkbox  
  114.     $scope.checkAll = function () {  
  115.         if ($scope.pageArray && $scope.pageArray.length > 0) {  
  116.             $scope.checkcurrentpage = [];  
  117.             $scope.checkcurrentpage = filterFilter($scope.pageArray, { currentPage: $scope.currentPage });  
  118.             if (($scope.checkcurrentpage && $scope.checkcurrentpage.length > 0)) {  
  119.   
  120.                 $scope.selectedAll = $scope.checkcurrentpage[0].selected;  
  121.                 if ($scope.checkcurrentpage[0].selected) {  
  122.                     event.target.value = 1;  
  123.                 }  
  124.                 else {  
  125.                     event.target.value = 0;  
  126.                 }  
  127.             }  
  128.             else {  
  129.                 event.target.value = 0;  
  130.             }  
  131.         }  
  132.   
  133.         if (event.target.value == 0) {  
  134.             $scope.selectedAll = true;  
  135.             event.target.value = 1;  
  136.         }  
  137.         else {  
  138.             $scope.selectedAll = false;  
  139.             event.target.value = 0;  
  140.         }  
  141.   
  142.   
  143.         for (var i = $scope.begin; i < $scope.end; i++) {  
  144.             if ($scope.Employees.Employees[i]) {  
  145.                 $index = $scope.Employees.Employees.indexOf($scope.Employees.Employees[i]);  
  146.                 $scope.Employees.Employees[$index].selected = $scope.selectedAll;  
  147.             }  
  148.         }  
  149.   
  150.         var currentpageid = filterFilter($scope.pageArray, { currentPage: $scope.currentPage });  
  151.         if (currentpageid.length <= 0 || currentpageid == null) {  
  152.             $scope.pageArray.push({ currentPage: $scope.currentPage, selected: $scope.selectedAll });  
  153.         }  
  154.         else {  
  155.             $index = $scope.pageArray.indexOf(filterFilter($scope.pageArray, { currentPage: $scope.currentPage })[0])  
  156.             $scope.pageArray[$index] = angular.copy({ currentPage: $scope.currentPage, selected: $scope.selectedAll });  
  157.         }  
  158.     };  
  159.     //method to generate ID  
  160.     $scope.generateId = function () {  
  161.         var date = new Date();  
  162.         $scope.second = ((date.getSeconds() < 10 ? '0' : '') + date.getSeconds());  
  163.         $scope.randomnumber = Math.floor((Math.random() * 6) + 50);  
  164.         return parseFloat($scope.randomnumber) + parseFloat($scope.second);  
  165.     };  
  166.     //Add new record using model pop-up   
  167.     $scope.addEmployee = function (postType) {  
  168.         if ($(".commontext").hasClass('has-error')) {  
  169.             $(".commontext").removeClass('has-error');  
  170.         }  
  171.      
  172.         $scope.errMessageCurrDate = '';  
  173.         $scope.errMessage = '';  
  174.         $scope.FormPostType = postType;  
  175.         $scope.employee = {};  
  176.   
  177.     };  
  178.   
  179.     $scope.save = function () {  
  180.         $scope.$broadcast('show-errors-check-validity');  
  181.     };  
  182.     //Enable/Disable Edit Button on Checkbox Checked  
  183.   
  184.   
  185.     //Take a copy of record to edit in model pop-up   
  186.     $scope.editEmployee = function (postType) {  
  187.         $scope.errMessageCurrDate = '';  
  188.         $scope.errMessage = '';  
  189.         $scope.FormPostType = postType;  
  190.         for (var i = $scope.end - 1; i >= $scope.begin; i--) {  
  191.             if ($scope.Employees.Employees[i] && $scope.Employees.Employees[i].selected) {  
  192.                 $index = $scope.Employees.Employees.indexOf($scope.Employees.Employees[i]);  
  193.                 $scope.employee = angular.copy($scope.Employees.Employees[$index]);  
  194.             }  
  195.         }  
  196.     }  
  197.     //Enable or desable of edite button  
  198.     $scope.disableEdit = function () {  
  199.         var result = 0;  
  200.         for (var i = $scope.end - 1; i >= $scope.begin; i--) {  
  201.             if ($scope.Employees.Employees[i] && $scope.Employees.Employees[i].selected) {  
  202.                 var result = result + 1;  
  203.             }  
  204.         }  
  205.         if (result && result == 1) {  
  206.             $('.icon-pencil').addClass('checked');  
  207.             $('.icon-pencil').removeClass('anchordisabled');  
  208.             result = 0;  
  209.             return false;  
  210.         } else {  
  211.             $('.icon-pencil').removeClass('checked');  
  212.             $('.icon-pencil').addClass('anchordisabled');  
  213.             result = 0;  
  214.             return true;  
  215.         }  
  216.     };  
  217.   
  218.   
  219.     //Enable/Disable Delete Button on Checkbox Checked  
  220.     $scope.disableDelete = function () {  
  221.         var result = 0;  
  222.         for (var i = $scope.end - 1; i >= $scope.begin; i--) {  
  223.             if ($scope.Employees.Employees[i] && $scope.Employees.Employees[i].selected) {  
  224.                 var result = result + 1;  
  225.             }  
  226.         }  
  227.   
  228.         if (result && result >= 1) {  
  229.             $('.deleteicon').addClass('checked');  
  230.             $('.deleteicon').removeClass('anchordisabled');  
  231.             result = 0;  
  232.             return false;  
  233.         } else {  
  234.             $('.deleteicon').removeClass('checked');  
  235.             $('.deleteicon').addClass('anchordisabled');  
  236.             result = 0;  
  237.             return true;  
  238.         }  
  239.     };  
  240.   
  241.     //Deactivate selected/all Employee  
  242.     $scope.remove = function () {  
  243.         if (confirm("Are you sure to Delete ?")) {  
  244.             for (var i = $scope.end - 1; i >= $scope.begin; i--) {  
  245.                 if ($scope.Employees.Employees[i] && $scope.Employees.Employees[i].selected) {  
  246.                     $index = $scope.Employees.Employees.indexOf($scope.Employees.Employees[i]);  
  247.                     $scope.Employees.Employees.splice($index, 1);  
  248.                 }  
  249.             };  
  250.             $scope.totalItems = $scope.Employees.Employees.length;  
  251.         }  
  252.     };  
  253.      
  254. }]);  

Site.cs

  1. body {  
  2.     padding-top: 50px;  
  3.     padding-bottom: 20px;  
  4. }  
  5.   
  6. /* Set padding to keep content from hitting the edges */  
  7. .body-content {  
  8.     padding-left: 15px;  
  9.     padding-right: 15px;  
  10. }  
  11.   
  12. /* Set width on the form input elements since they're 100% wide by default */  
  13. input,  
  14. select,  
  15. textarea {  
  16.     max-width: 280px;  
  17. }  
  18. .anchordisabled{  
  19.  cursor: not-allowed;  
  20.   pointer-events: none;  
  21.   opacity: .65;  
  22.   filter: alpha(opacity=65);  
  23.   -webkit-box-shadow: none;  
  24.   box-shadow: none;  
  25. }  
  26. /*.modal-logo-padding{ 
  27.     padding-top:30px; 
  28. }*/  
  29.   
  30. .right-data{  
  31. padding: 2px 0px !important;  
  32. padding-right:20px;  
  33. }  
  34.   
  35. .custom-file-upload-hidden {  
  36.   position: absolute;  
  37.     z-index: 999;  
  38.     width: 88%;  
  39.     height: 100%;  
  40.     direction: ltr;  
  41.     opacity: 0;  
  42. }  
  43.   
  44. .file-upload-input{  
  45.         top: -40px;  
  46.     position: relative;  
  47.     text-align:right;  
  48. }  
  49.   
  50. .right-data{  
  51. padding: 2px 0px !important;  
  52. padding-right:20px;  
  53. }  
  54.   
  55. .file-upload-button {  
  56.     cursor: pointer;  
  57.     height:34px;  
  58.     padding:8px 20px;  
  59.     display: inline-block;  
  60.     color: #fff;  
  61.     border: none;  
  62.     position: absolute;  
  63.     left: 28px;  
  64.     background-color: #b3b3b3;  
  65.     -moz-transition: all 0.2s ease-in;  
  66.     -o-transition: all 0.2s ease-in;  
  67.     -webkit-transition: all 0.2s ease-in;  
  68.     transition: all 0.2s ease-in;  
  69.     
  70.      
  71.     
  72. }  
  73.   
  74.  .file-upload-button{  
  75.    position: relative;  
  76.     display: inline-block;  
  77.     padding: 9px 9px;  
  78.     left: 0;  
  79.         height: 36px;  
  80.     width: 96px;  
  81. }  

Conclusion

In this article, we saw how to perform CRUD operations in Angular JS using JSON file.  I hope you liked it. If you have a query related to this, just comment below. You can download the whole project from the attachment.


Similar Articles