Thursday, 30 June 2016

SharePoint 2013 Crud Operations using AngularJS

Hi Guys !! Today I am gonna write post on using AngularJS in SharePoint. AngularJS is a Javascript MVC framework having 2 way databinding. detailed documentation on AngularJS is written here.

Please let me know for the better solutions using AngularJS in SharePoint as I am new to Angular JS and never used AngularJS in any of project. Simply because I am working on some other thing where AngularJS like excellent framework cant be used. This is just my curiosity to explore AngualrJS in my free time.

In this post I will be doing "Add List Item" and "Read List Items" operations using REST API through AngularJS Service. Since we are using REST API to interact with SharePoint List we will use AngularJS Service. AngularJS factory can also serve the same but using Service seems to be easy for me ;)

we will be creating 1 js file where our services will be defined. lets name it "svcLayer.js" which will have below code:-
brief explanation of the below code
1)  svcApp is an AppModel name which is added below in the HTML(i.e. View)
2) CustomSPService is a name of Service and function is created which has below 2 arguments
    a) $http verb is angularJS object to interact with WebServices.
    b) $q for promises in AngularJS. Promise is required because this would be an sync call and we don't know when our result will be ready

var ngApp = angular.module("svcApp", []);
 ngApp.service("CustomSPService", function CustomSPService($http, $q) {  
//fetchSPListItems  function will take rest service url in the parameter called query
   this.fetchSPListItems = function (query) {  
     var deferred = $q.defer();  
     $http({  
       url: query,  
       method: "GET",  
       headers: {  
         "accept": "application/json;odata=verbose",  
         "content-Type": "application/json;odata=verbose"  
       }  
     })  
       .success(function (data) {  
         deferred.resolve(data);  
       })  
       .error(function (result, status) {  
         deferred.reject(status);  
       });  
     return deferred.promise;  
   };  
//addSPListItems will have 2 parameters 1st rest service url, 2nd data to be posted to SharePoint
   this.addSPListItems = function (query,postDataObj) {  
     var deferred = $q.defer();  
     $http({  
       url: query,  
       method: "POST",  
       headers: {  
         "accept": "application/json;odata=verbose",  
         "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,  
         "content-Type": "application/json;odata=verbose"  
       },  
       data: JSON.stringify(postDataObj)  
     })  
       .success(function (data) {  
         deferred.resolve(data);  
       })  
       .error(function (result, status) {  
         deferred.reject(status);  
       });  
     return deferred.promise;  
   };  
 });  

Since I will be displaying the results of my List through content editor webpart I will be creating one HTML page which will be similar like below:-
brief explanation of the below code
1) while reading controlled I am injecting our above defined AngularJS Service and later on calling the methods of Service.

<!DOCTYPE html>  
 <html lang="en" xmlns="http://www.w3.org/1999/xhtml">  
 <head>  
   <meta charset="utf-8" />  
   <title></title>  
 </head>  
 <body ng-app="svcApp">  
   <div ng-controller="svcController">  
     <h2 ng-repeat="oitem in AllFetched">{{oitem.Title}} {{oitem.FirstName}} {{oitem.City}}</h2>  
     <input type="button" ng-click="AddSPItem()" value="Add Item" />  
   </div>  
 </body>  
 <script src="../Site%20Assets/JS/angular.js"></script>  
 <script src="../Site%20Assets/JS/svcLayer.js"></script>  
 <script type="text/javascript">  
   angular.module("svcApp").controller("svcController", function ($scope, CustomSPService) {  
     $scope.init = function () {  
       $scope.fetchAll();  
     }  
     $scope.fetchAll = function () {  
       console.log("fetchall Called");  
       CustomSPService.fetchSPListItems(_spPageContextInfo.webAbsoluteUrl +  
         "/_api/web/lists/getbytitle('UserList')/items")  
         .then(function (res) {  
           console.log(res);  
           $scope.AllFetched = res.d.results;  
         }, function (err) {  
           console.log(err);  
         })  
     }  
     $scope.AddSPItem = function () {  
       var itemType = "SP.Data.UserListListItem";  
       var vardata = {  
         '__metadata': { 'type': itemType },  
         'Title': 'Mr', 'FirstName': 'XYZ',  
         'City': 'Dubai'  
       };  
       CustomSPService.addSPListItems(_spPageContextInfo.webAbsoluteUrl +  
         "/_api/web/lists/getbytitle('UserList')/items", vardata)  
         .then(function (res) {  
           console.log('Success ' + res);  
           $scope.fetchAll();  
         }, function (err) {  
           console.log(err);  
         })  
     }  
     $scope.init();  
   });  
 </script>  
 </html>