How to Use Angular HTTP Services in SharePoint List

Ahamed Fazil Buhari
 
Senior Developer
October 10, 2016
 
Rate this article
 
Views
12816

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

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

Leave a comment