Angular Js
Introduction
This article is about CRUD Operation in SharePoint 2013/2010 using Angular Js.
Let's Start
Let's complete this task in following steps:-
- Create a simple web part page. I have created the same, in my Online SharePoint Site named it as EmpSysDetails.aspx.
- Create a custom list with the columns, which will store values of user input.
- Create an AngularJs folder in Site Assets library. Upload Angular.js file. You can download it from following site https://angularjs.org/ .
- Mention uploaded js script link in html markup file or you can use CDN link.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
- Create html mark-up with ng-app and ng-controller directive.
<div ng-app="myApp" ng-controller="myCtrl">
- Create a Table using ng-repeat directive.
<table class="table" style="margin-left:10px;">
<tr>
<th>
Employee Name
</th>
<th>
Employee Dept
</th>
<th>
Desk No
</th>
<th>
System Alloted
</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr ng-repeat="x in employees">
<td>{{x.EmpName}}</td>
<td>{{x.EmpDept}}</td>
<td>{{x.EmpDeskNo}}</td>
<td ng-if="x.SysAllocated">Yes</td>
<td ng-if="! x.SysAllocated">No</td>
<td><img ng-click="EditItem(x.ID)" ng-src="../SiteAssets/AngularJs/Images/edit.png" width="50px" height="50px" alt="Edit"></img></td>
<td><img ng-click="DeleteItem(x.ID)" ng-src="../SiteAssets/AngularJs/Images/delete-512.png" width="50px" height="50px" alt="Delete"></img></td>
</tr>
</table>
- Create Form Elements,for instance text box and checkbox using ng-model directive.
<div class="container">
<div class="row">
<div class="col-md-8 setrow">
<span class="col-md-4">Title</span> <input class="form-control" type="text" ng-model="title" placeholder="Title" />
</div>
</div>
<div class="row">
<div class="col-md-8 setrow">
<span class="col-md-4">Employee Name</span> <input type="text" class="form-control" ng-model="EmpName" placeholder="Enter Employee Full Name" />
</div>
</div>
</div>
- Include appropriate CSS using Bootstarp.css and custom css.
- Create two separate JavaScript File, name it as appscript.js and sharepointfactory.js.
- appScript.js file contains angular app module and controller code.
- In Controller code inject "$scope" object and "SharePointFactory" service (Name of angular factory).
varapp = angular.module("myApp",[]); app.controller("myCtrl",function($scope,SharePointFactory){ });
- sharepointfactory.js file contains REST API call to do CRUD operation.
- In the mentioned angular factory inject $http and $q service.
app.factory('SharePointFactory', ['$http','$q',function($http,$q) { }]);
- Upload these two files in Site Assets library's AngulaJs folder. Mention script link in the html markup file.
<script src="../SiteAssets/AngularJs/appscript.js"></script>
<script src="../SiteAssets/AngularJs/sharepointfactory.js"></script>
- Edit the EmpSysDetails.aspx. page and add a Script editor webpart.
- Click on Edit Snippet.Copy and paste all the html markup including script link into the editor window.
- Click on Save button present in top bar, ribbon.
EmpSysDetails.aspx looks like as shown below:-

Demystifying sharepointfactory.js file.
Let's dive into REST call to do CRUD operation.All the REST call has been done using $http and
$q service in angular factory written in sharepointfactory.js file.
* Fetch list items from SharePoint list i.e EmployeeList
vargetData =function() {return$http.get(_spPageContextInfo.siteAbsoluteUrl+"/Proctor/_api/Web/Lists/GetByTitle('EmployeeList')/items?select=ID,Title,EmpName,EmpDept,EmpDeskNo,SysAllocated") .then(function(response) {returnresponse.data.value; }); }
* Create a list item in EmployeeList
varcrtItem =function(data) {vardeferred = $q.defer(); $http({ url: _spPageContextInfo.siteAbsoluteUrl+"/Proctor/_api/Web/Lists/GetByTitle('EmployeeList')/items", method: "POST", headers: { "accept": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val(), "content-Type": "application/json;odata=verbose" }, data: JSON.stringify(data) }).then(functionsuccess(response){ deferred.resolve(response); },functionerror(result,status){ deferred.reject(status); });returndeferred.promise; }
* Fetch specific list item from EmployeeList by Id
varedtItem =function(Id) {return$http.get(_spPageContextInfo.siteAbsoluteUrl+"/Proctor/_api/Web/Lists/GetByTitle('EmployeeList')/GetItemById(" + Id + ")") .then(function(response) {returnresponse.data; }); }
* Update specific list item
varupdtitem =function(data){ console.log(data.ID);vardeferred = $q.defer(); $http({ url: _spPageContextInfo.siteAbsoluteUrl+"/proctor/_api/web/lists/getbytitle('employeelist')/getitembyid(" + data.ID + ")", method: "PATCH", headers: { "accept": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val(), "content-type": "application/json;odata=verbose", "X-HTTP-Method": "PATCH", 'IF-MATCH': '*' }, data: JSON.stringify(data) }).then(functionsuccess(response){ deferred.resolve(response); },functionerror(result,status){ deferred.reject(status); });returndeferred.promise; }
* Delete specific list item by Id
vardltItem =function(Id) {vardeferred = $q.defer(); $http({ url: _spPageContextInfo.siteAbsoluteUrl+"/Proctor/_api/Web/Lists/GetByTitle('EmployeeList')/items(" + Id + ")", method: "DELETE", headers: { "accept": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val(), 'IF-MATCH': '*' }, }).then(functionsuccess(response){ deferred.resolve(response); },functionerror(result,status){ deferred.reject(status); });returndeferred.promise; }
*Mention return object in angular factory.
return{ getData: getData , crtItem : crtItem, edtItem : edtItem, dltItem :dltItem, updtitem:updtitem };
Demystifying appScript.js file.
- $scope.employees declared as an array object. getData() method from "SharepointFactory" service to fetch list item and update array object. It will create table row with content in it.
varapp = angular.module("myApp",[]); app.controller("myCtrl",function($scope,SharePointFactory){ $scope.employees = [];// Get all the items from the SharePoint ListSharePointFactory.getData().then(function(emp){ angular.forEach(emp,function(item,index){ $scope.employees.push(item); }); });
2. The event.preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form.
$scope.createItem() event trigger on click of Create Button. It creates an item in list.and updates array object.The powerful feature of angular js - Two-way binding, creates a new row and content in the table.
// Create an Item in SharePoint List$scope.createItem =function(event){ event.preventDefault();vardata = { __metadata: { 'type': 'SP.Data.EmployeeListListItem' }, Title:$scope.title, EmpName:$scope.EmpName, EmpDept:$scope.EmpDept, EmpDeskNo:$scope.EmpDesk, SysAllocated:$scope.SysAllocated }; SharePointFactory.crtItem(data).then(function(response) { $scope.employees.push(response.data.d); $scope.title = ""; $scope.EmpName = ""; $scope.EmpDesk= ""; $scope.EmpDept= ""; $scope.SysAllocated = false; }); };
// Edit an Item in SharePoint List$scope.EditItem = function(ID){ SharePointFactory.edtItem(ID).then(function(emp){ $scope.title = emp.Title; $scope.EmpName = emp.EmpName; $scope.EmpDept = emp.EmpDept; $scope.EmpDesk = emp.EmpDeskNo; $scope.SysAllocated = emp.SysAllocated; $scope.ID = emp.ID; }); };
4. $scope.updateItem() event trigger on click of Update button. It will update the edited item and the splice() method adds/removes items to/from an array. It will update the UI with updated content in table row.
// Update an item in Sharepoint List$scope.updateItem =function(event){ event.preventDefault(); var data = { __metadata: { 'type': 'SP.Data.EmployeeListListItem' }, Title:$scope.title, EmpName:$scope.EmpName, EmpDept:$scope.EmpDept, EmpDeskNo:$scope.EmpDesk, SysAllocated:$scope.SysAllocated, ID:$scope.ID }; SharePointFactory.updtitem(data).then(function(response) { angular.forEach($scope.employees,function(item,index){ if(item.ID == data.ID){ $scope.employees.splice(index,1,data); $scope.title = ""; $scope.EmpName = ""; $scope.EmpDesk= ""; $scope.EmpDept= ""; $scope.SysAllocated = false; } }); }); };
5. $scope.DeleteItem() event trigger on click of Delete Icon in the Table. It will delete the list item and remove that item from the array object.It will remove the row from the table.
// Delete an Item in SharePoint List$scope.DeleteItem =function(ID){ SharePointFactory.dltItem(ID).then(function(emp){ $scope.removeItem($scope.employees,ID); }); }; $scope.removeItem =function(array, ID){ console.log("remove item"); angular.forEach(array,function(item,index){ if(item.ID == ID){ $scope.employees.splice(index,1); $scope.title = ""; $scope.EmpName = ""; $scope.EmpDesk= ""; $scope.EmpDept= ""; $scope.SysAllocated = false; } }); };



NIce work.. But poorly written for others to follow or replicate..
ReplyDeleteIs looks some lines under div id with class=container are missing, don't see all lines input controls for all values and create and update button too. Could you please update?
ReplyDeleteGOOD Article !! Thanks for sharing..
ReplyDeleteSharepoint Online Training
Sharepoint Training
Office 365 Online Training
Office 365 Training