Angularjs SharePoint Online examples

Do you want to know how to use angularjs in SharePoint online? This is article is all about, angularjs sharepoint online examples, we will see how to display SharePoint list items using AngularJS and Rest API.

We will learn here:

  • What is AngularJS and how to use it
  • Advantages of AngularJS
  • Download and Install AngularJS
  • Browser supports in AngularJS
  • AngularJS MVC
  • AngularJS Directive, controllers, scope, events, filters, etc.
  • Display SharePoint list items using angularjs and rest api

This tutorial will help SharePoint developers learn AngularJS.

What is AngularJS?

AngularJS is an MVC (Model-View-Controller) based application that is very much similar to the JavaScript framework. This JavaScript framework is used for building single-page applications which are developed by Google.

The main and important thing about AngularJS is, You can easily use, modify, and also can share this application with others.

AngularJS is also known as Angular which is purely based on JavaScript and HTML. Before starting AngularJS, You need to know the following languages:

  • HTML
  • CSS
  • JavaScript

Advantages of AngularJS

  • The best advantage is, It is supported by Google and also with any Browser like Google Chrome, Firefox, Opera, etc. It also uses in any other platforms like Android and iOS-based phones/tablets.
  • In AngularJS, You can use very less code to build a web application because it is an Open source JavaScript MVC (Model-View-Controller) framework. So that a user can write less code and get more functionality.
  • To use AngularJS, You don’t have to expert in any other scripting languages except HTML and JavaScript.
  • It supports the MVC (Model-View-Controller) design pattern which helps to design the application structure very smoothly.
  • AngularJS is having some Built-in attributes (directives) which makes HTML CSS dynamic.
  • You can easily test the design structure end to end of each and every component.
  • AngularJS uses the Dependency Injection where components are given their dependencies instead of hard coding them within the component.
  • Also, it can use some Directives, filters, modules, routes etc.

AngularJS Download and installation

AngularJS is easy to download and install in a short period of time and also free of cost. To download and install, follow these below steps:

  • Create a folder in your local system with a specific name like AngularJS. Inside this main folder (AngularJS), Create another subfolder called JS to contain your JavaScript files.
  • Click on this below link to download the AngularJS:

Download AngularJS

  • Once you will click on the above link to download the AngularJS, then the below page will appear. Just click on DOWNLOAD ANGULARJS.
sharepoint angular get list items
angularjs installation
  • When you will click on Download AngularJS button, a dialogue box will appear like below screenshot. No need to change anything on that page.
  • Just click on the Download button to start the download process.
angularjs installation steps
angularjs installation steps
  • Once you will click on Download button, a script page will come as shown below. just right click on that page and click on Save as.
sharepoint angular get list items
angularjs download
  • Once the download has completed, Move the downloaded file, angular.min.js, into the JS folder that you created before (assuming you did not save it there directly).
  • Now AngularJS Download and Installation is ready to use.

MVC in AngularJS

MVC stands for Model-View-Controller which is a Software Design Pattern. Before starting the MVC, You should know what is a Software Design Pattern in MVC?

Software Design Pattern is a documented solution to a recurring problem that has been identified by the users/programmers. This Designer Pattern will not give you any code to solve the given problem, although it will give you the proper idea/solution approach to solve the problem.

MVC Design Pattern helps for dividing an application into different parts (called Model, View, and Controller). All parts are having with different responsibilities. Below are the MVC parts:

  • Model: This Model part helps in managing all the application data. It takes the request from view and to the instructions from the controller to update itself. Also, It is a primitive data type such as number, string, boolean, object, etc.
  • View: In AngularJS, This View part helps to display all the application data to the user from the Controller.
  • Controller: Controller works as an intermediate of Model and View. It is a Software code that helps to control the interactions between the Model and View. It receives the inputs, validates it and then performs all the business operations.

AngularJS MVC Architecture Diagram

The below screenshot represents the architecture diagram of AngularJS MVC. How this AngularJS architecture works, I have explained below:

  • The Controller helps to do some business operations by using some business logic. It is the layer where user events trigger the functions that are stored within the controller itself.
  • The View is the presentation layer that helps to view all the data or information to the end-user.
  • Models layer helps to manage and also represent all the information of an end-user. All the data are having primitive declarations. Let’s take an example. Suppose in your organization, You are maintaining a project record of an employee. In this case, Your data model could just have an employee name and id.
sharepoint angular get list items
angularjs mvc architecture

What are AngularJS Directives?

AngularJS Directives are helped to enlarge the HTML with some new attributes. This AnguarJS also defines your own directives.

These AngularJS directives are beginning with “ng-“. This “ng-” is the prefix of AngularJS where this prefix only stands for Angular.

Also, It is having some set of built-in-directives. By using these built-in-directives, you can create various custom directives for your own business application.

The following table list represents some of the important built-in AngularJS directives.

Directive Description
ng-app This directive is an Auto bootstrap AngularJS application.
ng-init This directive helps to Initialize AngularJS variables.
ng-model This directive defines to bind HTML control’s value to a property on the $scope object.
ng-controller This directive helps to attach the controller of MVC to the view.
ng-bind This directive replaces the value of HTML control with the value of specified AngularJS expression.
ng-repeat This directive repeats the HTML template once per each item in the specified collection.
ng-show This directive displays HTML element based on the value of the specified expression.
ng-readonly This directive Makes HTML element read-only based on the value of the specified expression.
ng-disabled This directive helps to set the disabled attribute on the HTML element if the specified expression evaluates to true.
ng-if This directive removes or recreates an HTML element based on an expression.
ng-click This directive specifies custom behavior when an element is clicked.

ng-app Directive:

The basic and main part is, While you start to write the code using AngularJS, Always you need to start the code with the ng-app directive. That’s why it is known as the starting point of AngularJS.

This ng-app directive helps to load the framework automatically in AngularJS. At first in the HTML Document, AngularJS Framework checks the ng-app directive after that document is loaded.

Once the ng-app is found in the document, then it initializes itself and compiles the AngularJS framework.

Always make sure that You should place the ng-app directive at the root of the HTML document in AngularJS. Root of the HTML document means, You can place it within the tag of <html> or <body>.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>ng-app Directive</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body >
    <div>
        {{100*100}}
    </div>
    <div id="myDiv" ng-app>
        {{100+100}}
        <div>
            {{100-100}}
        </div>
    </div>
    <div>
        {{100/100}}
    </div>
</body>
</html>

The below screenshot represents the output of the above example ng-app directive.

ng-app directive
ng-app directive

In this above example, the AngularJS code is executed only the div element which is having id = “myDiv”. That means the AngularJS Framework will only compile the myDiv part and its all child elements. It will not compile that element that is present outside of the ng-app directive.

NOTE:

1. AngularJS Framework will not support to those HTML elements which is out of the ng-app directive. It will only support those HTML elements which is present inside the ng-app directive.
2. In a single HTML document, multiple ng-app directives are not allowed.

ng-app with Module name:

ng-app directive provides an application module name that helps to split different parts of your applications like services, controllers, filters, etc.

<!DOCTYPE html>
<html>
<head>
    <title>ng-app Directive with Module name</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app="angularModule">
    <div>
        {{100*100}}
    </div>
    <div>
        {{100+100}}
        <div>            
            {{100-100}}
        </div>
    </div>
    <script>
        var app = angular.module('angularModule', []);
    </script>
</body>
</html>

As in this above example, I have mentioned a module name using ng-app = ‘angularModule’ in the tag. After writing this code, I have created ‘angularModule’ module using angular.module() function within the script.

NOTE:

Always keep in your mind that the Module name should be same as the name what you have specified it with the ng-app directive.

Manual Bootstrap:

If you don’t want to use the ng-app directive in the AngularJS application, rather than that you want to boot or load the AngularJS application manually without using ng-app directive. So in this case, You can use Manual Bootstrap.

The only difference between the ng-app directive and Manual Bootstrap is, ng-app directive helps to autoload/auto initialize the AngularJS framework and the Manual Bootstrap helps to initialize manually without using the ng-app directive.

Example:

<!DOCTYPE html>
<html >
<head>
    <title>Angular Manual Bootstrap</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body>
    <div>
         {{100*100}}
    </div>
    <div>
        {{100/100}}
        <div>
            {{100+100}}
        </div>   
    </div>
<script>       
     angular.element(document).ready(function () {
         angular.bootstrap(document);
     });
</script>
 </body>
 </html>

In the above example, I have called the bootstrap function angular.bootstrap() function and specified the root element, which is a document object.

ng-init Directive:

In AngularJS Application, the ng-init directive helps to load or initialize all types of variables. You can initialize the variables like String, Array, Number, Object, etc.

How you can initialize all the various variables in AngularJS Framework, You can see in the below example.

Example:

<!DOCTYPE html>
<html >
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body >
    <div ng-app ng-init="employeeName = { firstName:'Bijay', lastName :'Sahu'}; ID = [101, 102]; salary= 50000; message='Welcome to TSInfo Technologies!' ">

		employeeName: {{employeeName.firstName}} <br/>
		ID:           {{ID[1]}}    <br />
		salary:       {{salary}}      <br />
		Message:      {{message}}
    </div>
</body>
</html>

The below screenshot represents the output of the ng-init directive.

sharepoint angular get list items
ng-init directive

In this above example, I have initialized variables as Object, Array, Number, and String. All these variables can be used in anywhere in the Document object element hierarchy.

NOTE:

In this ng-init directive, All the variables cannot be used out of <div> element. All the variables can only be used inside the <div> element.

ng-model Directive:

In the AngularJS Framework, the ng-model directive is used for Two-way data binding.

Two-way data binding specifies the integration between the Model and View. When some information changes in the Model, then the changes will reflect in View also. Similarly, When the information will change in View, then the change will reflect in the Model also.

By using this two-way data binding process, We can know the updates when the change occurs either in Model or View.

ng-model binds some HTML elements like <input>, <select> or <text area> to a specified property in the $scope object.

Example:

<!DOCTYPE html>
<html >
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app>
    <input type="text" ng-model="name" />
    <div>
Thank You {{name}} !!
    </div>
</body>
</html>

The below screenshot represents the output of the ng-model directive.

sharepoint angular get list items
ng-model directive

In this above example, I have set the property using ng-model which can be accessed in a controller using $scope object.

When you will enter some text in the textbox, then that text will appear in that particular place where you have set the value.

NOTE:

No initialized variable in ng-init is attached to the $scope object. Instead of ng-init, ng-model properties are attached to the $scope object.

ng-bind Directive:

In AngularJS, the ng-bind Directive is the type of directive which helps to bind all the properties declared through the $scope or ng-model directive. Also, It helps to provide all updates when data changes.

Example:

<!DOCTYPE html>
<html >
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app>
    <div>
        50 * 50 = <span ng-bind="50 * 50"></span> <br />

        Enter your name: <input type="text" ng-model="name" /><br />
        Hello <span ng-bind="name"></span>
    </div>
</body>
</html>

The below screenshot represents the output of the ng-bind directive.

Retrieve SharePoint List Items Using AngularJS
ng-bind directive

In the above example, I have bound the value “50*50” inside the <span> tag. Similarly, I have bound the value of the model property “name” in the <span> tag.

When you will enter some text in the textbox, then that text will appear in that particular place where you have bound the value. In the above example, I have bound the value after “Hello“, So when I have entered text, the text is appeared after “Hello“.

ng-repeat Directive:

ng-repeat Directive helps to repeat each HTML element once in the specified array collection in the AngularJS Framework.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
    <style>
	div
	{
	width:20%;
	height:50px;
	text-align:center;
	background-color:lightgreen;
	}
     </style>
</head>
<body ng-app ng-init="Employees=['Bijay', 'Preeti', 'Padmini']">
<ol>
<li ng-repeat="name in Employees">
{{name}}
</li>
</ol>
<div ng-repeat="name in Employees">
{{name}}
</div>
</body>
</html>

The below screenshot represents the output of the ng-repeat directive.

how to get data from sharepoint list using angularjs
ng-repeat directive

In the above example, the ng-repeat directive is used with the Employees array. It creates all list <li> element for each item in the Employees array. Similarly, it repeats the elements which are present in the <div> tag.

ng-if Directive:

ng-if Directive helps to build or remove an HTML element based upon the boolean value which depends on the expression in the AngularJS Framework.

If the expression value is true, then it rebuilds an element and if the expression value is false, then it removes an element from the HTML Document.

ng-readonly Directive:

In AngularJS Framework, ng-readonly directive helps to make the HTML element to be read-only based on the boolean value which depends on the expression.

If the expression value is true, then only you can read the HTML element otherwise not.

ng-disabled Directive:

ng-disabled Directive helps to make the HTML element to be disabled based upon the boolean value which depends on the specified expression in the AngularJS Framework.

The HTML element should be disabled if the expression value will true otherwise not.

Examples of ng-if, ng-readonly, and ng-disabled Directive:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
    <style>
        div {
            width: 100%;
            height: 30px;
            display: block;
            margin: 10px 0 0 10px;
        }
    </style>
</head>
<body ng-app ng-init="checked=true" >
    Click Item : <input type="checkbox" ng-model="checked" /> <br />
    <div>
        Add Item: <input ng-if="checked" type="text" />
    </div>
    <div>
        Read-only Item: <input ng-readonly="checked" type="text" value="This item is for read-only purpose." />
    </div>
    <div>
        Disabled Item: <input ng-disabled="checked" type="text" value="This item is for disabled purpose." />
    </div>
</body>
</html>

In this example, When you will check the checkbox (Click Item), then a hidden text box will appear. At the same time, You can only read the item, and also the item will disable as shown below screenshot.

how to get data from sharepoint list using angularjs
ng-if directive

The above example describes the combinations of ng-if, ng-readonly, and ng-disabled.

Also, the Readonly and Disabled Item will appear to do their specific operations depends upon their satisfying condition.

Syntax of AngularJS Directives:

Not only we can use the directives in a single way but also there are many ways to use AngularJS Directives in the AngularJS Framework.

In this AngularJS Directive Syntex, there is not compulsory to use “ng-” prefix/syntax only. Also, You can begin the AngularJS Directive with “x-” or “data-“.

How you can write the AngularJS Directive syntax, Follow the below format that:

data-ng-bind” or “x-ng-bind

In AngularJS Directive, Also the “” can be replaced with “:” or “_” or both. That means, Instead of ““, We can use “:“, “_” or also we can use “” at a time. You can see in the below example:

  • data_ng:repeat or x-ng_repeat
  • data:ng-model or x:ng_model

Also, You can mix the AngularJS Directive syntax as: “data-” or “x-“.

Example:

<!DOCTYPE html>
<html >
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app>
    Enter Name:  <input type="text" ng-model="name" /> <br />
    data-ng-bind: <span data-ng-bind="name"></span><br />  
    data:ng:bind: <span data:ng:bind="name"></span><br />
    x:ng:bind:    <span x:ng:bind="name"></span><br />
    ng:bind:      <span ng:bind="name"></span><br />
    x-ng-bind:    <span x-ng-bind="name"></span><br />
    ng_bind:      <span ng_bind="name"></span>
</body>
</html>

The below screenshot represents the output of AngularJS Directive Syntax. As it is dynamic, So you can enter any name in that text box. Once you will enter one name within the textbox, it will appear in all the directive syntaxes.

how to get data from sharepoint list using angularjs
directive syntax

In the above example, You can see that how we can write an AngularJS Directive syntax in many ways.

AngularJS Controllers

AngularJS controller is the type of control that helps to maintain all the application information or the flow of data within the application.

AngularJS controller is a simple JavaScript function or object which contains some of the attributes or properties and also functions. As Javascript function is used here, So this controller is also a regular Javascript function or Objects.

The ng-controller directive is used for this AngularJS Controller. $scope is a parameter which accepts by each controller. This controller needs to handle the applications which are being referred by the $scope.

$scope is the connection that helps to connect the View and Controller to each other. To know the details about AngularJS Scope, I have mentioned in the below topic.

Note:

The $ sign is used as a prefix in all the built-in objects in AngularJS so that we can differentiate AngularJS built-in objects and other objects.

A controller is a JavaScript Object, Created by a standard JavaScript object constructor.

Example:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myNewApp" ng-controller="myNewCtrl">
Candidate First Name: <input type="text" ng-model="candidateFirstName"><br>
Candidate Last Name: <input type="text" ng-model="candidateLastName"><br>
<br>
Full Name: {{candidateFirstName + " " + candidateLastName}}
</div>
<script>
var app = angular.module('myNewApp', []);
app.controller('myNewCtrl', function($scope) {
    $scope.candidateFirstName = "Preeti";
    $scope.candidateLastName = "Sahu";
});
</script>
</body>
</html>

The below screenshot represents the output of the AngularJS Controller. As this one dynamic, Also you can enter any name in that text box.

angularjs SharePoint
ng controller directive

In this above example, the application will run inside the <div> tag where ng-app specifies as “myNewApp” and ng-controller(refers to AngularJS Directive Controller) specifies as “myNewCtrl“.

myNewCtrl function is a JavaScript function. Here the controller creates two properties i.e. variables in the scope (candidateFirstName and candidateLastName).

ng-model directive helps to bind the input fields to candidateFirstName and candidateLastName properties.

AngularJS Controller methods

A controller is also having some methods in the AngularJS Framework application. You can follow the below example to use the methods in the Controller directives.

Example:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myController">
Person First Name: <input type="text" ng-model="personFirstName"></br>
Person Last Name: <input type="text" ng-model="personLastName"></br>
</br>
Person Full Name: {{fullName()}}
</div>
<script>
var app=angular.module('myApp', []);
app.controller('myController', function($scope){
$scope.personFirstName="Thomas";
$scope.personLastName="Christ";
$scope.fullName= function(){
return $scope.personFirstName + " " + $scope.personLastName;
};
});
</script>
</body>
</html>

The below screenshot represents the output of AngularJS Controller methods.

angularjs sharepoint online examples
ng controller methods

In the above example, I have assigned a function($scope) within the controller. Then I have declared the function in the fullName and it retrieved all the value using $scope object.

External Files Controllers in AngularJS

If there are some larger applications present in AngularJS Framework Application, then it is better to store all the controllers separately via external files.

It is the easiest way to find out all the controllers from each individually external file.

First, create an external file and save that file with extension “.js” i.e. like “externalfiles.js“.

As we have to call this external js file within the HTML document, So in the below example, I will show you how you can call the external js file inside the <script> tag within the HTML document file.

You can see the below code is an HTML Document file where the external file is called within the <script> tag.

Example-1:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myController">
Person First Name: <input type="text" ng-model="personFirstName"></br>
Person Last Name: <input type="text" ng-model="personLastName"></br>
</br>
Person Full Name: {{fullName()}}
</div>
<script src="externalfiles.js">
</script>
</body>
</html>

The below code is the external js file which it is being called within the HTML Document file. If you want to test this example, simply copy this code and paste it with js extension, and then call it within the HTML Document File.

externalfiles.js file:

angular.module('myApp', []).controller('myController', function($scope) {
    $scope.personFirstName = "Preeti",
    $scope.personLastName = "Sharma",
    $scope.fullName = function() {
        return $scope.personFirstName + " " + $scope.personLastName;
    }
});

Now the output is coming as shown in the given screenshot. As it is dynamic, Also you can enter any name in the Person First Name and Person Last Name.

angularjs sharepoint 2013 examples
ng controller external files

Example-2:

Similarly, In the below example, Create a new controller file with the extension as “.js“. This means you save the file as “namesController.js” (As I saved the file as namesController.js).

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="laptopVendorApp" ng-controller="laptopVendorCtrl"> 
<ul>
  <li ng-repeat="x in names">
    {{ x.name + ', ' + x.color }}
  </li>
</ul>
</div>
<script src="namesController.js"></script>
</body>
</html>

namesController.js file:

The below code is the external js file (namesController.js) which it is being called within the HTML Document file. If you want to test this example, simply copy this code and paste it with js extension, and then call it within the HTML Document File.

angular.module('laptopVendorApp', []).controller('laptopVendorCtrl', function($scope) {
    $scope.names = [
        {name:'DELL',color:'White'},
        {name:'HP',color:'Black'},
        {name:'LENOVO',color:'Silver'}
    ];
});

Now the output is coming as shown in the given screenshot. You can see all the laptop name with the given specified color.

angularjs sharepoint 2013
ng contollers external files

AngularJS Scope

AngularJS scope is a built-in object of AngularJS which contains model data. This Javascript object helps to connect the controller with views in the MVC.

The scope is the binding part between the HTML (view) and the JavaScript (controller) which it helps to transfer all the information from the controller to view and as well as from view to controller.

Simply, We can say the scope works as an intermediate of view and controller. Also, this scope object is having some properties and methods. The view can display $scope data using an expression, ng-model, or ng-bind directive, etc.

Note:

The ng-model directive is used for two-way data binding. It transfers the data from controller to view and vice-versa. An expression and ng-bind directive transfers data from controller to view but not vice-versa.

One can define member variables in the scope within the controller which can then be accessed by the view. The $scope object contains various methods. In the below table, You can follow all the important methods of $scope object.

Method Description
$new() This method helps to create a new child scope.
$watch() This method specifies registering a callback to be executed whenever model property changes.
$watchGroup() This method helps to register a callback to be executed whenever model properties change. Here, specify an array of properties to be tracked.
$watchCollection() This method helps to register a callback to be executed whenever the model object or array property changes.
$digest() This method is used to process all of the watchers of the current scope and its children.
$destroy() This method helps to remove the current scope (and all of its children) from the parent scope.
$eval() This method helps to remove the current scope (and all of its children) from the parent scope.
$apply() This method helps to remove the current scope (and all of its children) from the parent scope.
$on() This method is used to register a callback for an event.
$emit() This method helps to dispatch the specified event upwards till$rootScope.
$broadcast() This method helps to dispatch the specified event downwards to all child scopes.

Example-1:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="laptopVendorApp" ng-controller="laptopVendorCtrl">
<h1>{{laptopname}}</h1>
</div>
<script>
var app = angular.module('laptopVendorApp', []);
app.controller('laptopVendorCtrl', function($scope) {
    $scope.laptopname = "DELL";
});
</script>
<p> This is the Dell laptop vendor </p>
</body>
</html>

This is the output that will appear like the below screenshot.

Angularjs with SharePoint 2013
AngularJS scope

In the above example, I have bound the laptop value within the $scope object.

In the view, you do not use the prefix $scope, you just refer to a property name, like {{laptopname}}.

Example-2:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myNewApp" ng-controller="myNewCtrl">
<input ng-model="name">
<h1>This Laptop Color is {{name}}</h1>
</div>
<script>
var app = angular.module('myNewApp', []);
app.controller('myNewCtrl', function($scope) {
    $scope.name = "";
});
</script>
</body>
</html>

This is the output that will appear like the below screenshot.

Angularjs with SharePoint Online
AngularJS Scopes

The above example represents, When you enter any text or name in the input text box, then the changes will affect the model, and it will also affect the name property in the controller.

As in the first screenshot, I did not enter any name or text, So it is appearing only a blank text box. In the second screenshot, I have entered text, So it also affected the controller.

What is a Root Scope in AngularJS?

$rootScope is a type of scope where it contains all the AngularJS applications. This scope helps to create an HTML element that contains the ng-app directive.

Every AngularJS application is having a single $rootScope where all other $rootScope objects are child objects.

Suppose in the scope, there are present two scopes as the current scope and root scope. In this case, both of the current scope and root scope are having with the same variable name, then the application uses the one in the current scope only not the root scope.

All the properties and methods which is attached to $rootScope, will be available to all the controllers.

Example:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myFavFoodApp">
<p>The scope of the root's favorite food:</p>
<h1>{{food}}</h1>
<div ng-controller="myFavFoodCtrl">
<p>The scope of the controller's favorite food:</p>
<h1>{{food}}</h1>
</div>
<p>The scope of the root's favorite food is still:</p>
<h1>{{food}}</h1>
<script>
var app = angular.module('myFavFoodApp', []);
app.run(function($rootScope) {
    $rootScope.food = 'Chocolate';
});
app.controller('myFavFoodCtrl', function($scope) {
    $scope.food = "Ice cream";
});
</script>
</body>
</html>

The below screenshot represents the output of AngularJS Root Scope.

Angularjs with SharePoint Online
AngularJS Root Scope

In this above example, Both scopes i.e. Root scope and Controller scope are having one variable with the same name as “food”.

In the output, You can see that the controller’s food variable does not overwrite with the rootScope’s food value.

Events in AngularJS

If you are creating any web-based application, then your application needs to manage or handle some events like mouse enter, click event, keyboard press event, double click event, change event, etc.

Some additional functionalities which are present in AngularJS can be used to handle such type of various events.

Let’s take an example. Suppose, if you want to process something when you will press some keys of the keyboard. Then, in this case, You can use ng-keypress event directive.

Similarly, if you want to process something when you will hover the mouse, then you can use ng-mouseover event directive and so on.

Below table lists represent all the AngularJS event directives to build some events in your application.

Event Directive Description
ng-blur When an element loses focus, then this expression will execute.
ng-change When the value of an HTML element changes then that time only this expression will execute.
ng-click When the value of an HTML element is clicked then this event will execute.
ng-dblclick When an element is double-clicked then this event will execute.
ng-focus This event will work when an element gets focus.
ng-keydown When a key is pressed then this expression will execute.
ng-keyup This event will execute when a keypress is finished.
ng-keypress When a key is pressed, this event will execute.
ng-mousedown When a mouse button is clicked, this event will execute.
ng-mouseenter When the mouse cursor enters an element, this event will execute at that time.
ng-mouseleave When the mouse cursor leaves an element, at that time this event executes.
ng-mousemove This event will execute when the mouse cursor moves over an element.
ng-mouseover This event will execute when the mouse cursor moves over an element.
ng-mouseup When a mouse click is finished, then this event will execute.

Mouse Events Examples:

There are some events that will occur when the cursor moves over an element. Also, When you will click on a mouse button, then some mouse event will occur. Some of the Mouse Events are:

  • ng-mouseover
  • ng-mouseenter
  • ng-mousemove
  • ng-mouseleave
  • ng-mousedown
  • ng-mouseup
  • ng-click

These are some of the mouse events when you will move the cursor to any element, then it will happen something as related to the specific events.

ng-mouseover:

In this below example, When you will move the cursor to any element, then the mouseover event will occur. On this below code, I have done the count execution, When I will move the cursor to an element, then the count will increment.

This ng-mouseover event is very much similar to the ng-mousemove event. It will execute the same type of operation. That means when you will move the cursor to any element, then it will execute.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-mousemove="count = count + 1">Please Over the Mouse!</h1>
<h2>{{ count }}</h2>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.count = 100;
});
</script> 
</body>
</html>

The below screenshot represents the output of ng-mouse over events. Here, the count starts from 100. When you will move the cursor to element, then it will increment automatically.

SharePoint angularjs
ng mouseover

ng-mouseenter:

Similarly, When you will enter the mouse to any element, then this ng-mouseenter event will occur. You can follow the below code to use this ng-mouseenter event.

In the output, When you will enter the mouse, then the count value will be increment automatically which basically starts from 100.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-mouseenter="count = count + 1">Please Over the Mouse!</h1>
<h2>{{ count }}</h2>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.count = 100;
});
</script> 
</body>
</html>

ng-mouseleave:

This ng-mouseleave event will occur when you will leave the cursor from any element. Here in this below code, it represents when you will leave the cursor from any element, then the count value will increment automatically.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-mouseleave="count = count + 1">Please Over the Mouse!</h1>
<h2>{{ count }}</h2>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.count = 100;
});
</script> 
</body>
</html>

ng-click:

When the element is being clicked by someone, then this ng-click event will occur. In the below code, It represents when you will click the button “Beat Me“, then the count value will increase automatically.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="count = count + 1">Beat Me!</button>
<p>{{ count }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.count = 100;
});
</script> 
</body>
</html>

This is the output of the above ng-click event example when you will beat or click the button, then the count value will increment automatically. As in this HTML Code, I have specified the count value as 100, that’s why the count value increment starts from 100.

Angular SharePoint
ng mouseclick

Toggle Event/ True or False Event:

When you want to do some event or operation once a button or switch is being clicked by someone, then that’s called Toggle Event which works as a Switch.

Suppose you want to show some section of HTML Code once the button is being clicked by someone. At the same time, Again if you want to hide that code once you will click on the button, then, in this case, you can use Toggle Event. Also, it is known as True/False Event in AngularJS.

Example:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="carApp" ng-controller="carCtrl">
<button ng-click="carFunc()">Beat Me!</button>
<div ng-show="showCar">
    <h1>Car:</h1>
    <div>AUDI</div>
    <div>MERCEDESE</div>
    <div>BMW</div>
</div>
</div>
<script>
var app = angular.module('carApp', []);
app.controller('carCtrl', function($scope) {
    $scope.showCar = false;
    $scope.carFunc = function() {
        $scope.showCar = !$scope.showCar;
    }
});
</script>
</body>
</html>

The below screenshot is the output of Toggle switch event/ True or False event. Here, If you will click on the button, then it will show some executed HTML element section. Again, If you will click on the button, then it will hide all the HTML element sections.

angularjs sharepoint online examples
ng show

AngularJS Filters

AngularJS Filters helps to format the data without changing its original format. You can add the filters in HTML expressions by using the pipe (|) sign or character.

This pipe (|) sign is the expression or directive which you can use in AngularJS Filters. This means whenever you will see this (|) pipe sign in your entire HTML code, then you should understand i.e. an AngularJS Filters.

Also, You can write the expression using a filter as I have mentioned in below:

{{ expression | filterName:parameter }}

This AngularJS Filter uses various filters to format data for different data types in AngularJS.

Below table lists represent all the important AngularJS Filters that you can use:

Filter Name Description
Number This filter helps to format a number to a string with comma and fraction.
Currency This filter helps to format a number to a currency format and fraction.
Date This filter helps to format a date to a string in a specified format.
Uppercase This filter helps to convert a string to uppercase.
Lowercase This filter helps to convert a string to lowercase.
Filter This filter helps to select a subset of items from an array and then it returns a new array.
orderBy This filter specifies orders an array by an expression.
Json This filter helps to convert a Javascript object to a JSON string.
limitTo This filter helps to limit an array/string, into a specified number of elements/characters.

Number Filter:

In AnguarJS, this Number filter helps to format numeric data to a string that is separated with a comma and some fraction size.

You can write the Number filter syntax as:

{{ number_expression | number:fractionSize}}

It will display an empty string if the specified expression does not exist.

The below HTML code represents how you can use the Number Filter in AngularJS.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app >
<h1>AngularJS Number Filter Demo: </h1>
    Enter Amount: <input type="number" ng-model="salary" /> <br />
    500000 | number = {{100000 | number}} <br />
    salary | number = {{salary | number}} <br />
    salary | number:2 = {{salary | number:2}} <br />
    salary | number:4 = {{salary | number:4}} <br />
    salary | number = <span ng-bind="salary | number"></span>
</body>
</html>

The below screenshot represents the output of the Number filter.

angularjs sharepoint 2013 examples
AngularJS Number filter

Currency Filter:

In AnguarJS, this Currency filter helps to format a number to a currency format and fraction. When you won’t provide any currency symbol, then it will take the default symbol.

You can write the Currency filter syntax as:

{{ expression | currency : 'currency_symbol' : 'fraction'}}

To test the currency filter, You can use the below-tested currency filter HTML Code.

In this below example, I have used a currency filter to employee.salary, which is a numeric property. It can be displayed with different currency symbols and fractions.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app="currencyApp" >
<h1>AngularJS currency Filter: </h1>
    <div ng-controller="currencyController">
        Default currency: {{employee.salary | currency}} <br />
        Custom currency identifier: {{employee.salary | currency:'Rs.'}} <br/>
        No Fraction: {{employee.salary | currency:'Rs.':0}} <br />
        Fraction 2: <span ng-bind="employee.salary| currency:'GBP':4"></span>
    </div>
    <script>
        var myCurrencyApp = angular.module('currencyApp', []);
        
        myCurrencyApp.controller("currencyController", function ($scope) {
            $scope.employee = { employeeName: 'Preeti', Id: 101, salary: 50000}
        });
    </script>
</body>
</html>

The below screenshot represents the output of the Currency filter.

angularjs sharepoint 2013
AngularJS currency filter

Date Filter:

In AnguarJS, the Date filter helps to format a date to a string in a specified format. You can write the Currency filter syntax as:

{{ date_expression | date : 'format'}}
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app >
<h1>AngularJS Date Filter: </h1>
    <div ng-init="CandidateJoiningDate= 654321789089">
        Default date: {{CandidateJoiningDate| date}} <br />
        Short date: {{CandidateJoiningDate| date:'short'}} <br />
        Long date: {{CandidateJoiningDate | date:'longDate'}} <br />
        Year: {{CandidateJoiningDate | date:'yyyy'}} <br />
    </div>
</body>
</html>

You can see the output of the Date filter in the below screenshot.

Angularjs with SharePoint 2013
AngularJS Date filter

Uppercase Filter/Lowercase Filter:

This Uppercase Filter helps to convert a string to upper case. Similarly, Lowercase Filter helps to convert a string to a Lower case.

To know that how you can use these two filters, You can use the below tested HTML Code.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app >
<h1>AngularJS Uppercase And Lowercase Filter: </h1>
    <div ng-init="student.firstName='Bijay';student.lastName='Kumar'">
        Lower case: {{student.firstName + ' ' + student.lastName | lowercase}} <br />
        Upper case: {{student.firstName + ' ' + student.lastName | uppercase}} 
    </div>
</body>
</html>

You can see the output of the Uppercase and Lowercase filter in the below screenshot.

Angularjs with SharePoint Online
AngularJS Uppercase Lowercase filter

Filter:

In AngularJS, the Filter filter helps to select a subset of items from a specified array, and then it returns a new array. You can write the Filter filter syntax as:

{{ expression | filter : filter_criteria }}
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app="filterApp" >
<h1>AngularJS Filter: </h1>
    <div ng-controller="filterController">
        Enter Name to search: <input type="text" ng-model="searchFilter" /> <br />
        Result: {{filterArr | filter:searchFilter}} 
    </div>
    <script>
        var myApp = angular.module('filterApp', []);
        
        myApp.controller("filterController", function ($scope) {
            $scope.filterArr = ['Bijay', 'Bhawana', 'Preeti', 'Padmini', 'Lakshmi']
        });
    </script>
</body>
</html>

The below screenshot represents the output of Filter where searchFilter contains a text entered in the input box. This searchFilter helps to filter an array from the FilterArr.

In the below output, As I have searched the alphabet “p”, So it is displaying all the array element which is having p.

SharePoint angularjs
AngularJS filter

orderBy Filter:

This orderBy filter specifies orders an array by an expression. You can write the orderBy filter syntax as:

{{ expression | orderBy : predicate_expression : reverse}}

By using this below tested HTML Code you can test orderBy filter in AngularJS.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app="orderByFilterApp" >
<h1>AngularJS orderBy Filter: </h1>
    <div ng-controller="orderByFilterCtrl">
        <select ng-model="SortOrder">
            <option value="+name">Name (asc)</option>
            <option value="-name">Name (dec)</option>
            <option value="+phone">Phone (asc)</option>
            <option value="-phone">Phone (dec)</option>
        </select>
        <ul ng-repeat="travels in travels | orderBy:SortOrder">
            <li>{{travels.name}} - {{travels.phone}}</li>
        </ul>
    </div>
    <script>
        var myApp = angular.module('orderByFilterApp', []);
        
        myApp.controller("orderByFilterCtrl", function ($scope) {
        
            $scope.travels = [{ name: 'Bijay', phone: '512-455-1276' },
                         { name: 'Preeti', phone: '899-333-3345' },
                         { name: 'Lakshmi', phone: '511-444-4321' },
                         { name: 'Padmini', phone: '145-788-5678' },
                         { name: 'Bibhu', phone: '433-444-8765' },
                         { name: 'Bhawana', phone: '218-345-5678' }]
            
            $scope.SortOrder = '+name';
        });
    </script>
</body>
</html>

This is the below output screenshot of the orderBy filter where you can see all the name and phone number is sorted. Below 4 screen represents all the sorted items as in ascending order as well as in descending order.

angularjs SharePoint
AngularJS orderBy Filter

Display SharePoint List items using AngularJS and REST Api

Let us see, how to display dynamic contents from SharePoint List into a presentable format using Angularjs and REST API.

Angular is always best when used for SPA (Single Page Application) and it’s REST friendly as well. In addition, the benefits of REST API are it’s available in an executable format that is fast to retrieve in terms of performance.

Therefore, it is best to combine both in one module to leverage all the benefits.

Display SharePoint List items using AngularJS and REST Api

Below are some prerequisites, which are required before we jump in to implement the below code.

Prerequisites –

  • https://docs.angularjs.org/misc/downloading – To get latest angular.min.js
  • https://jquery.com/download/ – To get latest jquery.min.js
  • Any IDE that supports HTML and Angular i.e. Notepad++, Visual Studio
  • Little knowledge about CSS, HTML, JS, Angular and REST API.

In the below HTML file make sure to add below 3 major references as discussed above in <Head> section.

<head>
<script src="https://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<link rel="stylesheet" href="https://onlysharepoint2013.sharepoint.com/sites/Bhawana/SiteAssets/CSS/stylesheet.css">
</head>

Things to understand before implementation

  • newsAngApp – Angular module defined.
  • spCustomerController – Angular controller defined to bind within the module.
  • GET – REST Api method to fetch the data from the list.
  • Accept”: “application/json;odata=verbose – REST Api header defined.
  • _spPageContextInfo.webAbsoluteUrl – This will return a web absolute url of the site

In our case, it will return “https://onlysharepoint2013.sharepoint.com/sites/Bhawana/”

_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Announcements')/items?$select=Title,ImagePath,Body,Id&$top=6&$orderby=Created"

REST Api endpoint is defined to fetch the data from the ‘Announcements’ list, here in this endpoint we are taking only top=6 items ordered by Created so we can restrict no of records we want to fetch at a time, the max limit is 100.

You can also run the endpoint and see the output in the browser as below.

https://onlysharepoint2013.sharepoint.com/sites/Bhawana/_api/web/lists/getByTitle(‘Announcements’)/items?$select=Title,ImagePath,Body,Id
Angularjs with SharePoint Online
Angularjs with SharePoint Online

News1.html Code:

<html>
<head>
<style>
#contentBox h1
{
color: red !important;
font-weight: bold;
font-family: Futura Bold !important;
}
.tableData
{
font-family: Futura Medium !important;
}
.title-div-left
{
margin: 20px 0px;
border-bottom: .625rem solid #dd1d21;
text-align: left;
padding: 10px 5px;
display: table;
}
Td
{
font-family:Futura Medium (Body);
}
</style>
<script src="https://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<link rel="stylesheet" href="https://onlysharepoint2013.sharepoint.com/sites/Bhawana/SiteAssets/CSS/stylesheet.css">
<script>
var myAngApp = angular.module('newsAngApp', []);
myAngApp.controller('spCustomerController', function ($scope, $http) {
$http({
method: 'GET',
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Announcements')/items?$select=Title,ImagePath,Body,Id&$top=6&$orderby=Created",
headers: { "Accept": "application/json;odata=verbose" }
}).success(function (data, status, headers, config) {
$scope.customers = data.d.results;
alert($parentWebUrl);
}).error(function (data, status, headers, config) {
});
});
</script>
</head>
<div class="title-div-left">
<h1>News & Announcements</h1>
</div>
<br>
<div ng-app="newsAngApp" class="row">
<div ng-controller="spCustomerController" class="span10">
<table class="table table-condensed table-hover">
<tr ng-repeat="customer in customers">
<td>
<img src="{{customer.ImagePath}}" width="140" height="140"></img>
</td>
<td></td>
<td></td>
<td valign="top"><b><div class="tableData"> <a ng-href="https://onlysharepoint2013.sharepoint.com/sites/Bhawana/Lists/Announcements/DispForm.aspx?ID={{customer.Id}}">{{customer.Title}}</a></div></b> <br> <br><div class="tabBody"> {{customer.Body}} .. </div> <br> </td>
</tr>
</table>
</div>
</div>
</html>

You can refer to this HTML file to the content editor’s path URL. So that any modification would be easy.

Please follow the below steps to add a web part to the SharePoint page. Create a web part page and then add a content editor web part into it.

sharepoint online angularjs
sharepoint online angularjs

Then edit the web part and then add the page reference like below:

angularjs SharePoint
angularjs SharePoint

Page URL- /sites/Bhawana/SiteAssets/SitePages/News1.html

Also, you can set the Chrome Type property to None.

Once you save the above changes in the content editor web part property and save the page, you can see the below output.

The main advantage of this module is once this is set up you just need to add or modify data in the list rest it will reflect below. Therefore, maintenance would be easy.

angularjs sharepoint 2013 examples
Display SharePoint list items using angularjs

On the title click, it will navigate to show you the full news as linked below.

angularjs sharepoint online examples
Display SharePoint list items using angularjs

This is how to display SharePoint list items using Angularjs and Rest API.

You may like the following SharePoint Angularjs tutorials:

In this angularjs SharePoint tutorial, we saw angularjs sharepoint online examples and the below topics:

  • What is AngularJS?
  • Advantages of AngularJS
  • AngularJS Download and installation
  • MVC in AngularJS
  • AngularJS MVC Architecture Diagram
  • What are AngularJS Directives?
  • AngularJS Controllers
  • AngularJS Scope
  • Events in AngularJS
  • AngularJS Filters
  • Display SharePoint List items using AngularJS and REST Api
>