Web Technology
Web Technology
WEB TECHNOLOGIES
*****
MODULE I
EXPERIMENT 1
AIM:
What is node js
Objective:
Explain node JS
Theory:
When people ask, “what are the advantages of Node.js,” its structure is
the reason we give them. It is, after all, the primary reason why it was
created, and a whole ecosystem of dedicated, open-source modules was
created around it.
Whether you‟re developing apps for the iPad, iPhone, or Android, nodes
are what makes this environment so useful to programmers. Because
each task is separated into independent, separate node paths, tasks can
run simultaneously and seamlessly together, without bogging down the
server or using up too much capacity.
1
Advantage of Node JS:
The ability to scale up quickly: Each of the nodes in Node.js is based
around an “event.” A customer buys an in-app purchase, or sends an
email to customer service, for instance. The amount of nodes you can
add to your core programming function are nearly limitless. This means
you can scale vertically, adding new capability paths that lead back to
your core application code. Or, you can scale horizontally, adding new
resources to existing programming. Either way, scalability gives your
application room to grow, and that‟s one of the key benefits of using
Node.js.
2
Node.js Process Model:
The Node.js process model differs from traditional web servers in that
Node.js runs in a single process with requests being processed on a
single thread. One advantage of this is that Node.js requires far fewer
resources. When a request comes in, it will be placed in an event queue.
Node.js uses an event loop to listen for events to be raised for an
asynchronous job. The event loop continuously runs, receiving requests
from the event queue.
There are two scenarios that will occur depending on the nature of the
request. If the request is non-blocking, it does not involve any long-
running processes or data requests, the response will be immediately
prepared and then sent back to the client. In the event the request is
blocking, requiring I/O operations, the request will be sent to a worker
thread pool. The request will have an associated call-back function that
will fire when the request is finished and the worker thread can send the
request to the event loop to be sent back to the client. In this way, when
the single thread receives a blocking request, it hands it off so that the
thread can process other requests in the meantime. In this way Node.js is
inherently asynchronous.
3
Step 2: Install Node.js and NPM from Browser
1. Once the installer finishes downloading, launch it. Open
the downloads link in your browser and click the file. Or, browse to the
location where you have saved the file and double-click it to launch.
2. The system will ask if you want to run the software – click Run.
3. You will be welcomed to the Node.js Setup Wizard – click Next.
4. On the next screen, review the license agreement. Click Next if you
agree to the terms and install the software.
5. The installer will prompt you for the installation location. Leave the
default location, unless you have a specific need to install it somewhere
else – then click Next.
6. The wizard will let you select components to include or remove from
the installation. Again, unless you have a specific need, accept the
defaults by clicking Next.
7. Finally, click the Install button to run the installer. When it finishes,
click Finish.
The system should display the Node.js version installed on your system.
You can do the same for NPM:
npm -v
Starting REPL:
REPL can be started by simply running node on shell/console without any
arguments as follows.
$ node
4
You will see the REPL Command prompt > where you can type any
Node.js command −
$ node
>
Simple Expression
Let's try a simple mathematics at the Node.js REPL command prompt −
$ node
>1+3
4
>1+(2*3)-4
3
>
Node.js – Console:
Node.js console is a global object and is used to print different levels of
messages to stdout and stderr. There are built-in methods to be used for
printing informational, warning, and error messages.
It is used in synchronous way when the destination is a file or a terminal
and in asynchronous way when the destination is a pipe.
Console Methods:
Following is a list of methods available with the console global object.
Sr.No. Method & Description
1 console.log([data][, ...])
Prints to stdout with newline. This function can take multiple
arguments in a printf()-like way.
2 console.info([data][, ...])
Prints to stdout with newline. This function can take multiple
arguments in a printf()-like way.
3 console.error([data][, ...])
Prints to stderr with newline. This function can take multiple
arguments in a printf()-like way.
4 console.warn([data][, ...])
Prints to stderr with newline. This function can take multiple
arguments in a printf()-like way
5 console.dir(obj[, options])
Uses util.inspect on obj and prints resulting string to stdout.
6 console.time(label)
Mark a time.
7 console.timeEnd(label)
Finish timer, record output.
8 console.trace(message[, ...])
Print to stderr 'Trace :', followed by the formatted message and
stack trace to the current position.
9 console.assert(value[, message][, ...])
Similar to assert.ok(), but the error message is formatted as
util.format(message...).
*****
5
MODULE II
EXPERIMENT 1
AIM:
Objective:
Node js callback pattern function callback
Theory:
Callback is an asynchronous equivalent for a function. A callback function
is called at the completion of a given task. Node makes heavy use of
callbacks. All the APIs of Node are written in such a way that they support
callbacks.
For example, a function to read a file may start reading file and return the
control to the execution environment immediately so that the next
instruction can be executed.
Explanation:
Once file I/O is complete, it will call the callback function while passing
the callback function, the content of the file as a parameter. So there is no
blocking or wait for File I/O. This makes Node.js highly scalable, as it can
process a high number of requests without waiting for any function to
return results.
Create a text file named input.txt with the following content :
var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
$ node main.js
6
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Program Ended
AIM:
To demonstrate the event emitter pattern
Objective:
Explanation of event emitter pattern with programme.
Theory:
The EventEmitter is a module that facilitates communication/interaction
between objects in Node. EventEmitter is at the core of Node
asynchronous event-driven architecture. Many of Node‟s built-in modules
inherit from EventEmitter including prominent frameworks like
Express.js.
The concept is quite simple: emitter objects emit named events that cause
previously registered listeners to be called. So, an emitter object basically
has two main features:
Emitting name events.
Registering and unregistering listener functions.
It‟s kind of like a pub/sub or observer design pattern (though not exactly).
Explanation:
The $http.POST() service is used to deliver data to a certain URL and
expects the resource at that URL to handle the request. In other words, the
POST method is used to insert new data based on a specified URL and is
one of the $http service's shortcut methods.
function c1() {
console.log('an event occurred!');
}
function c2() {
console.log('yet another event occurred!');
}
7
myEmitter.emit('eventOne');
an event occurred!
yet another event occurred!
Events:
emitter.removeListener(event, listener)
Remove a listener from the listener array for the specified event. Caution:
changes array indices in the listener array behind the listener.
var callback = function(stream) {
console.log('someone connected!');
};
server.on('connection', callback);
server.removeListener('connection', callback);
emitter.removeAllListeners([event])
AIM:
To demonstrate the use of defer execution of a function
Objective
Implement defer execution in node JS function
Theory:
One occasionally needs to defer the execution of a function.
Traditional JavaScript uses timers for this purpose, with the well-known
setTimeout and setInterval functions.
8
Node introduces another perspective on defers, primarily as means of
controlling the order in which a callback executes in relation to I/O
events, as well as timer events properly.
Two types of deferred event sources that give a developer the ability to
schedule callback executions to occur either before, or after, the
processing of queued I/O events are process.nextTick and setImmediate.
process.nextTick
Explanation
// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter example.');
In the above example, we first import the 'events' module and then
create an object of EventEmitter class. We then specify event handler
function using on() function. The on() method requires name of the
event to handle and callback function which is called when an event is
raised.
The emit() function raises the specified event. First parameter is name of
the event as a string and then arguments. An event can be emitted with
zero or more arguments. You can specify any name for a custom event
in the emit() function.
AIM:
9
Theory:
Using a return is the correct way to stop a function executing. You are
correct in that process.exit() would kill the whole node process, rather than
just stopping that individual function. Even if you are using a callback
function, you'd want to return it to stop the function execution.
Explanation:
var thisIsTrue = false;
if (thisIsTrue) {
response.send('All is good!');
cb(null, response)
} else {
response.send('ERROR! ERROR!');
return cb("THIS ISN'T TRUE!");
}
We should use return, which will help you respond to what happened.
Here's a bit cleaner version, basically first validate whatever you want to
validate, rather than encapsulating everything in if{}else{} statements
a) Throw an error, which will also help you debug the app (wouldn't
completely stop the app, if the test() function was wrapper
in try{}catch(e){}):
AIM:
To demonstrate the use Schedule and repetitive execution
Objective:
Using setTimeout & setInterval Schedule and repetitive execution
10
Theory:
We may decide to execute a function not right now, but at a certain time
later. That‟s called “scheduling a call”.
Explanation:
let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)
Parameters:
func|code
Delay
arg1, arg2…
Arguments for the function (not supported in IE9-)
For instance, this code calls sayHi() after one second:
function sayHi() {
alert('Hello');
}
setTimeout(sayHi, 1000);
With arguments:
11
let timerId = setTimeout(() => alert("never happens"), 1000);
alert(timerId); // timer identifier
clearTimeout(timerId);
alert(timerId); // same identifier (doesn't become null after canceling)
setInterval
The following example will show the message every 2 seconds. After 5
seconds, the output is stopped:
Nested setTimeout
12
The setTimeout above schedules the next call right at the end of the
current one (*).
For instance, we need to write a service that sends a request to the server
every 5 seconds asking for data, but in case the server is overloaded, it
should increase the interval to 10, 20, 40 seconds…
AIM:
To demonstrate the use Block escape event loop
Objective
Using block loop method run node js function
Theory
Now that we have a healthy refresh on how threads work, we can finally
tackle the Node.js event loop logic. By reading this, you will understand
the reason behind the previous explanation, and every piece will go at the
right spot by itself.
Please note that the event loop doesn‟t get generated instantly as soon as
we run our program. In fact, it only runs once the whole program has been
executed.
Explanation:
const fs = require('fs');
function someAsyncOperation(callback) {
// Assume this takes 95ms to complete
fs.readFile('/path/to/file', callback);
}
13
When the event loop enters the poll phase, it has an empty queue
(fs.readFile() has not completed), so it will wait for the number of ms
remaining until the soonest timer's threshold is reached. While it is waiting
95 ms pass, fs.readFile() finishes reading the file and its callback which
takes 10 ms to complete is added to the poll queue and executed. When
the callback finishes, there are no more callbacks in the queue, so the
event loop will see that the threshold of the soonest timer has been reached
then wrap back to the timers phase to execute the timer's callback. In this
example, you will see that the total delay between the timer being
scheduled and its callback being executed will be 105ms.
setTimeout(() => {
const delay = Date.now() - timeoutScheduled;
*****
14
MODULE III
EXPERIMENT 1
AIM:
Objective
Theory:
n Node.js, file handling is handled by fs module. You can read more about
it here. We can check the path for file or directory in Node.js in both
Synchronous and Asynchronous way.
Explanation:
Example:
15
is file ? true
is directory ? true
AIM:
To demonstrate the how to read, write, & close file
Objective:
Explantion of the how to read, write, & close file in node.js
Theory
Reading From Files:
Being able to read from files on your local file system can be hugely
useful and there are a number of different things you can build on top of
this. A log reader, importing information from spreadsheets and xml files
or whatever you can think of, being able to read from files is hugely useful
the file path is File, otherwise returns false. The stats.isDirectory() method
returns true if file path is Directory, otherwise returns false
Explanation:
app.js
var fs = require("fs");
fs.readFile("temp.txt", function(err, buf) {
console.log(buf.toString());
});
var fs = require("fs");
This line does the job of importing the fs package and allowing us to
utilize it within our own code.
AIM:
Demonstrate how to read data in SQL using node js
Objective:
Explanation how to read data in SQL using node js
16
Theory:
NoSQL databases are rather popular among Node developers, with
MongoDB (the “M” in the MEAN stack) leading the pack. When starting
a new Node project, however, you shouldn‟t just accept Mongo as the
default choice. Rather, the type of database you choose should depend on
your project‟s requirements. If, for example, you need dynamic table
creation, or real-time inserts, then a NoSQL solution is the way to go. If
your project deals with complex queries and transactions, on the other
hand, an SQL database makes much more sense.
Explanation:
The steps for querying data in the MySQL database from a node.js
application are as follows:
1. Establish a connection to the MySQL database server.
2. Execute a SELECT statement and process the result set.
3. Close the database connection.
The following select.js program selects all data from the todos table of the
todoapp database:
17
It returned 4 rows as expected.
connection.end();
In this example, we used the question mark (?) as the placeholder value of
the completed field.
>node select2.js
[ RowDataPacket { id: 1, title: 'Learn how to insert a new row', completed:
1 },
RowDataPacket { id: 4, title: 'It should work perfectly', completed: 1 } ]
The select2.js program returns two rows with the completed column is 1,
which means true in Node.js
*****
18
MODULE IV
EXPERIMENT 1
AIM:
Objective:
THEORY:
AngularJS Library:
19
Download AngularJS Library
Select the required version from the popup and click on download
button in the popup.
Editor:
Online Editor:
20
Web server:
Use any web server such as IIS, apache etc., locally for development
purpose
Browser:
Install any browser of your choice as AngularJS supports cross-browser
compatibility. However, it is recommended to use Google Chrome while
developing an application.
Angular Seed:
Use Angular seed project to quickly get started on AngularJS
application. The Angular-seed is an application skeleton for a typical
AngularJS web application. It can be used to quickly bootstrap your
angular webapp projects and development environment for your project.
Download angular-seed from GitHub
Select Web in the left pane and ASP.NET Web Application in the
middle pane and then click OK. In the New ASP.NET Project dialog
box, select Empty template and then click OK.
21
AngularJS in Visual Studio
22
AngularJS in Visual Studio
Search for "angular" in the Manage NuGet Packages dialog box and
install AngularJS Core.
23
AngularJS in Visual Studio
This will add AngularJS files into Scripts folder such as angular.js,
angular.min.js, and angular-mocks.js, as shown below.
ALGORITHM:
STEP 1:
Create a HTML document with <head> and <body> elements, as shown
below.
<!DOCTYPE html>
<html>
24
<head>
</head>
<body>
</body>
</html>
STEP 2:
Include angular.js file in the head section
<!DOCTYPE html>
<html>
<head>
<title>First AngularJS Application</title>
<script src= "~/Scripts/angular.js"></script>
</head>
<body>
</body>
</html>
STEP 3:
PROGRAM
<!DOCTYPE html>
<html>
<head>
<title>First AngularJS Application</title>
<script src= "~/Scripts/angular.js"></script>
</head>
<body ng-app >
<h1>First AngularJS Application</h1>
25
</body>
</html>
Try it
The above example looks like HTML code with some strange attributes
and braces such as ng-app, ng-model, and {{ }}. These built-in
attributes in AngularJS are called directives.
26
Template:
In AngularJS, a template is HTML with additional markups. AngularJS
compiles templates and renders the resultant HTML.
Directive:
Directives are markers (attributes) on a DOM element that tell
AngularJS to attach a specific behavior to that DOM element or even
transform the DOM element and its children. Most of the directives in
AngularJS are starting with ng. It stands for Angular.
Expression:
An expression is like JavaScript code which is usually wrapped inside
double curly braces such as {{ expression }}. AngularJS framework
evaluates the expression and produces a result. In the above example, {{
Num1 * Num2}} will simply display the product of Num1 and Num2.
QUESTIONS
*****
27
EXPERIMENT 2
AIM:
Objective:
Understand basic AngularJS components such as Modules, Directives,
Expressions, Controllers, Services and Filters
Understand the basic design of AngularJS
Build AngularJS forms and bind data to objects
THEORY:
Before creating actual Hello World ! application using AngularJS, let us
see the parts of a AngularJS application. An AngularJS application
consists of following three important parts −
ng-app: This directive defines and links an AngularJS application to
HTML.
ng-model: This directive binds the values of AngularJS application
data to HTML input controls.
ng-bind: This directive binds the AngularJS Application data to HTML
tags.
28
on our computers. This technique is good to use during the development
process but advised against for production code.
ALGORITHM:
Step 4: Bind the value of above model defined using ng-bind directive
<p>Hello <span ng-bind = "name"></span>!</p>
Step 5:
Executing AngularJS Application
Use the above-mentioned three steps in an HTML page.
testAngularJS.htm
Step 6: Output
Open the file testAngularJS.htm in a web browser. Enter your name and
see the result.
PROGRAM
testAngularJS.htm
<html>
<head>
<title>AngularJS First Application</title>
</head>
<body>
<h1>Sample Application</h1>
29
<div ng-app = "">
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
</div>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</body>
</html>
index.html
<hr><!doctype html>
<html ng-app>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</script>
</head>
<body>
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name
here">
<h1>Hello {{yourName}}!</h1>
</div>
</body>
</html>
OUTPUT
sudha
Name:
Hello sudha!
30
QUESTIONS
*****
31
EXPERIMENT 3
AIM:
To create a real AngularJS Application for shopping Cart
Objective:
Use some of the AngularJS features to make a shopping list, where user
can add or remove items:
Shopping List
Milk×
Bread×
Cheese×
Add
THEORY:
32
ALGORITHM
Step 1.
Getting Started:
Start by making an application called myShoppingList, and add a
controller named myCtrl to it.The controller adds an array
named products to the current $scope. In the HTML, use the ng-
repeat directive to display a list using the items in the array.
Example
Make a HTML list based on the items of an array:
<script>
Step 2.
Adding Items:
In the HTML, add a text field, and bind it to the application with the ng-
model directive. In the controller, make a function named addItem, and
use the value of the addMe input field to add an item to
the products array. Add a button, and give it an ng-click directive that will
run the addItem function when the button is clicked.
Example
Now add items to our shopping list:
<script>
var app=angular.module("myShoppingList",[]);
app.controller("myCtrl", function($scope){
$scope.products =["Milk", "Bread", "Cheese"];
$scope.addItem = function (){
$scope.products.push($scope.addMe);
}
});
</script>
33
<div ng-app="myShoppingList" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">{{x}}</li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">Add</button>
</div>
Step 3.
Removing Items:
We also want to be able to remove items from the shopping list.
Example
Now we can remove items from our shopping list:
<script>
var app=angular.module("myShoppingList",[]);
app.controller("myCtrl", function($scope){
$scope.products =["Milk", "Bread", "Cheese"];
$scope.addItem = function (){
$scope.products.push($scope.addMe);
}
$scope.removeItem = function (x){
$scope.products.splice(x, 1);
}
});
</script>
Step 4.
Error Handling:
The application has some errors, like if you try to add the same item twice,
the application crashes. Also, it should not be allowed to add empty items.
34
We will fix that by checking the value before adding new items. In the
HTML, we will add a container for error messages, and write an error
message when someone tries to add an existing item.
Example
A shopping list, with the possibility to write error messages:
<script>
var app=angular.module("myShoppingList",[]);
app.controller("myCtrl", function($scope){
$scope.products =["Milk", "Bread", "Cheese"];
$scope.addItem = function (){
$scope.errortext = "";
if (!$scope.addMe){return;}
if ($scope.products.indexOf($scope.addMe) ==-1){
$scope.products.push($scope.addMe);
} else {
$scope.errortext = "The item is already in your shopping list.";
}
}
$scope.removeItem = function (x){
$scope.errortext = "";
$scope.products.splice(x, 1);
}
});
</script>
Step 5.
Design:
The application works, but could use a better design. Use the W3.CSS
stylesheet to style the application. Add the W3.CSS stylesheet, and include
the proper classes throughout the application, and the result will be the
same as the shopping list at the top of this page.
Example
Style your application using the W3.CSS stylesheet:
35
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"
>
PROGRAM:
<script>
var app=angular.module("myShoppingList",[]);
app.controller("myCtrl", function($scope){
$scope.products =["Milk", "Bread", "Cheese"];
$scope.addItem = function (){
$scope.errortext = "";
if (!$scope.addMe){return;}
if ($scope.products.indexOf($scope.addMe) ==-1){
$scope.products.push($scope.addMe);
} else {
$scope.errortext = "The item is already in your shopping list.";
}
}
$scope.removeItem = function (x){
$scope.errortext = "";
$scope.products.splice(x, 1);
}
});
</script>
OUTPUT:
36
QUESTIONS
*****
37
EXPERIMENT 4
AIM:
Show the use of md-dialog directive and mdDialog service and also the
use of angular dialog boxes.
OBJECTIVE:
THEORY:
$mdDialog opens a dialog over the app to inform users about critical
information or require them to make decisions. There are two approaches
for setup: a simple promise API and regular object syntax.
Restrictions
The dialog is always given an isolate scope.
The dialog's template must have an outer <md-dialog> element. Inside,
use an <md-dialog-content> element for the dialog's content, and use
an <md-dialog-actions> element for the dialog's actions.
Dialogs must cover the entire application to keep interactions inside of
them. Use the parent option to change where dialogs are appended.
PROGRAM
am_dialog.htm\
Href="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angula
r-material.min.css">
<script src
="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min
.js"></script>
<script src
="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-
animate.min.js"></script>
<script src
="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-
aria.min.js"></script>
38
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-
messages.min.js"></script>
<script src =
"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-
material.min.js"></script>
<script language = "javascript">
angular
.module('firstApplication', ['ngMaterial'])
.controller('dialogController', dialogController);
.parent(angular.element(document.querySelector('#dialogContainer')))
.clickOutsideToClose(true)
.title('TutorialsPoint.com')
.textContent('Welcome to TutorialsPoint.com')
.ariaLabel('Welcome to TutorialsPoint.com')
.ok('Ok!')
.targetEvent(ev)
);
};
$scope.showConfirm = function(event) {
var confirm = $mdDialog.confirm()
.title('Are you sure to delete the record?')
.textContent('Record will be deleted permanently.')
.ariaLabel('TutorialsPoint.com')
.targetEvent(event)
.ok('Yes')
.cancel('No');
$mdDialog.show(confirm).then(function() {
$scope.status = 'Record deleted successfully!';
}, function() {
$scope.status = 'You decided to keep your record.';
});
};
$scope.showCustom = function(event) {
$mdDialog.show ({
clickOutsideToClose: true,
scope: $scope,
preserveScope: true,
template: '<md-dialog>' +
39
' <md-dialog-content>' +
' Welcome to TutorialsPoint.com' +
' </md-dialog-content>' +
' </md-dialog>',
controller: function DialogController($scope, $mdDialog) {
$scope.closeDialog = function() {
$mdDialog.hide();
}
}
});
};
}
</script>
</head>
</md-content>
40
</div>
</body>
</html>
OUTPUT
QUESTIONS
*****
41
MODULE 5
EXPERIMENT 1
AIM:
To Develop a Single Page Application Using AngularJS
OBJECTIVE:
Create single page applicaiton in which all the code (JS, HTML, CSS) is
loaded when application loads for the first time. Loading of the dynamic
contents and the navigation between pages is done without refreshing the
page.
THEORY:
Traditionally, applications were Multi-Page Application (MPA) where
with every click a new page would be loaded from the server. This was not
only time consuming but also increased the server load and made the
website slower. AngularJS is a JavaScript-based front-end web framework
based on bidirectional UI data binding and is used to design Single Page
Applications. Single Page Applications are web applications that load a
single HTML page and only a part of the page instead of the entire page
gets updated with every click of the mouse. The page does not reload or
transfer control to another page during the process. This ensures high
performance and loading pages faster. Most modern applications use the
concept of SPA. In the SPA, the whole data is sent to the client from the
server at the beginning. As the client clicks certain parts on the webpage,
only the required part of the information is fetched from the server and the
page is rewritten dynamically. This results in a lesser load on the server
and is cost-efficient. SPAs use AJAX and HTML5 to create a fluid and
responsive Web applications and most of the work happens on the client-
side. Popular applications such as Facebook, Gmail, Twitter, Google
Drive, Netflix, and many more are examples of SPA.
SPAs are good when the volume of data is small and the website that
needs a dynamic platform. It is also a good option for mobile applications.
But businesses that depend largely on search engine optimizations such as
e-commerce applications must avoid single-page applications and opt for
MPAs.
ALGORITHM
Step 1:
Create a Module
AngularJS follows MVC architecture, hence every AngularJS application
contains a module comprising of controllers, services, etc.
var app = angular.module('myApp', []);
42
Step 2:
Define a Simple Controller
app.controller('FirstController', function($scope) {
$scope.message = 'Hello from FirstController';
});
Step 3:
Include AngularJS script in HTML code
Specify the module (created in step 1) in ng-app attribute and the
controller (defined in step 2) in the ng-controller attribute.
<!doctype html>
<html ng-app="myApp">
<head>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"
></script>
</head>
<body ng-controller="FirstController">
<h1>{{message}}</h1>
<script src="app.js"></script>
</body>
</html>
Once the code is run on localhost, the output will be as shown below.
It is now confirmed that our module and controller are set up, and
AngularJS is working properly.
Step 4:
Use AngularJS‟s routing capabilities to add different views to our
SPA
Include angular-route script after the main angular script.
<script src="https://cdnjs. cloudflare.com/ajax/libs/angular.js /1.4.7
/angular.min.js"> </script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>
Use the ngRoute directive to enable routing.
var app = angular.module('myApp', ['ngRoute']);
43
Step 5:
Create an HTML layout for the website
Once an HTML layout for the website is created, use the ng-
view directive to specify the place where the HTML of each page will be
placed in our layout.
<!doctype html>
<html ng-app="myApp">
<head>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>
</head>
<body>
<div ng-view></div>
<script src="app.js"></script>
</body>
</html>
Step 6:
Use $routeProvider service from ngRoute module to configure the
navigation to different views
It is necessary to specify a templateUrl and a controller for each route that
we wish to add.
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'pages/first.html',
controller : 'FirstController'
})
.when('/blog', {
templateUrl : 'pages/second.html',
controller : 'SecondController'
})
.when('/about', {
templateUrl : 'pages/third.html',
controller : 'ThirdController'
})
.otherwise({redirectTo: '/'});
});
44
Step 7:
Build controllers for every route specified in $routeProvider
app.controller('FirstController', function($scope) {
$scope.message = 'Hello from FirstController';
});
app.controller('SecondController', function($scope) {
$scope.message = 'Hello from SecondController';
});
app.controller('ThirdController', function($scope) {
$scope.message = 'Hello from ThirdController';
});
Step 8:
Configure the pages
first.html
<h1>First</h1>
<h3>{{message}}</h3>
second.html
<h1>Second</h1>
<h3>{{message}}</h3>
third.html
<h1>Third</h1>
<h3>{{message}}</h3>
Step 9:
Add links to the HTML that will help in navigating to the configured
pages
<!doctype html>
<html ng-app="myApp">
<head>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>
</head>
<body>
<a href="#/">First</a>
<a href="#/second">Second</a>
<a href="#/third">Third</a>
<div ng-view></div>
<script src="app.js"></script>
</body>
</html>
45
Step 10:
Include the HTML of routing pages to index.html file using script tag
<!doctype html>
<html ng-app="myApp">
<head>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>
</head>
<body>
<script type="text/ng-template" id="pages/first.html">
<h1>First</h1>
<h3>{{message}}</h3>
</script>
<script type="text/ng-template" id="pages/second.html">
<h1>Second</h1>
<h3>{{message}}</h3>
</script>
<script type="text/ng-template" id="pages/third.html">
<h1>Third</h1>
<h3>{{message}}</h3>
</script>
<a href="#/">First</a>
<a href="#/second">Second</a>
<a href="#/third">Third</a>
<div ng-view></div>
<script src="app.js"></script>
</body>
</html>
(When Angular detects the templates defined by the ng-template
directives, it will load its content to the template cache and will not
perform Ajax request to get their content.)
PROGRAM:
<!doctype html>
<html ng-app="myApp">
<head>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>
</head>
46
<body>
<script type="text/ng-template" id="pages/first.html">
<h1>First</h1>
<h3>{{message}}</h3>
</script>
<script type="text/ng-template" id="pages/second.html">
<h1>Second</h1>
<h3>{{message}}</h3>
</script>
<script type="text/ng-template" id="pages/third.html">
<h1>Third</h1>
<h3>{{message}}</h3>
</script>
<a href="#/">First</a>
<a href="#/second">Second</a>
<a href="#/third">Third</a>
<div ng-view></div>
<script src="app.js"></script>
</body>
</html>
Observe that the hyperlinks First, Second, Third on the page are routers
and when you click on them, navigation to the corresponding web pages
occur, without refreshing.
47
QUESTIONS
*****
48
EXPERIMENT 2
AIM:
Create Simple User Registration Form in AngularJS
OBJECTIVE:
User Registration is very basic and common feature in modern web
application. It is one of the basic and most important features for a web
application that is used to authenticate or restrict unauthorized access to
member only areas and features in a web application. The user is required
to register an account using the registration form provided on the
application so the username and password is created in order to login in
the application.
THEORY:
Most of the websites features a Login and Registration link. This is done
to authenticate a user and to provide some extra features/privileges to the
user. The user needs to register himself first so that the username and
password get created in order to enable the login functionality. This
article, leads the user through a step by step process to understand the User
Registration in an Angular platform.
ALGORITHM:
Step 1:
Create registration form
Create a registration form that allows users to create a new account by
filling out a web form. User Registration form will have Name, Email,
Password and Phone as basic registration fields. Registration form will
look like as following –
Step 2
Create index.html and app.js
Create index.html in project‟s root directory and put the following code
in it
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>User Registraion Form - W3Adda</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></
script>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"
></script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.
css">
50
<script src="app.js"></script>
</head>
<body>
<div ng-app = "myApp" class = "container" style="width:550px">
<div style="text-align:center;">
<h3><b>User Registraion Form - W3Adda</b></h3>
</div>
<div ng-controller = "RegisterController">
<div align="right">
<a href="#" ng-click="searchUser()">{{title}}</a>
</div>
<form role = "form" class="well" ng-hide="ifSearchUser">
<div class = "form-group">
<label for = "name"> Name: </label>
<input type = "text" id = "name" class = "form-control" placeholder =
"Enter Name " ng-model = "newuser.name">
</div>
<div class = "form-group">
<label for = "email"> Email: </label>
<input type = "email" id = "email" class = "form-control" placeholder =
"Enter Email " ng-model = "newuser.email">
</div>
<div class = "form-group">
<label for = "password"> Password: </label>
<input type = "password" id = "password" class = "form-control"
placeholder = "Enter Password " ng-model = "newuser.password">
</div>
<div class = "form-group">
<label for = "phone"> Phone: </label>
<input type = "text" id = "phone" class = "form-control" placeholder =
"Enter Phone " ng-model = "newuser.phone">
</div>
<br>
<input type="hidden" ng-model="newuser.id">
<input type="button" class="btn btn-primary" ng-click="saveUser()"
class="btn btn-primary" value = "Submit">
</form>
<div><h4><b>Registered Users</b></h4>
<table ng-if="users.length" class = "table table-striped table-bordered
table-hover">
<thead>
<tr class = "info">
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th ng-if="!ifSearchUser">Action</th>
51
</tr>
</thead>
<tbody>
<tr ng-repeat = "user in users">
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>{{ user.phone }}</td>
<td ng-if="!ifSearchUser">
<a href="#" ng-click="edit(user.id)" role = "button" class = "btn btn-
info">edit</a>
<a href="#" ng-click="delete(user.id)" role = "button" class = "btn btn-
danger">delete</a>
</td>
</tr>
</tbody>
</table>
<div ng-hide="users.length > 0">No Users Found</div>
</div>
</div>
</div>
</body>
</html>
On top of the the form User List link is available to list all the registered
users. Right below the form, list of registered users along
with Edit/Delete button is displayed.
Step 3:
Create AngularJS Application
In this step, create a javascript file app.js in project‟s root directory and
define a AngularJS application.
app.js
var myApp = angular.module("myApp", []);
Step 4:
Create Registration Service
Create a registration service that will be used to add, list, edit and delete users.
Let’s open app.js file and append the following code in it –
myApp.service("RegisterService" , function(){
var uid = 1;
var users = [{
'id' : 0,
'name' : 'John Doe',
'email' : '[email protected]',
'password': 'johndoe',
'phone' : '123-45-678-901'}];
52
// Save User
this.save = function(user)
{
if(user.id == null)
{
user.id = uid++;
users.push(user);
}
else
{
for(var i in users)
{
if(users[i].id == user.id)
{
users[i] = user;
}
}
}
};
// Search User
this.get = function(id)
{
for(var i in users )
{
if( users[i].id == id)
{
return users[i];
}
}
};
// Delete User
this.delete = function(id)
{
for(var i in users)
{
if(users[i].id == id)
{
users.splice(i,1);
}
}
};
// List Users
this.list = function()
{
return users;
53
};
});
Step 5:
Create Registration Controlle
Create a registration controller that will bind add, list, edit and delete action to
registration service. Let’s open app.js file and append the following code in it –
app.js
Register Controller
myApp.controller("RegisterController", function($scope ,
RegisterService){
console.clear();
$scope.ifSearchUser = false;
$scope.title ="User List";
$scope.users = RegisterService.list();
$scope.saveUser = function()
{
console.log($scope.newuser);
if($scope.newuser == null || $scope.newuser == angular.undefined)
return;
RegisterService.save($scope.newuser);
$scope.newuser = {};
};
$scope.delete = function(id)
{
RegisterService.delete(id);
if($scope.newuser != angular.undefined && $scope.newuser.id == id)
{
$scope.newuser = {};
}
};
$scope.edit = function(id)
{
$scope.newuser = angular.copy(RegisterService.get(id));
};
$scope.searchUser = function(){
if($scope.title == "User List"){
$scope.ifSearchUser=true;
$scope.title = "Back";
}
else
{
$scope.ifSearchUser = false;
$scope.title = "User List";
}
};
});
54
Step 6:
Run AngularJS Application
Now start the application server and visit the application to view the
output.
PROGRAM:
var myApp = angular.module("myApp", []);
// Register Service
myApp.service("RegisterService" , function(){
var uid = 1;
var users = [{
'id' : 0,
'name' : 'John Doe',
'email' : '[email protected]',
'password': 'johndoe',
'phone' : '123-45-678-901'}];
// Save User
this.save = function(user)
{
if(user.id == null)
{
user.id = uid++;
users.push(user);
}
else
{
for(var i in users)
{
if(users[i].id == user.id)
{
users[i] = user;
}
}
}
};
// Search User
this.get = function(id)
{
for(var i in users )
{ if( users[i].id == id)
{
return users[i];
}
}
55
};
// Delete User
this.delete = function(id)
{
for(var i in users)
{
if(users[i].id == id)
{
users.splice(i,1);
}
}
};
// List Users
this.list = function()
{
return users;
};
});
// Register Controller
myApp.controller("RegisterController" , function($scope ,
RegisterService){
console.clear();
$scope.ifSearchUser = false;
$scope.title ="User List";
$scope.users = RegisterService.list();
$scope.saveUser = function()
{
console.log($scope.newuser);
if($scope.newuser == null || $scope.newuser == angular.undefined)
return;
RegisterService.save($scope.newuser);
$scope.newuser = {};
};
$scope.delete = function(id)
{
RegisterService.delete(id);
if($scope.newuser != angular.undefined && $scope.newuser.id == id)
{
$scope.newuser = {};
}
};
$scope.edit = function(id)
{
$scope.newuser = angular.copy(RegisterService.get(id));
56
};
$scope.searchUser = function(){
if($scope.title == "User List"){
$scope.ifSearchUser=true;
$scope.title = "Back";
}
else
{
$scope.ifSearchUser = false;
$scope.title = "User List";
}
};
});
OUTPUT
QUESTIONS
*****
57
EXPERIMENT 3
AIM:
To implement form validation in angular js.
OBJECTIVE:
Understand form and input field controls validations in angularjs, different
validation properties of form and input fields in angularjs and different
validation classes of form and input field controls in angularjs. since all
forms come across sending data to server which is a validate input from
the user. So that desired value can be submitted from the form.
THEORY:
AngularJS Form Validations:
1. <input required>
Both of them can be used as per the preference but as per angularjs its
preferred use ng-required attribute.
Syntax of AngularJS Form Validation with Input Fields
Following is the syntax of implementing validations to input fields on
form in angularjs applications.
<form name="personForm">
<input type="text" name="firstname" ng-
model="person.fname" required />
<span ng-
show="personForm.firstname.$error.required">Required!</span>
</form>
58
Observe the above syntax where it is defined required to input control
and showing span element based on validation of input control.
<!DOCTYPE html>
<html>
<head>
<title>
AngularJs Validate Controls in Form
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.m
in.js"></script>
<script type="text/javascript">
var app = angular.module('formApp', []);
app.controller('formCtrl', function ($scope) {
$scope.sendForm = function () {
$scope.msg = "Form Validated";
};
});
</script>
</head>
<body>
<div ng-app="formApp" ng-controller="formCtrl">
<form name="personForm" ng-submit="sendForm()">
First Name:<input type="text" name="firstname" ng-
model="person.fname" required />
<span ng-
show="personForm.firstname.$error.required"> Required! </span>
<br /><br />
Last Name:<input type="text" name="lastname" ng-
model="person.lname" required />
<span ng-
show="personForm.lastname.$error.required"> Required! </span>
<br /><br />
<button type="submit">Submit Form</button><br /><br />
<span>{{msg}}</span>
</form>
</div>
</body>
</html>
59
AngularJS Form and Input Field Validation States:
Angularjs have different properties available for form and input fields that
helps to validate form controls. Following are the different properties
available for form validation in angularjs and all these properties will
return either true or false based on status.
Property Description
$pristine This property helps to know whether form
elements has been modified or not. It will return
true if no form elements has been modified yet
$dirty It returns true if any form elements modified
$invalid It tells whether form element invalid or not
based on rules
$valid It tells whether form element valid or not based
on rules
Following are the different properties available for input controls for
validation in angularjs and all these properties will return
either true or false.
Property Description
$pristine This property helps to know whether form
elements has been modified or not. It will
return true if no form elements has been
modified yet
$dirty It returns true if any form elements modified
Access properties of form and input fields for validationsas shown below
- Access the form properties like <form name>.<angular property>
60
<!DOCTYPE html>
<html>
<head>
<title>
AngularJs Form and Input Validation Controls
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.m
in.js"></script>
</head>
<body>
<div ng-app="">
<form name="personForm">
First Name: <input type="text" name="firstname" ng-
model="person.fname" required />
<span ng-show="personForm.firstname.$touched &&
personForm.firstname.$invalid "> Required! </span><br /><br />
Last Name:<input type="text" name="lastname" ng-
model="person.lname" required />
<span ng-show="personForm.lastname.$dirty &&
personForm.lastname.$valid"> Thanks for Text </span><br /><br />
</form>
</div>
</body>
</html>
Observe above example for first name textbox which is showing error
message when control was touched or blurred and if there is no input text.
Same way for last name textbox shows whether textbox content modified
or not using $dirty property and textbox containing text or
<!DOCTYPE html>
61
<html>
<head>
<title>
AngularJs Applying classes for Form Validation
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.m
in.js"></script>
<style>
form.ng-invalid {
background-color:#f2672e;
}
form.ng-valid {
background-color:#2b8bc0;
}
</style>
</head>
<body>
<div ng-app="">
<form name="personForm">
<br />
First Name:<input type="text" name="firstname" ng-
model="person.fname" required /><br /><br />
Last Name:<input type="text" name="lastname" ng-
model="person.lname" required />
<br /><br />
</form>
</div>
</body>
</html>
In the above code classes are written classes form ng-valid and ng-
invalid properties.
Class Description
ng-pristine It returns true if field has not been modified yet
ng-dirty It returns true if field has been modified
ng-valid It tells whether field content valid or not based on
rules
ng-invalid It tells whether field content invalid or not based on
rules
ng-touched It tells field has been touched or blurred
ng-untouched It tells field has been not touched or blurred yet
62
AngularJS Applying Classes for Input Field Validation:
<!DOCTYPE html>
<html>
<head>
<title>
AngularJs Applying classes for Input Fields Validation
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.m
in.js"></script>
<style>
input.ng-invalid {
background-color:#f2672e;
}
input.ng-valid {
background-color:#2b8bc0;
}
</style>
</head>
<body>
<div ng-app="">
<form name="personForm">
<br />
First Name:<input type="text" name="firstname" ng-
model="person.fname" required /> <br /><br />
Last Name:<input type="text" name="lastname" ng-
model="person.lname" required />
<br /><br />
</form>
</div>
</body>
</html>
In the above code classes are written for input fields ng-valid and ng-
invalid properties.
PROGRAM
<!DOCTYPE html>
<html>
<head>
<title>
AngularJs Form Input Fields Validation Example
</title>
63
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.m
in.js"></script>
<script>
var app = angular.module('formApp', []);
app.controller('formCtrl', function ($scope) {
$scope.sendForm = function () {
$scope.msg='Form Submited Successfully';
};
QUESTIONS
1. What is required or ng-required ? How to use it?
2. What is a form?
3. Write the syntax of implementing validations to input fields on form?
*****
65
MODULE VI
EXPERIMENT 1
AIM :
Create an application using Filters
OBJECTIVE:
A Filter in AngularJS helps to format the value of an expression to
display to the user without changing the original format. For example, if
you want your string in either lowercase or uppercase, you can do it using
filters. There are built-in filters such as 'lowercase', 'uppercase', which can
retrieve the lowercase and uppercase output accordingly. Similarly, for
numbers, you can use other filters.
THEORY:
AngularJS filter is a tool, which we can use to format the data. With this
filter, the user can see and modify according to the requirement. It is added
in angular to format the data that is being displayed on the view part.
SYNTAX OF FILTER:
With pipe character (|), we can add filters in angularJS. Filters can club
with the expression as well as a directive.
SYNTAX:
{{expression| name_of_filter}}
Example: {{name | uppercase}}
Here, a name is the expression and uppercase is the built-in filter provided
by angular. It converts the name in uppercase in view part.
Syntax:
66
{{ expression | filter1 | filter2 | ... }}
Syntax:
{{ expression | filter:argument1:argument2:... }}
1. UPPERCASE:
Uppercase Filter use to convert the string into an uppercase string.
If Uppercase filter is used then the string that is taken as an input in any
format is formatted and gets displayed to the user in an uppercase format
as an output.
Syntax:
{{expression | uppercase}}
2. LOWERCASE:
67
Lowercase Filter in AngularJS uses to convert the string into a lowercase
string.
If a lowercase filter is used then the string that is taken as an input in any
format is formatted and gets displayed to the user in the lowercase format
as an output.
Syntax:
{{expression | lowercase}}
3. CURRENCY:
Currency filter is used to change the convert the number in the specified
currency. In case no symbol of currency is specified then by default the
symbol for current locale is used.
Syntax:
4. FILTER:
It is applied only on array elements. A particular element is selected from
an array based on certain condition and a new array is created from the
existing array.
Syntax:
5. ORDERBY:
It is used to sort the data either in ascending or in descending order.
Syntax:
6. DATE:
Date filter in AngularJS use to convert the date into a string according to
the specified date format.
Syntax:
7. NUMBER:
It is used to format the data or a numerical value taken as an input. It can
add a comma or specified fraction size in it. In case the number expression
doesn‟t contain valid numeric data in that case number filter display an
empty string.
Syntax:
{{ number_expression | number:fractionSize}}
PROGRAM:
testAngularJS.htm
<html>
<head>
<title>Angular JS Filters</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
69
<tr>
<td>Enter subject: </td>
<td><input type = "text" ng-model = "subjectName"></td>
</tr>
</table>
<br/>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
70
{name:'Math',marks:65}
],
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
</script>
</body>
</html>
OUTPUT:
Open the file testAngularJS.htm in a web browser. See the result.
QUESTIONS
1. Define filter?
2. When to use a filter in angularjs?
3. Write the syntax of any one filter type?
4. What is the use of Orderby filter?
5. List out the types of built in filters?
*****
71
EXPERIMENT 2
AIM:
Implement the use of number filter
OBJECTIVE:
Learn
What is angularjs number filter?
Use of number filter in angularjs
How to show number with decimal values
How to limit size of decimal values using angularjs number filter.
THEORY:
In angularjs, number filter is used to format the number and convert it as
string or text. By using number filter in angularjs we can show number
with decimal values and we define limit to show number of decimal
values.
To show number with decimal values the syntax will be as shown below
{{numberexpression | number:fractionsize}}
This line will format the numberValue based on current system locale and
return the formatted value in string.
This line will format the numberValue based on current system locale with
decimal precision of 4 points and return the formatted value in string.
72
This line show whenever Number Filter encounters the numberValue as
undefined, it will return “ ” Empty String value back.
PROGRAM
Index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-number-filter-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="numberFilterExample">
<script>
angular.module('numberFilterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.val = 1234.56789;
}]);
</script>
<div ng-controller="ExampleController">
<label>Enter number: <input ng-model='val'></label><br>
Default formatting: <span id='number-
default'>{{val | number}}</span><br>
No fractions: <span>{{val | number:0}}</span><br>
Negative number: <span>{{-val | number:4}}</span>
</div>
</body>
</html>
Protractor.js
it('should format numbers', function() {
73
expect(element(by.id('number-default')).getText()).toBe('1,234.568');
expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
expect(element(by.binding('-val | number:4')).getText()).toBe('-
1,234.5679');
});
OUTPUT:
QUESTIONS
*****
74
EXPERIMENT 3
AIM:
Implement date filter in angularjs applications
OBJECTIVE:
At times there is a need to check the date for any particular reason. What
happens is that sometimes it is in desired format and sometimes it is not.
AngularJS date filter is used to convert a date into a specified format.
THEORY:
In angularjs, date filter is used to convert date to string based on the given
format. In angularjs, date can be converted to multiple formats using date
filter.
In angularjs different type of date formats are available with date filter.
Following table shows different type of date formats available with date
filter in angularjs.
PROGRAM:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
AngularJs Date filter Example
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.m
in.js"></script>
<script>
var app = angular.module("AngulardateApp", []);
app.controller("datectrl", function ($scope) {
$scope.sampledate = new Date();
});
</script>
</head>
<body ng-app="AngulardateApp">
<div ng-controller="datectrl">
Enter Number: <input type="text" ng-
model="sampledate" style="width:400px" /><br /><br />
76
Date with short expression:{{sampledate | date:"short" }}<br /><br />
Date with mediumDate expression: {{sampledate | date :
"mediumDate"}} <br /><br />
Date with yyyy-mm-dd hh:mm:ss expression: {{sampledate | date : "yyyy-
mm-dd hh:mm:ss" : 0}} <br /><br />
Date with yyyy-mm-dd hh:mm:ss expression: {{sampledate | date :
"dd/mm/yyyy 'at' hh:mma" : 0}}
</div>
</body>
</html>
OUTPUT:
QUESTIONS
*****
77
EXPERIMENT 4
AIM:
Create an application to demonstrate the use of Custom Filters
OBJECTIVE:
AngularJS provides many in-built directives like search. If required,
AngularJS also allows creating custom filters.AngularJS gives a simple
API to create a custom filter. Remember that app.controller() is used to
create controllers and app.module() is used to create modules. In exactly
the same way, AngularJS has given the angular.filter API to create a
custom filter in AngularJS.
THEORY:
Sometimes the built-in filters in Angular cannot meet the needs or
requirements for filtering output. In such a case, an AngularJS custom
filter can be created which can pass the output in the required manner.
78
Custom filter syntax:
PROGRAM:
Index.html
<!DOCTYPE html>
<html>
<head>
<link data-require="[email protected]" data-
semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstra
p/3.1.1/css/bootstrap.min.css" />
<script data-require="angular.js@*" data-semver="1.3.0-
beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script data-require="lodash.js@*" data-
semver="2.4.1" src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/l
odash.js"></script>
79
<script data-require="jquery@*" data-
semver="2.0.3" src="http://code.jquery.com/jquery-
2.0.3.min.js"></script>
<script data-require="bootstrap@*" data-
semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstra
p.min.js"></script>
<link rel="stylesheet" href="style.css"/>
<script src="script.js"></script>
</head>
<table class="table">
<thead>
<tr>
<th>Title</th>
<th>Category</th>
<th>Released</th>
</tr>
</thead>
<tbody>
<tr ng-
repeat="movie in main.movies | filter:{ genre: main.selectedGenre, release
d: main.selectedYear, title: main.selectedTitle}">
<td>{{movie.title}}</td>
<td>{{movie.genre}}</td>
<td>{{movie.released}}</td>
</tr>
</tbody>
</table>
</div>
80
</body>
</html>
Script.js
(function(){
typeOf.movies = movieData.getAll();
typeOf.titles = _.chain(typeOf.movies).pluck("title").uniq().sortBy().
value();
typeOf.genres = _.chain(typeOf.movies).pluck("genre").uniq().sortBy
().value();
typeOf.years = _.chain(typeOf.movies).pluck("released").uniq().sort
By().value();
typeOf.clearTitle = function(){
typeOf.selectedTitle = undefined;
};
typeOf.clearGenre = function(){
typeOf.selectedGenre = undefined;
};
typeOf.clearYear = function(){
typeOf.selectedYear = undefined;
};
});
app.factory("movieData", function(){
var movies = [
{
title: "Godzilla",
genre:"Action",
released: 2014
},
{
title: "Tarzan",
genre: "Action",
81
released: 2013
},
{
title: "Edge Of Tomorrow",
genre: "Action",
released: 2014
},
{
title: "Neighbors",
genre: "Comedy",
released: 2014
},
{
title: "Frozen",
genre: "Comedy",
released: 2013
},
{
title: "Into The Woods",
genre: "Musical",
released: 2014
},
{
title: "Tangled",
genre: "Musical",
released: 2010
}
];
return {
getAll: function(){
return movies;
}
};
});
}
()
);
82
OUTPUT
83
QUESTIONS
*****
84
EXPERIMENT 5
AIM :
Create an applicaiton to demonstrate the use of conditional directives.
OBJECTIVE:
When require some advance feature, to create an angular application
(advanced) like a mouse click, keyboard presses, changes events, moves
etc. The advance application focuses on handling DOM events in
AngularJS. It provides a model to add an event listener in the HTML part.
THEORY:
AngularJS lets you extend HTML with new attributes called Directives.
AngularJS has a set of built-in directives which offers functionality to your
applications. AngularJS also lets you define your own directives.
AngularJS Directives:
AngularJS directives are extended HTML attributes with the prefix ng-.
The ng-app directive initializes an AngularJS application. The ng-
init directive initializes application data. The ng-model directive binds the
value of HTML controls (input, select, textarea) to application data.
The NgIf directive is used when you want to display or remove an element
based on a condition.If the condition is false the element the directive
is attached to will be removed from the DOM.
Important:
The difference between [hidden]='false' and *ngIf='false' is that the first
method simply hides the element. The second method
with ngIf removes the element completely from the DOM.
Syntax
<element ng-if="expression"></element>
Supported by all HTML elements.
85
Parameter Values
Value Description
expression An expression that will completely remove
the element if it returns false. If it returns
true, a copy of the element will be inserted
instead.
PROGRAM
App.js
app.controller('mainCtrl', function($scope){
$scope.txtOptions = {
'1': 'Text Paragraph First',
'2': 'Text Paragraph Second',
'3': 'Text Paragraph Third',
'4': 'Text Paragraph Default'
};
});
Index.html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Conditional directive ng-if and ng-
switch with example</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstra
p.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.m
in.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular
.min.js"></script>
<script src="app.js"></script>
<script src="script.js"></script>
<style>hr{padding:30px 0;}</style>
</head>
<body>
</select>
<br/><br/>
<div ng-switch on="txtOption">
<p ng-switch-
when="1" style="border: 5px solid #000; padding:10px;">Text Paragraph
First</p>
<p ng-switch-
when="2" style="border: 5px solid #000; padding:10px;">Text Paragraph
Second</p>
<p ng-switch-
when="3" style="border: 5px solid #000; padding:10px;">Text Paragraph
Third</p>
<p ng-switch-
default style="border: 5px solid #000; padding:10px;">Text Paragraph De
fault</p>
</div>
</div>
</div>
<p><center>Tutorial: <a href="http://learningturn.com/angular-
js/angularjs-conditional-directive-ng-if-and-ng-switch-with-
example/">AngularJS Conditional directive ngIf and ngSwitch with exam
ple</center></p>
</body>
</html>
Script.js
function changeBg() {
$("#demo-text").css("background-color", "blue");
}
87
OUTPUT
88
QUESTIONS
*****
89
EXPERIMENT 6
AIM:
Create an application to demonstrate the use of style directive
OBJECTIVE:
The ng-style Directive in AngularJS is used to apply custom CSS styles
on an HTML element. The expression inside the ng-style directive must
be an object. It is supported by all the HTML elements.
THEORY:
Syntax
<element ng-style="expression"></element> Supported by all HTML
elements.
Parameter Values:
Value Description
expression An expression which returns an object
where the keys are CSS properties, and the
values are CSS values.
Overview:
The ngStyle directive allows you to set CSS style on an HTML element
conditionally.
Known Issues:
Do not use interpolations in the value of the style attribute, when using
the ngStyle directive on the same element.
Directive Info:
This directive executes at priority level 0.
Usage:
as attribute:
<ANY
ng-style="expression">
...
</ANY>
90
as CSS class:
<ANY class="ng-style: expression;"> ... </ANY>
Arguments:
PROGRAM:
Index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-ng-style-production</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="">
<input type="button" value="set color" ng-
click="myStyle={color:'red'}">
<input type="button" value="set background" ng-
click="myStyle={'background-color':'blue'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</body>
</html>
Protractor.js
var colorSpan = element(by.css('span'));
91
expect(colorSpan.getCssValue('color')).toMatch(/rgba\(0, 0, 0, 1\)|rgb\(0,
0, 0\)/);
});
Style.css
span {
color: black;
}
OUTPUT
92
QUESTIONS
*****
93
EXPERIMENT 7
AIM:
Create an application to demonstrate mouse and keyboard events
directives
OBJECTIVE:
Generally while developing applications different type of html DOM
events like mouse clicks, key press, change events, etc can be used
likewise angularjs is having its own event directives for DOM
interactions.In angularjs different type of DOM event listener directives
are available and which can attach those events to html elements.
THEORY:
AngularJS includes certain directives which can be used to provide
custom behavior on various DOM events, such as click, dblclick,
mouseenter etc. The following table lists AngularJS event directives.
Event Directive
ng-blur
ng-change
ng-click
ng-dblclick
ng-focus
ng-keydown
ng-keyup
ng-keypress
ng-mousedown
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
ng-mouseup
94
mouse events : It occurs when the control of cursor moves over an element
or an element is clicked by mouse event. The order of mouse event when
the cursor moves over an element is:
ng-mouseover
ng-mouseenter
ng-mousemove
ng-mouseleave
PROGRAM
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"
></script>
<style>
.redDiv {
width: 100px;
height: 100px;
background-color: red;
padding:2px 2px 2px 2px;
}
.yellowDiv {
width: 100px;
height: 100px;
background-color: yellow;
padding:2px 2px 2px 2px;
}
</style>
</head>
<body ng-app="myApp" >
<h1>AngularJS ng-click Demo: </h1>
<div ng-controller="myController">
Enter Password: <input type="password" ng-model="password" />
<br /><br />
<button ng-click="DisplayMessage(password)">Show Password</button
</div>
95
<h1>AngularJS Mouse Events Demo: </h1>
<div ng-class="{redDiv: enter, yellowDiv: leave}" ng-
mouseenter="enter=true;leave=false;" ng-
mouseleave="leave=true;enter=false">
Mouse <span ng-show="enter">Enter</span> <span ng-
show="leave">Leave</span>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller("myController", function ($scope, $window) {
$scope.DisplayMessage = function (value) {
alert(value)
}
});
</script>
</body>
</html>
OUTPUT:
Mouse Events:
In the above example, the ng-class directive includes map of CSS
classes, so redDiv will be applied if enter=true and yellowDiv will be
96
applied if leave=true. The ng-mouseenter directive sets 'enter' to true,
which will apply redDiv class to the <div> element. In the same way,
ng-mouseleave will set leave to true, which will apply yellowDiv class.
QUESTIONS
*****
97
EXPERIMENT 8
AIM:
Create an application to demonstrate builtin directives
OBJECTIVE:
Angular provides a number of built-in directives, which are attributes,
added to the HTML elements that give us dynamic behavior.
THEORY:
Directives are markers on a DOM element that tell AngularJS to attach a
specified behavior to that DOM element or even transform the DOM
element and its children. In short, it extends the HTML.
Directive Description
ng-app Auto bootstrap AngularJS application.
ng-init Initializes AngularJS variables
ng-model Binds HTML control's value to a property on the $scope
object.
ng- Attaches the controller of MVC to the view.
controller
ng-bind Replaces the value of HTML control with the value of
specified AngularJS expression.
ng-repeat Repeats HTML template once per each item in the
specified collection.
ng-show Display HTML element based on the value of the
specified expression.
ng-readonly Makes HTML element read-only based on the value of
the specified expression.
ng-disabled Sets the disable attribute on the HTML element if
specified expression evaluates to true.
ng-if Removes or recreates HTML element based on an
expression.
ng-click Specifies custom behavior when an element is clicked.
AngularJS directives are used to extend HTML. They are special attributes
starting with ng-prefix.
ng-app − This directive starts an AngularJS Application.
ng-init − This directive initializes application data.
98
ng-model − This directive defines the model that is variable to be used
in AngularJS.
ng-repeat − This directive repeats HTML elements for each item in a
collection.
ng-ap :
The ng-app directive starts AngularJS and makes the specified element a
root element of the application.
ng-init:
The ng-init directive can be used to initialize variables in AngularJS
application.
ng-model:
The ng-model directive is used for two-way data binding in AngularJS.
It binds <input>, <select> or <textarea> elements to a specified property
on the $scope object. So, the value of the element will be the value of a
property and vica-versa.
ng-bind:
The ng-bind directive binds the model property declared via $scope or
ng-model directive or the result of an expression to the HTML element.
It also updates an element if the value of an expression changes.
ng-repeat:
The ng-repeat directive repeats HTML once per each item in the
specified array collection.
ng-if:
The ng-if directive creates or removes an HTML element based on the
Boolean value returned from the specified expression. If an expression
returns true then it recreates an element otherwise removes an element
from the HTML document.
ng-readonly:
The ng-readonly directive makes an HTML element read-only, based on
the Boolean value returned from the specified expression. If an
expression returns true then the element will become read-only,
otherwise not.
PROGRAM
<!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: 50px;
display: block;
margin: 15px 0 0 10px;
}
</style>
</head>
<body ng-app ng-init="checked=true">
<input type="text" ng-model="name1" />
<div>
Hello {{name1}}
</div><BR><BR>
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 />
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 />
x_ng_bind: <span x_ng_bind="name"></span><br />
ng_bind: <span ng_bind="name"></span><BR><BR>
Click Me: <input type="checkbox" ng-model="checked" /> <br />
<div>
100
New: <input ng-if="checked" type="text" />
</div>
<div>
Read-only: <input ng-readonly="checked" type="text" value="This is
read-only." />
</div>
<div>
Disabled: <input ng-disabled="checked" type="text" value="This is
disabled." />
</div>
</body>
</html>
OUTPUT:
QUESTIONS
*****
101
MODULE VII
EXPERIMENT 1
AIM: Demonstrate controllers in Angular.js through an application
a) Programming Controllers & $scope object
Objective:
Create an application that needs to set up the initial state for the AngularJS
$scope. set up the initial state of a scope by attaching properties to the
$scope object.
THEORY:
The controller in AngularJS is a JavaScript function that maintains the
application data and behavior using $scope object.
This can attach properties and methods to the $scope object inside a
controller function, which in turn will add or update the data and attach
behaviours to HTML elements. The $scope object is a glue between the
controller and HTML.
102
</script>
</body>
</html>
Result:
Hello World!
ALGORITHM:
Steps to create an AngularJS Controller
103
PROGRAM:
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-controller-spicy-2-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="spicyApp2">
<div ng-controller="SpicyController">
<input ng-model="customSpice">
<button ng-click="spicy('chili')">Chili</button>
<button ng-click="spicy(customSpice)">Custom spice</button>
<p>The food is {{spice}} spicy!</p>
</div>
</body>
</html>
app.js
(function(angular) {
'use strict';
var myApp = angular.module('spicyApp2', []);
104
$scope.spicy = function(spice) {
$scope.spice = spice;
};
}]);
})(window.angular);
OUTPUT:
*****
105
EXPERIMENT 2
AIM:
Demonstrate controllers in Angular.js through an application
b) Adding Behavior to a Scope Object
OBJECTIVE:
Create an application that needs to set up the initial state for the AngularJS
to add behavior to the scope by attaching methods to the $scope object.
THEORY:
In order to react to events or execute computation in the view we must
provide behavior to the scope. We add behavior to the scope by attaching
methods to the $scope object. These methods are then available to be
called from the template/view.
Once the Controller has been attached to the DOM, the double method can
be invoked in an AngularJS expression in the template:
<div ng-controller="DoubleController">
Two times <input ng-model="num"> equals {{ double(num) }}
</div>
ALGORITHM:
106
Step 3: Create a controller
ngApp.controller('myController', function ($scope)
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>AngualrJS Controller</title>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
<div id="div1" ng-controller="myController">
Message: {{message}} <br />
<div id="div2">
Message: {{message}}
</div>
</div>
<div id="div3">
Message: {{message}}
</div>
<div id="div4" ng-controller="anotherController">
Message: {{message}}
</div>
<script>
var ngApp = angular.module('myNgApp', []);
107
OUTPUT:
*****
108
EXPERIMENT 3
AIM:
Demonstrate controllers in Angular.js through an application
c) Passing Parameters to the Methods
OBJECTIVE:
Create an application that needs to pass parameters to the methods by
using controllers in Angular.js.
THEORY:
To pass arguments to the controller method, we need to define them with
those number of arguments and while calling them, we need to call them
with that number of arguments.
In the above code snippet, we have declared two functions, Preference and
Preference1. The Preference function accepts only one parameter (lang).
The Preference1 function accepts two parameters (lang and lang1).
On clicking on the first three buttons, we call the Preference method with
only one parameter (language name - English, Hindi etc.) however on
clicking on the 4th button, we call the Preference method and pass two
parameters 'French' and ' and Hindi language also'.
ALGORITHM:
109
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.
js"></script>
<script>
var app = angular.module('app', []);
app.controller('myController', ['$scope', function($scope) {
$scope.Language = 'Hindi';
$scope.Preference = function(lang) {
$scope.Language = lang;
};
OUTPUT:
*****
110
EXPERIMENT 4
AIM:
Demonstrate controllers in Angular.js through an application
d) Listing from array in AngularJS
OBJECTIVE:
Create an application that demonstrates listing from arrays in AngularJS
controllers.
THEORY:
In this case also we shall use ng-repeat directive to list the data from the
array. However, here will see how to list the data from an array that is
declared in JavaScript.
In the HTML code, the ng-app, ng-controller both have been declared in
the same <div> element.
ALGORITHM:
111
<li ng-repeat="username in Usernames">{{username}}</li>
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.m
in.js"></script>
</head>
<body>
<h4>Looping array</h4>
<script>
var usernames = ['Sheo', 'Narayan', 'Dutta'];
</script>
OUTPUT:
Looping array
● Sheo
● Narayan
● Dutta
*****
112
EXPERIMENT 5
AIM:
Program to implement Nested Controllers using angularJS
THEORY:
Angular allows nested controllers. The following example demonstrates
multiple controllers.
ALGORITHM:
Step 1:
Add the script
<script src="~/Scripts/angular.js"></script>
Step 2:
Define the ng-app directive
<body ng-app="myNgApp">
Step 3:
Define the ng-controller directive for parent
<div ng-controller="parentController">
Step 4:
Define the ng-controller directive for child
<div ng-controller="childController">
Step 5:
Create an app module.
var ngApp = angular.module('myNgApp', []);
Step 6:
Create a ngApp controller for parent & pass $scope to function.
ngApp.controller('parentController', function ($scope) {
$scope.message1 = "This is parentController";
});
113
Step 7:
Create a ngApp controller for child & pass $scope to function.
ngApp.controller('childController', function ($scope) {
$scope.message2 = "This is childController";
});
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>AngualrJS Controller</title>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
<div ng-controller="parentController">
Message: {{message1}}
<div ng-controller="childController">
Parent Message: {{message1}} </br>
Child Message: {{message2}}
</div>
Child Message: {{message2}}
</div>
<script>
var ngApp = angular.module('myNgApp', []);
OUTPUT:
Message: This is parentController
Parent Message: This is parentController
Child Message: This is childController
Child Message:
114
QUESTIONS
*****
115
MODULE VIII
EXPERIMENT 1
AIM:
Demonstrate features of Simple Angular.js forms with a program
OBJECTIVE:
Create Simple Angular Forms using different input controls & events.
THEORY:
AngularJS facilitates you to create a form enriched with data binding and
validation of input controls.
Input controls are ways for a user to enter data. A form is a collection of
controls for the purpose of grouping related controls together.
Step 3: Add the the input controls in AngularJS forms using ng-model
<input name = "firstname" type = "text" ng-model = "firstName"
required>
PROGRAM
<!DOCTYPE html>
<html>
<head>
<title>Angular JS Forms</title>
<script src =
"http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.j
s"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: lightpink;
}
table tr:nth-child(even) {
background-color: lightyellow;
}
</style>
117
</head>
<body>
<tr>
<td>Enter last name: </td>
<td><input name = "lastname" type = "text" ng-model
= "lastName" required>
<span style = "color:red" ng-show =
"studentForm.lastname.$dirty &&
studentForm.lastname.$invalid">
<span ng-show =
"studentForm.lastname.$error.required">Last Name is
required.</span>
</span>
</td>
</tr>
<tr>
<td>Email: </td><td><input name = "email" type =
"email" ng-model = "email" length = "100" required>
<span style = "color:red" ng-show =
"studentForm.email.$dirty && studentForm.email.$invalid">
<span ng-show =
"studentForm.email.$error.required">Email is required.</span>
<span ng-show =
"studentForm.email.$error.email">Invalid email address.</span>
</span>
</td>
</tr>
<tr>
118
<td>
<button ng-click = "reset()">Reset</button>
</td>
<td>
<button ng-disabled = "studentForm.firstname.$dirty
&&
studentForm.firstname.$invalid ||
studentForm.lastname.$dirty &&
studentForm.lastname.$invalid ||
studentForm.email.$dirty &&
studentForm.email.$invalid" ng-
click="submit()">Submit</button>
</td>
</tr>
</table>
</form>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.reset = function(){
$scope.firstName = "idol";
$scope.lastName = "mumbai university";
$scope.email = "[email protected]";
}
$scope.reset();
});
</script>
</body>
</html>
OUTPUT:
*****
119
EXPERIMENT 2
AIM:
Demonstrate Select & Option features of Angular.js forms with a program
OBJECTIVE:
Create Simple Angular Forms that demonstrate drop-down list using select
and option directive.
THEORY:
In AngularJS, we can create a dropdown list (select box) based on items in
an array, or an object.
Using ng-options:
We should use the ng-option directive to create a dropdown list, based on
an object or an array in AngularJS.
We can also use the ng-repeat directive to make the same dropdown list as
ng-options.
Limitation of ng-repeat:
The ng-repeat directive has a limitation that the selected value must be a
string:
While using the ng-options directive, you can select an object value:
$scope.cars = {
car01 : "Ford",
car02 : "Honda",
car03 : "Volvo",
120
car03 : "Hundai",
};
ALGORITHM:
PROGRAM:
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angula
r.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Select a car:</p>
<select ng-model="selectedCar">
<option ng-repeat="x in cars"
value="{{x.model}}">{{x.model}}</option>
</select>
<h1>You selected: {{selectedCar}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.cars = [
{model : "Ford", color : "red"},
{model : "Honda", color : "white"},
{model : "Volvo", color : "black"},
121
{model : "Hundai", color : "gray"}
];
});
</script>
</body>
</html>
OUTPUT:
*****
122
EXPERIMENT 3
AIM:
Demonstrate Input Validation features of Angular.js forms with a program
OBJECTIVE:
Create Simple Angular Forms that demonstrate input validation to name,
address, contact number and email address fields.
THEORY
AngularJS provides client-side form validation. It checks the state of the
form and input fields (input, textarea, select), and lets its notify the user
about the current state. It also holds the information about whether the
input fields have been touched, or modified, or not.
Required:
Adding the required HTML5 tag to an input field validates whether the
field is empty or not. This ensures that the field should have some value.
The following syntax is used for required input.
<input type="text" required />
The following syntax is used to make sure that the input field should not
be empty. We can set it to false if you do not want to restrict this.
<input type="text" ng-required="true" />
Minimum Length:
The directive ng-minlength is used to validate the minimum length of the
input value. This will make sure that the length of the entered value is not
less than the value set using ng-minlength directive.
<input type="text" ng-minlength=10 />
123
Maximum Length:
The directive ng-maxlength is used to validate the maximum length of the
input value. This will make sure that the length of the entered value is not
more than the value set using ng-max length directive.
<input type="text" ng-maxlength=20 />
Pattern:
The ng-pattern directive is used to ensure that an input matches a regex
pattern, the following syntax is used. The ng-pattern directive returns true
if input text is validated as per expression otherwise it returns false.
<input type="text" ng-pattern="[a-zA-Z]" />
Email:
We can set the input type to email to ensure that the input field is a valid
email id.
<input type="email" name="email" ng model="user.email" />
Number:
We can set the input type to number to ensure that the input field is a
number.
<input type="number" name="age" ng-model="user.age" />
URL:
We can set the input type to url to ensure that the input field is a url.
<input type="url" name="homepage" ng-model="user.url" />
Input State:
AngularJS is constantly updating the state of both the form and the input
fields.
They are all properties of the input field, and are either true or false.
Form State:
Forms have the following states:
• $pristine No fields have been modified yet
• $dirty One or more have been modified
• $invalid The form content is not valid
• $valid The form content is valid
124
• $submitted The form is submitted
They are all properties of the form, and are either true or false.
ALGORITHM:
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>
AngularJs Form Input Fields Validations Example
</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"
></script>
<script>
var app = angular.module('formApp', []);
app.controller('formCtrl', function ($scope) {
$scope.sendForm = function () {
$scope.msg='Form Submited Successfully';
};
OUTPUT:
*****
127
EXPERIMENT 4
AIM:
Demonstrate features of Angular.js forms with a program using CSS
classes.
OBJECTIVE:
Create Simple Angular Forms that demonstrate input validation using CSS
classes.
THEORY:
AngularJS adds CSS classes to forms and input fields depending on their
states.
The following classes are added to, or removed from, input fields:
ALGORITHM:
128
Step 2: Specify the ng-model in input fields of forms.
<input type="text" name="firstname" ng-model="person.fname" required
/>
Step 3: Add the CSS property to form using form.ng-valid and form.ng-
invalid.
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>
AngularJs Form Validation with Classes Example
</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js
"></script>
<style>
form.ng-invalid {
background-color:red;
}
form.ng-valid {
background-color:green;
}
</style>
</head>
<body>
<div ng-app="">
<h2>AngularJS Form Validation with Class Example</h2>
<form name="personForm">
<br />
First Name:<input type="text" name="firstname" ng-
model="person.fname" required /><br /><br />
Last Name:<input type="text" name="lastname" ng-
model="person.lname" required />
<br /><br />
</form>
</div>
</body>
</html>
129
OUTPUT:
QUESTION
*****
130
MODULE IX
EXPERIMENT 1
AIM:
Write a Angular.js program to implement the concept of Single page
application.
OBJECTIVE:
Create a single page application that loads a single HTML page and only a
part of the page instead of the entire page gets updated with every click of
the mouse.
THEORY:
Single page applications or (SPAs) are web applications that load a single
HTML page and dynamically update the page based on the user
interaction with the web application.
The page does not reload or transfer control to another page during the
process. This ensures high performance and loading pages faster. Most
modern applications use the concept of SPA. In the SPA, the whole data is
sent to the client from the server at the beginning. As the client clicks
certain parts on the webpage, only the required part of the information is
fetched from the server and the page is rewritten dynamically. This results
in a lesser load on the server and is cost-efficient. SPAs use AJAX and
HTML5 to create fluid and responsive Web applications and most of the
work happens on the client-side.
Advantages:
1. Team collaboration:
Single-page applications are excellent when more than one developer is
working on the same project. It allows backend developers to focus on the
API, while the frontend developers can focus on creating the user interface
based on the backend API.
131
2. Caching:
The application sends a single request to the server and stores all the
received information in the cache. This proves beneficial when the client
has poor network connectivity.
Disadvantages:
1. SEO optimization:
SPAs provide poor SEO optimization. This is because single-page
applications operate on JavaScript and load data at once server. The URL
does not change and different pages do not have a unique URL. Hence it is
hard for the search engines to index the SPA website as opposed to
traditional server-rendered pages.
2. Browser history:
A SPA does not save the users‟ transition of states within the website. A
browser saves the previous pages only, not the state transition. Thus when
users click the back button, they are not redirected to the previous state of
the website. To solve this problem, developers can equip their SPA
frameworks with the HTML5 History API.
3. Security issues:
Single-page apps are less immune to cross-site scripting (XSS) and since
no new pages are loaded, hackers can easily gain access to the website and
inject new scripts on the client-side.
4. Memory Consumption:
Since the SPA can run for a long time, sometimes hours at a time, one
needs to make sure the application does not consume more memory than it
needs. Else, users with low memory devices may face serious performance
issues.
5.Disabled Javascript:
Developers need to chalk out ideas for users to access the information on
the website for browsers that have Javascript disabled.
132
ALGORITHM:
133
Step 7: Build controllers for every route specified in $routeProvider
Step 9: Add links to the HTML that will help in navigating to the
configured pages
Step 10: Include the HTML of routing pages to index.html file using
script tag
PROGRAM:
<!doctype html>
<html ng-app="myApp">
<head>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js
"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>
</head>
<body>
<script type="text/ng-template" id="pages/first.html">
<h1>First</h1>
<h3>{{message}}</h3>
</script>
<script type="text/ng-template" id="pages/second.html">
<h1>Second</h1>
<h3>{{message}}</h3>
</script>
<script type="text/ng-template" id="pages/third.html">
<h1>Third</h1>
<h3>{{message}}</h3>
</script>
<a href="#/">First</a>
<a href="#/second">Second</a>
<a href="#/third">Third</a>
<div ng-view></div>
<script src="app.js"></script>
</body>
</html>
134
OUTPUT:
*****
135
EXPERIMENT 2
AIM:
Demonstrate route provider features of Angular.js forms with a program
OBJECTIVE:
Create a single page application that shows a routing provider demo with
layout and template.
THEORY:
AngularJS Routing
AngularJS supports SPA using the routing module ngRoute. This routing
module acts based on the url. When a user requests a specific url, the
routing engine captures that url and renders the view based on the defined
routing rules.
Routing Example:
Let's build an application, which will display a login page when a user
requests a base url - http://localhost/. Once the user logs in successfully,
we will redirect it to the student page http://localhost/student/{username}
where the username would be logged in user's name.
In our example, we will have one layout page - index.html, and two
HTML templates - login.html and student.html.
1. Index.html - layout view
2. login.html - template
3. student.html - template
ALGORITHM:
Step 1:
To include angular.js, angular-route.js, and bootstrap.css in the index.html.
The angular-route.js includes necessary functions for routing.
Step 2:
Apply ng-app directive.
Step 3:
Apply ng-view directive to <div> or other elements where you want to
inject another child view. AngularJS routing module uses ng-view
136
directive to inject another child view where it is defined. Therefore,
Angular will inject login.html or student.html inside this div element.
Step 4:
Now, create an application module and specify 'ngRoute' as a dependency
module.
Step 5:
Now, we need to configure the routing rules that need to be compiled
before any other module of an application. So, use the config() method to
configure the routing rules using the $routingProvider object.
Step 6:
Use $routeProvider.when(path, route) method to configure routing rules,
where the first parameter is request URL and the second parameter is an
object which contains controller, template, or other properties. In the
above example, we specified that if a user requests for "/" URL, meaning
the base url then inject login.html and loginController. In the same way, if
a user requests for "/student/:username" url then inject student.html and
studentController. The :username would be the url parameter.
Step 7: Use otherwise() method to redirect to base url if user requests for
the URL other than configured rules.
PROGRAM:
1. Index.html - layout view
2. login.html - template
3. student.html - template
Index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/angular.js"></script>
137
<script src="Scripts/angular-route.js"></script>
<link href="Content/bootstrap.css" rel="stylesheet"
/>
</head>
<body ng-app="ngRoutingDemo">
<h1>Angular Routing Demo</h1>
<div ng-view>
</div>
<script>
var app = angular.module('ngRoutingDemo',
['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/login.html',
controller: 'loginController'
}).when('/student/:username', {
templateUrl: '/student.html',
controller: 'studentController'
}).otherwise({
redirectTo: "/"
});
$location.path('/student/' + username)
};
});
});
</script>
</body>
</html>
------------------------------------------------------------------------
-------------------------------
138
Create login.html as shown below, which contains
username and password input box with validation. Please
note that we are using bootstrap.css.
login.html
</div>
<div class="form-group" >
<div class="col-sm-3">
</div>
<div class="col-sm-6">
<input type="password" id="password"
name="password" placeholder="Password" class="form-
control" ng-model="password" required />
<span ng-show="loginForm.password.$touched &&
loginForm.password.$error.required">Please enter
Password.</span>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div class="form-group">
<label for="lastName" class="col-sm-3 control-
label">Last Name</label>
<div class="col-sm-6">
<input type="text" id="lastName" class="form-
control" ng-model="student.lastName" />
</div>
<div class="col-sm-3"></div>
</div>
<div class="form-group">
<label for="dob" class="col-sm-3 control-
label">DoB</label>
<div class="col-sm-2">
<input type="date" id="dob" class="form-control"
ng-model="student.DoB" />
</div>
<div class="col-sm-7"></div>
</div>
<div class="form-group">
<label for="gender" class="col-sm-3 control-
label">Gender</label>
<div class="col-sm-2">
<select id="gender" class="form-control" ng-
model="student.gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<div class="col-sm-7"></div>
</div>
140
<div class="form-group">
<div class="col-sm-3"></div>
<div class="col-sm-2">
<span><b>Training Location</b></span>
<div class="radio">
<label><input value="online" type="radio"
name="training" ng-model="student.trainingType"
/>Online</label>
</div>
<div class="radio">
<label><input value="onsite" type="radio"
name="training" ng-model="student.trainingType"
/>OnSite</label>
</div>
</div>
<div class="col-sm-7">
<span><b>Main Subjects</b></span>
<div class="checkbox">
<label><input type="checkbox" ng-
model="student.maths" />Maths</label>
</div>
<div class="checkbox">
<label><input type="checkbox" ng-
model="student.physics" />Physics</label>
</div>
<div class="checkbox">
<label><input type="checkbox" ng-
model="student.chemistry" />Chemistry</label>
</div>
</div>
</div>
OUTPUT:
141
*****
142
EXPERIMENT 3
AIM:
Demonstrate feature of Animations using angular.js
OBJECTIVE:
Create a simple animation by using ng-hide directive.
THEORY:
The framework offers a very interesting mechanism to hook specific style
classes to each step of the life cycle of some of the most used directives
such as ngRepeat, ngShow, ngHide, ngInclude, ngView, ngIf, ngClass,
and ngSwitch. The first thing that we need to do in order to start is import
the angular animation.js file to our application. After that, we just need to
declare it in our module as follows:
app.js
var parking = angular.module("parking", ["ngAnimate"]);
Based on this, it's time to check out the supported directives and their
events:
143
Animating ngHide:
app.css
.ng-hide-add
{
-webkit-transition: all 5s linear;
-moz-transition: all 5s linear;
-ms-transition: all 5s linear;
-o-transition: all 5s linear;
transition: all 5s linear;
opacity: 1;
}
.ng-hide-add-active
{
display: block !important;
opacity: 0;
}
In this case, the transition must flow in the opposite way. For the fade-out
effect, we need to shift from the opacity 1 to 0. This display property is set
to block, because the regular behavior of the ngHide directive is to change
the display property to none. With that property in place, the element will
vanish instantly, and our fade-out effect will not work as expected.
ALGORITHM:
Step 1:
Declare the CSS code for DIV
div {
transition: all linear 0.5s;
background-color: lightblue;
height: 100px;
width: 100%;
position: relative;
top: 0;
left: 0;
}
Step 2:
Declare the CSS code for ng-hide directive
144
.ng-hide {
height: 0;
width: 0;
background-color: transparent;
top:-200px;
left: 200px;
}
Step 3:
Add the source to script that shows angular animation
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.j
s"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-
animate.js">
</script>
Step 4:
Add <body ng-app="ngAnimate">
Step 5:
Add the input control checkbox
<input type="checkbox" ng-model="myCheck"></h1>
Step 6:
Add the following
<div ng-hide="myCheck"></div>
PROGRAM:
<!DOCTYPE html>
<html>
<style>
div {
transition: all linear 0.5s;
background-color: lightblue;
height: 100px;
width: 100%;
position: relative;
top: 0;
left: 0;
}
.ng-hide {
height: 0;
width: 0;
145
background-color: transparent;
top:-200px;
left: 200px;
}
</style>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.m
in.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-
animate.js"></script>
<body ng-app="ngAnimate">
<h1>Hide the DIV: <input type="checkbox" ng-
model="myCheck"></h1>
<div ng-hide="myCheck"></div>
</body>
</html>
OUTPUT:
QUESTIONS
1. What are the advantages & disadvantages of SPA?
2. What is ngRoute? Explain with the help of an example.
3. Explain the different directives and their events used during animation?
*****
146