SharePoint Pals
 | Sign In
How to Use Angular HTTP Services in SharePoint List
by Ahamed Fazil Buhari 10 Oct 2016
Author
SharePoint Developer
Visits   
Today  :   13     Total  :    2262

Hello everyone, in this article we will look into the approach on how to Insert, Update and Delete SharePoint List Items using simple HTTP Service provided by AngularJS, please refer my previous article - Basics of AngularJS in SharePoint.

Let me just say few words about Services in AngularJS. A Service in Angular would performs a specific job, like providing the ability to communicate over HTTP or providing a timer or to log our actions etc. Already we’ve used one of the services -> $http and its method get() in my another article, “How to Get all Items in SharePoint List and Display it in Custom HTML table with Sorting using AngularJS”. Below you can find complete list of methods available for $http service.

· $http.get

· $http.post

· $http.put

· $http.delete

· $http.head

· $http.jsonp

· $http.patch

Where this Services fit in Angular framework,

clip_image001

Controllers are responsible for setup the Model and the View consumes the Model. Directives are an intermediary for Model and View.

Directives keep the Model and View separate, but allowing them to communicate indirectly and move data back and forth. For example, if any input value changes, then ng-model directive will push the value back into Model and vice versa.

And one of the many benefits of putting logic into that Service is that the logic will be easy to use anywhere else in the application. We never use a Service directly from a View, because View is about presentation and directives only. Mostly we use post, get and delete methods for CRUD operation on SharePoint list items. Below you can find the syntax for $http service methods

$http.post('/URL/', data, requestHeader);

$http.get(url, [config-optional]);

$http.delete(url, [config-optional]);

Here, Config is nothing but a requestHeader which we use in REST API. In the below example you can find AngularJS $http service to Create, Update and Delete SharePoint List Item. To read the SharePoint List Item, I’ve explained that in my another article named as ‘’How to Get all Items from SharePoint List and Display it in Custom HTML table with Sorting using AngularJS”.

 <script src="../SiteAssets/JS/Form JS/jquery-1.10.2.js"></script>
 <script src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
 
 <script src="../SiteAssets/JS/Form JS/MyAngular.js"></script>
 
 <div id="appDiv" ng-app="myapp">
 	<div id="controllerDiv" ng-controller="MyController">
 		<label ng-show="error" class="ng-hide">Error : {{error}}</label>
 		
 		<h2>Insert into List</h2>		
 		<br /><br />
 		Phone Name : <input type="text" ng-model="phonename" />
 		<br /><br />
 		No. of People Usng : <input type="number" ng-model="pplusing" />
 		<br/><br />
 		<button type="button" ng-click="saveItem()">Save</button>
 		<br/><br/><br/>
 		
 		<h2>Delete or Update List Item</h2>		
 		<br /><br />
 		Enter Item ID :  <input type="text" ng-model="itemID" />
 		<br /><br />
 		New Phone Name : <input type="text" ng-model="newphonename" />
 		<br /><br />
 		New No. of People Usng : <input type="number" ng-model="newpplusing" />
 		<br/><br />		
 		<button type="button" ng-click="deleteItem()">Delete</button>
 		<button type="button" ng-click="updateItem()">Update</button>
     </div>
 </div>
 

In MyAngular.js file the following Angular script should be added,

 (function () { //IIFE 
     var app = angular.module("myapp", []);
     
     var MyController = function ($scope, $http) {               			
 		
 		var urlVal = {
 			url: _spPageContextInfo.webAbsoluteUrl + "/_api" + "/web/lists/GetByTitle('Phone')/Items"
 		};
 		//created json obj to keep track of requestHeader		
 		var requestHeader = {
 				getHeader: {
 					'headers': {
 						'accept': 'application/json;odata=verbose'
 					}
 				},
 				postHeader: {
 					'headers': {
 						"X-RequestDigest": $("#__REQUESTDIGEST").val(),
 			            'content-type': 'application/json;odata=verbose',
 			            'accept': 'application/json;odata=verbose'
 					}
 				},				
 				deleteHeader: {
 					'headers': {
 						"X-RequestDigest": $("#__REQUESTDIGEST").val(),
 			            'content-type': 'application/json;odata=verbose',
 			            "IF-MATCH":"*"
 					}
 				},
 				updateHeader: {
 					'headers': {
 						"X-RequestDigest": $("#__REQUESTDIGEST").val(),
 			            'content-type': 'application/json;odata=verbose',
 			            'accept': 'application/json;odata=verbose',
 			            "IF-MATCH":"*",
 			            "X-HTTP-Method": "MERGE"
 			        }
 				},				
 			};
 			
 		var onSuccess = function(response) {
 				//refreshing all the text box to empty value
 				$scope.phonename = '';
 				$scope.pplusing	= '';
 				$scope.newphonename = '';
 				$scope.newpplusing	= '';
 				$scope.itemID	= '';
 				$scope.error = '';
 				console.log('working');	
 			};
 			
 		var onError = function(reason) {
 				$scope.error = "Could not fetch, something went wrong" + reason;
 			};
 		
 		//Save button click
 		$scope.saveItem = function() {		
 			var createURL = urlVal.url;
 			var data = {
 	   	        //To Get __metadata->'type' value for the list, go to
 //https://<site>/_api/web/lists/getbytitle('<List Name>')?$select=ListItemEntityTypeFullName
 	//from the xml, get the value inside <d:ListItemEntityTypeFullName> element
 				    __metadata: { 'type': 'SP.Data.TestingListItem' },
 				    Title: $scope.phonename,
 				    People_x0020_using: $scope.pplusing		    			    
 				};
 				         				
    	//UpdateFormDigest(_spPageContextInfo.webServerRelativeUrl, _spFormDigestRefreshInterval);
 	//this function is used when the RequestDigest value won’t update nor exist  
 	           
 	       $http.post(createURL, data, requestHeader.postHeader)
 	        	.then(onSuccess, onError);  
 	    }   
 	    
         //Delete Button Click
 	    $scope.deleteItem = function() {
 			var deleteURL = urlVal.url + '(' + $scope.itemID + ')';	    		    	
 	    	$http.delete(deleteURL, requestHeader.deleteHeader)
 	    		.then(onSuccess, onError);
 	    }
 	    
         //Update Button Click
 	    $scope.updateItem = function() {
 	    	var updateURL = urlVal.url + '(' + $scope.itemID + ')';	 
 	    	var updatedata = {	   	        
 				    __metadata: { 'type': 'SP.Data.TestingListItem' },
 				    Title: $scope.newphonename,
 				    People_x0020_using: $scope.newpplusing			    			    
 				};
    	
 	    	$http.post(updateURL, updatedata, requestHeader.updateHeader)
 	    		.then(onSuccess, onError);
 	    }
 
     };
 
     app.controller("MyController", MyController);
 
 } ());
 
 

clip_image003

Happy Coding

Ahamed

blog comments powered by Disqus

SharePoint Pals

Pals
SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile

Training

Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community




SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to articles@sharepointpals.com in a word document.

Related Resources

Recent Tweets

Twitter January 15, 00:25
How To Enable Target Value And Actual Value In #D3 Gauge Chart https://t.co/VxSi4QnNrC

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window https://t.co/EQ7HkoZDkX

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features https://t.co/zAXObHCFpH

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013 https://t.co/LEwnUoI7EY

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services https://t.co/Yvp2VPFIRP

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation