AngularJS is now best way to work on the MVC pattern at client side. In this post, I will walk you through how we can display the data from a SharePoint list in a SharePoint hosted app using AngularJS and SharePoint REST. My assumption is that you have basic understanding of AngularJS and SharePoint REST.
- Create a SharePoint hosted app.
- Create a Contacts List in app web.
- Add a reference of AngularJS to default.aspx
In the default.aspx, add the below code.
<div ng-app="myApp">
<div ng-controller="customersCtrl">
<table>
<tr>
<th>Last Name</th>
<th>First Name</th>
</tr>
<tr ng-repeat="x in Contacts">
<td>{{ x.Title }}</td>
<td>{{ x.FirstName }}</td>
</tr>
</table>
</div>
</div>
In the above code, ng-app is used to specify that its an AngularJS app and ng-controller is the controller.
Add the below code in the App.JS file.
'use strict';
var myapp = angular.module('myApp', []);
myapp.controller('customersCtrl', function ($scope, $http) {
var restUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Contacts')/items?$select=Title,FirstName";
$http({
method: "GET",
url: restUrl,
headers: { "Accept": "application/json;odata=verbose" }
}).success(function (data) {
$scope.Contacts = data.d.results;
}).error(function (sender,args) {
alert("Error:" + args.message);
});
});
function getQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
Change the restUrl to below if you wanted to query Host Web.
var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
var restUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.AppContextSite(@target)" + "/web/lists/getbytitle('Contacts')/items?$select=Title,FirstName,Company" + "&@target='" + hostUrl + "'";
In the above code, we are getting the results from the contacts lists and assigning it to Contacts collection of $scope.
Add few items in the contacts lists by navigating to Lists/Contacts url
Run the code, the results of the code is something like below