Monday, 23 April 2018

How to Fetch SharePoint List using AngularJS and Display on html Page (Explaining the Codes)

Hello, good to see you again.
I am Kindson and today, I'm going to explain to you how to fetch Sharepoint using AngularJS list and display it in html page. I would try to be very clear and easy to follow in this lesson.
So Let's go!

  1. Introduction
  2. The Building Blocks You Need
  3. Understanding the Pieces of the Your Script
    • Initializing the AngularJS App and Controller
    • The GetList() Function
    • The $.ajax() Method
    • Success Function
    • Error Function
  4. Understanding the Pieces of the your html page
    1. The ng-app directive
    2. The ng-controller directive
    3. The ng-repeat directive
    4. Specifying Repeat Items
  5. Final Notes

1. Introduction

In this simple tutorial, you I explain very clearly and in a simple way the ingredients you need to query a SharePoint list and display the content on a html page.
Note that we can perform SELECT, INSERT, UPDATE and DELETE operations on a SharePoint list using AngularJS. In this lesson, we would examine the select operation and in the following lessons we would learn about the other CRUD operations.
How it works is that AngulaJS makes a REST GET request to the SharePoint list and gets a JSON response. It then parses this response and displays it on a page.
Easy? Right? Let's see! ☺

2. Building Block you Need

1. You Need two  AngularJS files: the angular.js file and the angular-route.js file
2. A html Page to display your results
3. The Script code we would write. In this case, we would include the script in the html file using the <script></script tag. But for very large scripts, a seperate file would be needed

3. Understanding the Pieces of the Your Script

Let's start writting the script and as we write, we would be explaining each piece of the script. So now, create a html file  with the basic content:

<script type="text/javascript" src="angular.1.6.2.js"></script>
<script type="text/javascript" src="angular-route.1.6.2.js"></script>
<title> Fetch HTML List Using AngularJS</title>


AngularJS Code goes here

AngularJS+HTML is used to diaplay list of items in tabular form
Listing 1.0: How AngularJS works in HTML page

From the html file, we would write our AngularJS codes inside the <script></script> part.
The we would  write the html codes inside the <table></table> tag to display the data.

Initializing the AngularJS App and Controller

Write this code inside the script block

        var appVar = angular.module('listApp', ['ngRoute']);
        appVar.controller("controller1", function($scope){    
        GetListItems($scope, "Users");            
Listing 1.1: Initializing AngularJS App and Controller

The first line initializes and AngularJS app called appVar. This is done using angular.module method. This method takes the name of the app (you can choose any name) and a second parameter ['ngRoute']

The second parameter ngRoute according to W3school 'allows you to navigate to different pages in your application, while the application remains a single page application(SPA) with no page reloading.

The GetList() Function
This function could have any name.
It is the function that contains the code that actually performs the query to fetch data from the SharePoint list.

I have added line numbers to the code below, for easy explanation

     function GetList($scope, listName){    
            var requestUrl = "sites/KindsonTheGenuis/Lessons/2018/_api/web/lists/getbytitle('" + listName + "')/items";           
            url: requestUrl,    
            method: "GET",    
            async: false,    
            headers: { "Accept": "application/json;odata=verbose" },    
            success: function(data){    
                $scope.items = data.d.results;    
            error: function(sender,args){    
Listing 1.2: AngularJS code to make GET Request to a URL

The function GetList in line 1 takes two parameters. The first parameter is $scope. This parameters makes is possible for  objects declared in the controller code to be available for use in the html page.
The second parameter listName is the name of the SharePoint list you want to access.

The $.ajax() Method
The $.ajax() method is used to  create ajax request.
It takes the following parameter:
url: a string value of the request url to send the request to
async: indicates if wether the request should be
method: specified the HTML method to use for the request. Here we use a GET methods since we are only retrieving data
headers: specifies the headers  such as contenttype

The next two parameters are functions discussed next

Success Function 
This is a function that is run if the request is successfully  executed. In this case, the fuction takes the results of the request and assigns it to the items collection of the $scope object. This makes is possible that the results are available in the view(html page)

Error Function
This is the fuction that is run if the request fails. In this case a message containing the error is written to the console.

4. Understanding the Pieces of the your html page

The page displays the data from the request. So how does this work?
Remember that the data from the request was put in $scope.items. This means that it  can be accessed from the html page.

<div ng-app="listApp">    
    <div id="App1" ng-controller="controller1">    
        <h1>First List Items</h1>    
        <table border="1">
        <tr ng-repeat="item in items">
Listing 1.3: HTML Page displaying AngularJS Content

The ng-app directive
This helps you to specify the root element of the AngularJs application. All AngularJS application must have a root element in the html page.
If this code is specified in a html element, then AngularJS code could be written inside this element. In our case we made the table element the root element. But you can also place this code in the body element of the html code.

<table ng-app='modulename'>
AngularJS code can go here...
modulename specifiess the name of the module to load with the application. Remember that the modulename is given as parameter to the angular.module() method.

Quiz: What is the modulename from our code? ☺

The ng-controller directive
The ng-controller directive attaches a controller to the view(html page).
This means that the functions and variables defined in the controller will be available in the veiw.(remember, our controller is Controller1)

The ngRepeat directive
The ngRepead directive is added to the html page to iterate through a collection of items. Look at the code fragment so you oculd understand how it works.

In our case we have

<tr ng-repeat="item in items">
<td>{{item.Firstname}} </td>
<td>{{item.Lastname}} </td>

Listing 1.4: Using ng-repeat to display a table

This code would create as many rows as there are items in the $scope

Specifying Repeat Items
Repeat items are specified one element below the element containing the ngRepeat directive. So in our case, the ngRepead directive is in <tr> element, therefore, the repeat elements would be in the <td> tag.
Also, the repeat variables are enclosed in double curly braces, like this {{}}

5. Final Notes

If you hav followed this tutorial up to the end, thumbs up to you. If you have any challenges or observation, you can let me know in the comment box below or in the form to the left of this page.

I would also like to let you know that the key to catching up on software tutorials is to practice them yourselft. Secondly, you can get assistance from experienced professionals like me!
Feel free to leave me a message or question

Thanks for your efforts!