Tuesday, 28 March 2017

AngularJS with SharePoint Online

A - OBJECTIVE: 

To retrieve items from SharePoint List or Library using AngularJS

B - REQUIREMENT:

Some expected use cases as follows:

  1. A fully customised page is expected with its own layout (i.e. no SharePoint default list view).
  2. Cross-site collection data aggregation: SharePoint default list view webpart only allows you to extract data from the same site collection, and the client expects you to show data across multiple site collections. AngularJS is one of the best options for you.

C - SOLUTION:

By adopting the AngularJS framework, together with SPServices, you can design your code as follows:
  1. Create an AngularJS app in a SharePoint page
  2. Create a SPServices function to get all data & pass it to AngularJS view
  3. Iterate all items in a list or library using ng-repeat within a particular scope (defined by ng-controller). You can create your own custom filter to display data.

D - SOURCE CODE:

At SharePoint Page: View in MVC
    <p> KEY MESSAGES </p>         <table ng-controller="ControllerKeyMessages"  class="ng-scope">         <tr><th>ID</th>         <th>TITLE</th>         <th>FEO CONTENT OWNER</th>         <th>PUBLISHED</th>         <th>SECTION</th>         <th>PUBLISH DATE</th>         <th>CREATED</th></tr>                 <tr ng-repeat="item in items">         <td align = "center" ng-cloak>{{item.ID}}</td>         <td class="digestLeft" ng-cloak>{{item.Title}}</td>         <td align = "center" ng-cloak>{{item | myTaxonomy}}</td>         <td align = "center" ng-cloak>{{item.Published}}</td>         <td align = "center" ng-cloak>Key Messages</td>         <td align = "center" ng-cloak>{{item.Publish_x0020_Date | date:'d MMM y'}}</td>         <td align = "center" ng-cloak>{{item.Created | date:'d MMM y'}}</td>         </tr>            </table>

At SPServices: Model in MVC

function funcNgGetListItems($scope, $http, webURL, listName, extraColumns){
 $http({
  method: 'GET',
  url: webURL + "/_api/web/lists/GetByTitle('"+listName+"')/Items?$filter=Created gt '2016-01-01T00:00:00.1374695Z'&$top=30&$select=ID,Title,Created,Modified,EncodedAbsUrl" + extraColumns +"&$orderby= Created desc",
  headers: { "Accept": "application/json;odata=verbose" }
 }).success(function(data, status, headers, config){  
  $scope.items = data.d.results;
 }).error(function(data, status, headers, config){
  alert("Error: " + JSON.stringify(data))
 });
}

At AngularJS script: Controller in MVC

var appVar = angular.module('myDigestList', []);

appVar.controller("ControllerKeyMessages", function($scope, $http){
    GetListItems($scope, $http, "https://anthonynhn.sharepoint.com/corpinfo/KM", "Posts", ",FEO_x0020_Content_x0020_Owner,Published,Publish_x0020_Date,Thumbnail1,Publication_x0020_Description");
});

No comments:

Post a Comment