Sunday, September 24, 2017

CRUD operation in SharePoint Online using REST, AngularJS

CRUD operation in SharePoint Online using REST, AngularJS
Step 1:-
---------------------
Create custom list as "Employees"

Step 2:-
---------------------
Create Folder structure as below format.

Use below images for edit, delete, cancel buttons.


Step 3:-
---------------------
Update below code.
style.css:-
---------------------
.all-employees table{
       font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    width: 100%;
    border-collapse: collapse;
    border: 1px solid #999999;
} 
.all-employees table th{
       font-size: 1.4em;
  text-align: left;
  padding: 5px;
  text-align: center;
  border-right: 1px solid #999999;
} 
.all-employees table td{
  font-size: 1.2em;
  border: 1px solid #999999;
  padding: 5px;
  text-align: center;
}
.all-employees{
  margin-top: 17px;
}
.add-new-button{
  background-color: rgb(55, 139, 202);
  padding: 8px;
  color: white;
}
.add-new-button:visited{
  color: white;
}
.employees-app{
   width: 800px;
}
.employees-app-table{
  width: 100%;
}
.employees-app-table input[type=text], textarea{
  width: 50%!important;
}
.employees-app-table input[type=button]{
  margin: 0!important;
}
add.js:-
---------------------
"use strict";
(function () {
       angular.module("EmployeesApp")
              .controller("addEmployeeCtrl", ["$scope", "employeesService","$location",
              function ($scope, employeesService,$location) {
              $scope.addEmployee = function (employee) {
                     employeesService.addNew(employee)
                     .then(function(response){
                           console.log(response);
                           $location.path("/");
                     });
                    
              };
       }]);
})();
all.js:-
---------------------
"use strict";
(function () {
       angular.module("EmployeesApp")
              .controller("allEmployeesCtrl", ["$scope", "employeesService",
              function ($scope, employeesService) {
                     employeesService.getAll()
                           .then(function (response) {
                $scope.employees = response.d.results;
                     });
                     $scope.removeEmployee = function(employee){                  
                           if (confirm(" Are you sure want to delete " + employee.FirstName + " " + employee.LastName + " ?")) {       
                                  employeesService.remove(employee.ID)
                                  .then(function(response){
                                         var employeeIndex = $scope.employees.indexOf(employee);
                                         $scope.employees.splice(employeeIndex,1);
                                  });
                           }
                     };
              }]);
})();
cancel.js:-
---------------------
"use strict";
(function () {
       angular.module("EmployeesApp")
              .controller("cancelEditEmployeeCtrl", ["$scope", "employeesService",
              function ($scope, employeesService) {
                     employeesService.cancelRequest()
                           .then(function (response) {
                $scope.employees = response.d.results;
                     });
                     $scope.removeEmployee = function(employee){
                           employeesService.remove(employee.ID)
                           .then(function(response){
                                  var employeeIndex = $scope.employees.indexOf(employee);
                                  $scope.employees.splice(employeeIndex,1);
                           });
                     };
              }]);
})();
edit.js:-
---------------------
"use strict";
(function () {
       angular.module("EmployeesApp")
              .controller("editEmployeeCtrl", ["$scope", "employeesService", "$routeParams","$location",
                     function ($scope, employeesService, $routeParams,$location) {
                           employeesService.getById($routeParams.employeeId)
                                  .then(function (response) {
                                         $scope.employee = {
                                                employeeId : response.d.ID,
                                                firstName: response.d.FirstName,
                                                lastName: response.d.LastName
                                         };
                                         $scope.editEmployee = function(employee){
                                                employeesService.update(employee)
                                                .then(function(response){
                                                       $location.path("/");
                                                });
                                         };
                                  });
                     }]);
})();
employees.js:-
---------------------
"use strict";
(function(){
       angular.module("EmployeesApp")
       .factory("employeesService",["baseSvc",function(baseService){
              var listEndPoint = '/_api/web/lists';
              var getAll = function(){
                     var query = listEndPoint + "/GetByTitle('Employees')/Items?$select=ID,FirstName,LastName";
                     return baseService.getRequest(query);
              };
              var addNew = function(employee){
                     var data = {
                           __metadata: { 'type': 'SP.Data.EmployeesListItem' },
                           FirstName : employee.firstName,
                           LastName : employee.lastName
                     };
                     var url = listEndPoint + "/GetByTitle('Employees')/Items";
                     return baseService.postRequest(data,url);
              };
              var getById = function(employeeId){
                     var query = listEndPoint + "/GetByTitle('Employees')/GetItemById("+employeeId+")?$select=ID,FirstName,LastName";
                     return baseService.getRequest(query);
              };
              var update = function (employee){
                     var data = {
                           __metadata: { 'type': 'SP.Data.EmployeesListItem' },
                           FirstName : employee.firstName,
                           LastName : employee.lastName
                     };
                     var url = listEndPoint + "/GetByTitle('Employees')/GetItemById("+employee.employeeId+")";
                     return baseService.updateRequest(data,url);
              };
              var remove = function(employeeId){
                     var url = listEndPoint + "/GetByTitle('Employees')/GetItemById("+employeeId+")";
                     return baseService.deleteRequest(url);
              };
              var cancel = function(){
                     var query = listEndPoint + "/GetByTitle('Employees')/Items?$select=ID,FirstName,LastName";
                     return baseService.cancelRequest(query);
              };
              return{
                     getAll:getAll,
                     addNew:addNew,
                     getById:getById,
                     update:update,
                     remove:remove,
                     cancel:cancel
              };
       }]);
})();
baseSvc.js:-
---------------------
"use strict";
(function () {
    angular.module("EmployeesApp")
        .factory("baseSvc", ["$http", "$q", function ($http, $q) {
        var baseUrl = _spPageContextInfo.webAbsoluteUrl;
        var getRequest = function (query) {
            var deferred = $q.defer();
            $http({
                url: baseUrl + query,
                method: "GET",
                headers: {
                    "accept": "application/json;odata=verbose",
                    "content-Type": "application/json;odata=verbose"
                }
            })
                .success(function (result) {
                deferred.resolve(result);
            })
                .error(function (result, status) {
                deferred.reject(status);
            });
            return deferred.promise;
        };
        var postRequest = function (data, url) {
            var deferred = $q.defer();
            $http({
                url: baseUrl + url,
                method: "POST",
                headers: {
                    "accept": "application/json;odata=verbose",
                    "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
                    "content-Type": "application/json;odata=verbose"
                },
                data: JSON.stringify(data)
            })
                .success(function (result) {
                deferred.resolve(result);
            })
                .error(function (result, status) {
                deferred.reject(status);
            });
            return deferred.promise;
        };
        var updateRequest = function (data, url) {
            var deferred = $q.defer();
            $http({
                url: baseUrl + url,
                method: "PATCH",
                headers: {
                    "accept": "application/json;odata=verbose",
                    "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
                    "content-Type": "application/json;odata=verbose",
                    "X-Http-Method": "PATCH",
                    "If-Match": "*"
                },
                data: JSON.stringify(data)
            })
                .success(function (result) {
                deferred.resolve(result);
            })
                .error(function (result, status) {
                deferred.reject(status);
            });
            return deferred.promise;
        };
        var deleteRequest = function(url){
            var deferred = $q.defer();
            $http({
                url: baseUrl + url,
                method: "DELETE",
                headers: {
                    "accept": "application/json;odata=verbose",
                    "X-RequestDigest":document.getElementById("__REQUESTDIGEST").value,
                    "IF-MATCH": "*"
                }
            })
                .success(function (result) {
                    deferred.resolve(result);
                })
                .error(function (result, status) {
                    deferred.reject(status);
                });
            return deferred.promise;
         };
         var cancelRequest = function (query) {
            var deferred = $q.defer();
            $http({
                url: baseUrl + query,
                method: "GET",
                headers: {
                    "accept": "application/json;odata=verbose",
                    "content-Type": "application/json;odata=verbose"
                }
            })
                .success(function (result) {
                deferred.resolve(result);
            })
                .error(function (result, status) {
                deferred.reject(status);
            });
            return deferred.promise;
        };
        return {
            getRequest: getRequest,
            postRequest: postRequest,
            updateRequest: updateRequest,
            deleteRequest:deleteRequest,
            cancelRequest:cancelRequest
        };
    }]);
})();
app.js:-
---------------------
"use strict";
(function () {
       angular.module("EmployeesApp", ["ngRoute"])
              .config(["$routeProvider", function ($routeProvider) {
              $routeProvider.when("/", {
                     templateUrl: "/sites/dev/SiteAssets/employees01/templates/employees/all.html",
                     controller: "allEmployeesCtrl"
              }).when("/addEmployee", {
                     templateUrl: "/sites/dev/SiteAssets/employees01/templates/employees/add.html",
                     controller: "addEmployeeCtrl"
              }).when("/editEmployee/:employeeId", {
                     templateUrl: "/sites/dev/SiteAssets/employees01/templates/employees/edit.html",
                     controller: "editEmployeeCtrl"
              }).when("/cancelEditEmployee/:employeeId", {
                     templateUrl: "/sites/dev/SiteAssets/employees01/templates/employees/edit.html",
                     controller: "cancelEditEmployeeCtrl"
              });
       }]);
})();
add.html:-
---------------------
<h2>Add New</h2>
<hr>
<table class="employees-app-table">
       <tr>
              <td>First Name</td>
              <td>
                     <input type="text" data-ng-model="employee.firstName">
              </td>
       </tr>
       <tr>
              <td>Last Name</td>
              <td>
                     <input type="text" data-ng-model="employee.lastName">
              </td>
       </tr> 
       <tr>
              <td></td>
              <td>
                     <input type="image" src="/sites/dev/SiteAssets/employees01/images/save.png" alt="Save" data-ng-click="addEmployee(employee)">
                     <input type="image" src="/sites/dev/SiteAssets/employees01/images/cancel.png" alt="Cancel" data-ng-click="cancelEditEmployee(employee)">
              </td>
       </tr>
</table>
all.html:-
---------------------
<div class="all-employees">
       <table>
              <tbody>
                     <tr>
                           <th>First Name</th>
                           <th>Last Name</th>
                           <th>Action</th>
                     </tr>
                     <tr data-ng-repeat="employee in employees">
                           <td>{{employee.FirstName}}</td>
                           <td>{{employee.LastName}}</td>
                           <td>
                                  <a href="#/editEmployee/{{employee.ID}}"><img src="/sites/dev/SiteAssets/employees01/images/edit.png" alt="Edit"></a>
                                  <a href="" data-ng-click="removeEmployee(employee)"><img src="/sites/dev/SiteAssets/employees01/images/delete.png" alt="Delete"></a>
                           </td>
                     </tr>
              </tbody>
       </table>
</div>
<a href="#/addEmployee" class="add-new-button">Add New Employee</a>
edit.html:-
---------------------
<h2>Edit</h2>
<hr>
<table class="employees-app-table">
       <tr>
              <td>First Name</td>
              <td><input type="text" data-ng-model="employee.firstName"></td>
       </tr>
       <tr>
              <td>Last Name</td>
              <td><input type="text" data-ng-model="employee.lastName"></td>
       </tr>
       <tr>
              <td></td>
               <td>
                     <input type="image" src="/sites/dev/SiteAssets/employees01/images/save.png" alt="Save" data-ng-click="editEmployee(employee)">
                     <input type="image" src="/sites/dev/SiteAssets/employees01/images/cancel.png" alt="Cancel" data-ng-click="cancelEditEmployee(employee)">
               </td>
       </tr>
</table>

Employees.txt:-
---------------------
<link href="/sites/dev/SiteAssets/employees01/css/style.css" rel="stylesheet" type="text/css">
<script src="/sites/dev/SiteAssets/employees01/lib/angular.min.js" type="text/javascript"></script>
<script src="/sites/dev/SiteAssets/employees01/lib/angular-route.min.js" type="text/javascript"></script>
<script src="/sites/dev/SiteAssets/employees01/js/app.js" type="text/javascript"></script>
<script src="/sites/dev/SiteAssets/employees01/js/services/baseSvc.js" type="text/javascript"></script>
<script src="/sites/dev/SiteAssets/employees01/js/services/employees/employees.js" type="text/javascript"></script>
<script src="/sites/dev/SiteAssets/employees01/js/controllers/employees/all.js" type="text/javascript"></script>
<script src="/sites/dev/SiteAssets/employees01/js/controllers/employees/add.js" type="text/javascript"></script>
<script src="/sites/dev/SiteAssets/employees01/js/controllers/employees/edit.js" type="text/javascript"></script>
<div data-ng-app="EmployeesApp">
       <div data-ng-view class="employees-app"></div>
</div>

Step 4:-
---------------------
Upload these files into Site Assets.
Step 5:-
---------------------
Create a page and add Content Editor Webpart and 

Step 6:-
---------------------
Test the application.

Featured Post

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management https://docs.microsoft.com/en-us/azure/api-management/api-...

Popular posts