Introduction

This sample contains a reusable angularjs module. The module contains a service and a directive. Anyone can use this module throw dependence injection. This is for those people who want to take the advantage of two way data binding in SharePoint client side development. In client side development, basically we make some GET, POST, UPDATE and DELETE request to some particular end-points. So this module will save you from code redundancy for making any HTTP requests. This module is applicable for content editor web part and SharePoint Hosted app development.

Before you begin

Target users requires following knowledges before using this module. I am providing some references of those prerequisites below.

  1. AngularJs
  2. REST API and SharePoint list
  3. SharePoint and AngularJs

Current problem

A typical GET request to get all lists looks like following.

JavaScript
Edit|Remove
function getAllLists() { 
 
    $http({ 
 
        url: "/_api/web/lists" 
 
            method: "GET", 
 
        headers: { 
 
            "accept""application/json;odata=verbose", 
 
            "content-Type""application/json;odata=verbose" 
 
        } 
 
    }).success(function(result) { 
 
        //do something here 
 
    }).error(function(error, status) { 
 
        // do something here 
 
    }); 
}

And a GET request to get all items from a particular list looks like following.

JavaScript
Edit|Remove
function getAllItems() { 
 
    $http({ 
 
        url: "/_api/web/lists/GetByTitle('List Title')/Items" 
 
            method: "GET", 
 
        headers: { 
 
            "accept""application/json;odata=verbose", 
 
            "content-Type""application/json;odata=verbose" 
 
        } 
 
    }).success(function(result) { 
 
        //do something here 
 
    }).error(function(error, status) { 
 
        // do something here 
 
    }); 
}

The purpose of these functions is different but they are sharing most of the code. So this module is taking all hassle of handling GET, POST, UPDATE and DELETE request. You will just pass your data and url to make any kind of request. 

What's included in this module

endPoint is optional in everywhere. I will discuss the usages of it later on. You will be able to use these endpoints those support GET, POST, UPDATE and DELETE request. Every method will return you a promise and you will have to handle it in your code.

How to use 

At first, download this module from attachment. Attachment contains minified and non-minified version of my module. After downloading the file, add the reference in your project. For example, In SharePoint hosted App, It should look like following.

HTML
Edit|Remove
<script src="../Scripts/App/spNgModule.js"></script>

In Content Editor Web Part, you have to upload this file in some library then you will use it.

Adding dependence in your module

You can this dependence in your module in following way. The name of this module is spNgModule.

JavaScript
Edit|Remove
(function () { 
    angular.module("spNgModuleTest", ["spNgModule"]) 
    .constant("IS_APP_WEB", false); 
})();

Here you will have to specify the value of IS_APP_WEB. It means which Web URL will be used for making GET, POST, UPDATE and DELETE request. After specifying the value of IS_APP_WEB, you will be able to use other URL also for making any request. That's why there is an optional parameter named endPoint

NB: If you specify endPoint in your request then url parameter will be optional. By default all requests will be made base on the value of IS_APP_WEB. Either it is APP Web or Host Web.

Injecting Service

The service name I have used is spBaseService. So inject this service in your service. 

JavaScript
Edit|Remove
angular.module("spNgModuleTest") 
    .factory("spNgTestSvc", spNgTestSvc); 
 
    spNgTestSvc.$inject = ["spBaseService"];

GET request example

JavaScript
Edit|Remove
spBaseService.getRequest(query, endPoint)

You can pass any query or end-point that support HTTP GET request. For example,

You want to get all lists under current site

JavaScript
Edit|Remove
function getAllLists() { 
    var query = "/_api/web/lists?$select=Title"; 
    return spBaseService.getRequest(query); 
}

If you want get all items of a list, then it will be

JavaScript
Edit|Remove
function getAllItems() { 
    var query = "/_api/web/lists/GetByTitle('List Title')/Items"; 
    return spBaseService.getRequest(query); 
}

If you want get all sub sites, then it will be

JavaScript
Edit|Remove
function getSubSites() { 
    var query = "/_api/Web/Webs"; 
    return spBaseService.getRequest(query); 
}

So what I wanted to say by these examples is: Just to make a GET request, you will to deal with query or endPoint.

Use of endPoint parameter

Someone may need endPoint in following scenario. 

Let's say your current site is https://xxx.sharepoint.com (can be host web or app web). Now you want to make a GET, POST, UPDATE or DELETE request to the sub site https://xxx.sharepoint.com/hr or a GET, POST, UPDATE or DELETE request to host web from app web. In that case, you will need to use endPoint.

JavaScript
Edit|Remove
function getSubSites() { 
    var endPoint = "https://xxx.sharepoint.com/hr/_api/Web/Webs"; 
    return spBaseService.getRequest(null, endPoint); 
}

POST request example

It is applicable for adding new object (list item, file, site and so on). 

spBaseService.postRequest(data, url, endPoint)

data is the quest body. It will vary request to request. For example, to add a sub site, the request body should look like

JavaScript
Edit|Remove
var data = { 
    parameters: { 
        __metadata: { 
            'type''SP.WebInfoCreationInformation' 
        }, 
        Url: "site url", 
        Title: "site title", 
        Description: "site description", 
        Language: 1033, 
        UseUniquePermissions: true 
    } 
};

url is the any end-point that supports POST request. For adding a sub site, the end-point is 

JavaScript
Edit|Remove
var url = "/_api/web/webinfos/add";

Usages of endPoint can be found  here.

So the full POST request of adding a site is:

JavaScript
Edit|Remove
function addSubSite() { 
    var data = { 
        parameters: { 
            __metadata: { 
                'type''SP.WebInfoCreationInformation' 
            }, 
            Url: "site url", 
            Title: "site title", 
            Description: "site description", 
            Language: 1033, 
            UseUniquePermissions: true 
        } 
    }; 
    var url = "/_api/web/webinfos/add"; 
    return spBaseService.postRequest(data, url); 
}

UPDATE request example

JavaScript
Edit|Remove
spBaseService.updateRequest(data, url, endPoint);

It is all most same as POST request. You can use this method to update any object in your site. Have a look on the updating an item in a particular list.

JavaScript
Edit|Remove
function updateItemById(itemId) { 
    var url = "/_api/web/lists/GetByTitle('List Name')/GetItemById(" + itemId + ")"; 
 
    var data = { 
        __metadata: { 
            type: "SP.Data.SpNgListListItem" 
        }, 
        Title: "New sp ng item updated " + Math.random() 
    }; 
    return spBaseService.updateRequest(data, url); 
}

See here the usages of endPoint.

DELETE request example

JavaScript
Edit|Remove
spBaseService.deleteRequest(url, endPoint);

You will use this method to remove something from your site. Let's say we want to remove an item having ID equals 5.

JavaScript
Edit|Remove
function deleteAnItem() { 
    var url = "/_api/web/lists/GetByTitle('List Name')/GetItemById(5)"; 
    return spBaseService.deleteRequest(url); 
}

See here the usages of endPoint.

File upload example

JavaScript
Edit|Remove
spBaseService.fileUploadRequest(data, url, endPoint);

In request body, you will have to pass the file as ArrayBuffer. As I said earliar, this module also contains a directive so this directive will help you to get file as ArrayBuffer. The name of this directive is customFileChange. The html for uploading should look like

HTML
Edit|Remove
<input type="file" data-custom-file-change="attachment" /> 

attachment is the model and it will give you the file as ArrayBuffer. You can change its name as per your liking. There are two properties you will get from this model such as fileName and fileAsBuffer.

Following is the example of uploading an attachment of a partcular item having ID equals 2.

JavaScript
Edit|Remove
function uploadAttachment(attachment){ 
            var url = "/_api/web/lists/GetByTitle('SpNgList')/items(2)/AttachmentFiles/add(FileName='" + attachment.fileName + "')"; 
            return spBaseService.fileUploadRequest(attachment.fileAsBuffer, url); 
        }

See here the usages of endPoint.

Handling response example

You will get a promise in return from all of the above methods. So it is same as typical response handling angular code. For example

JavaScript
Edit|Remove
spNgTestSvc.addSubSite() 
    .then(function(successResponse) { 
        // code after success 
    }function(errorrResponse) { 
        //code after error 
    });
errorResponse has two properties such as error and statuserrorResponse. error is the actual error as object returned by SharePoint end-point.

Conclusion

That's all about my current module. I will try to make it more better in future updates. As my source is opened so I will be highly pleased if I get any feedback and suggestion from my readers.