web-technology-munotes

Page 1

1
MODULE I

EXPERIMENT 1

AIM:
What is node js
Objective:
Explain node JS
Theory :

It is a free, open -source, cross -platform runtime environment that runs
on JavaScript. Meant mainly for the server side, or client side, of a
mobile application, it is a full -stack development environment that
divides up tasks into fully separate “nodes.”

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 ecosyst em 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 pat hs, tasks can
run simultaneously and seamlessly together, without bogging down the
server or using up too much capacity.

A Node refers to this as a “microservice” pattern, with each a self -
contained pathway to fulfill a particular service. It‟s an innovat ive way
of breaking an app down into its smallest bits. But it‟s a very efficient
way to handle mobile applications, which need speed, accessibility, and
accuracy above all.


This chart represents how a typical application might be organized. See
how eve rything is organized as a spoke off the core app programming?
Functions like customer email, or shopping carts, or portal requests are
given their own “node.” And those self -contained areas can run without
interfering with each other, or the core applicati on itself.



munotes.in

Page 2

2
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 c ore 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, scalabil ity gives your
application room to grow, and that‟s one of the key benefits of using
Node.js.

Speed and Performance : Its non -blocking, input -output operations
make the environment one of the speediest options available. Code runs
quickly, and that enhanc es the entire run -time environment. This is
largely due to its sectioned -off system. But it also has to do with the fact
that it runs on Google‟s V8 JavaScript engine. Its apps are more likely
to be programmed end -to-end in Javascript, and that plug and pl ay
interoperability contributes to speed and performance.

Flexibility : In a discussion of Node.js pros and cons programming
flexibility is perhaps the biggest benefit of all. When you make a change
in Node.js, only that node is affected. Where other run time
environments or frameworks may require you to make changes all the
way back to the core programming, it doesn‟t require anything more
than a change to the node. And that is great not just for your initial
build, but for your ongoing maintenance as wel l. And best of all, when
you combine JSON with Node.js, you can easily exchange information
between client servers and the webserver. Programmers can also use
APIs to build TCP, HTTP, DNS, etc. into the server.

Efficient caching : In a debate over the pros and cons of Node.js,
caching always comes up as a key Node.js benefit. It has a powerful
ability to cache data. When requests are made to the app, they are
cached in -app memory. Consequently, when requests cycle through
execution and re -execution, the nod es are still able to run efficiently and
not be bogged down by historical data.

Fast -to-market -development : Node‟s basis in JavaScript brings many
benefits to the table, especially the ease at which developers can add
more features and predesigned tools and templates.

Efficient Queueing of Requests : A critical benefit of using Node.js is
its ability to handle multiple requests at once. How does it do this? By
offering users an optional nob -block I/O system. The system works by
giving priority to those requests that take the lowest response time. This
prioritization helps speed up the overall running of your app, especially
when comparing it to other languages like Python or Ruby on Rails.

munotes.in

Page 3

3
Node.js Process Model :
The Node.js process model differs from t raditional 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 p ool. 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 requ est, it hands it off so that the
thread can process other requests in the meantime. In this way Node.js is
inherently asynchronous.

Traditional Web Server Model :
The traditional web server model consists of a pool of threads which
may process requests. Ea ch time a new request comes in, it is assigned
to a different thread in the pool. In the event a request is received and a
thread is not available, the request will have to wait until a previous
request finishes, a response is returned, and the thread is r eturned to the
thread pool. In this way, the web server model is synchronous, or
blocking.

How to Install Node.js and NPM on Windows :
In a web browser, navigate to https://nodejs.org/en/download/ . Click
the Windows Installer button to download the latest default version. At
the time this article was written, version 10.16.0 -x64 was the latest
version. The Node.js installer includes the NPM package manager.


munotes.in

Page 4

4
Step 2: Install Node.js and NPM from B rowser
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 install ation 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, ac cept the
defaults by clicking Next .
7. Finally, click the Install button to run the installer. When it finishes,
click Finish .

Step 3: Verify Installation :
Open a command prompt (or PowerShell), and enter the following:
node -v

The system should displa y the Node.js version installed on your system.
You can do the same for NPM:
npm -v

Node.js - REPL Terminal :
REPL stands for Read Eval Print Loop and it represents a computer
environment like a Windows console or Unix/Linux shell where a
command is enter ed and the system responds with an output in an
interactive mode. Node.js or Node comes bundled with a REPL
environment. It performs the following tasks −
 Read − Reads user's input, parses the input into JavaScript data -
structure, and stores in memory .
 Eval − Takes and evaluates the data structure.
 Print − Prints the result.
 Loop − Loops the above command until the user presses ctrl- c twice.

The REPL feature of Node is very useful in experimenting with Node.js
codes and to debug JavaScript codes.

Starti ng REPL :
REPL can be started by simply running node on shell/console without any
arguments as follows.
$ node munotes.in

Page 5

5
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 informa tional, 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 obje ct. 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...). ***** munotes.in

Page 6

6
MODULE II

EXPERIMENT 1

AIM:

To demonstrate the use of Standard callback pattern

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 :

Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!!
Create a js file named main.js with the following code :

var fs = require("fs"); var data = fs.readFileSync('input.txt'); console.log(data.toString()); console.log("Program Ended");
Now run the main.js to see the result −

$ node main.js
Verify the Output.
munotes.in

Page 7

7
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:
 Emitt ing 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 th at 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.

Create an event emitter instance and register a couple of callbacks
const myEmitter = new EventEmitter();

function c1() {
console.log('an event occurred!');
}

function c2() {
console.log('yet another event occurred!');
}

myEmitter.on('eventOne', c1); // Register for eventOne
myEmitter.on('eventOne', c2); // Register for eventOne

When the event ‘eventOne’ is emitted, both the above callbacks
should be invoked.
munotes.in

Page 8

8
myEmitter.emit('eventOne');
The output in the console will be as follows:

an event occurred! yet another event occurred!
Events:
Sr.No. Events & Description 1 newListener  event − String: the event name  listener − Function: the event handler function This event is emitted any time a listener is added. When this event is triggered, the listener may not yet have been added to the array of listeners for the event. 2 removeLis tener
 event − String The event name
 listener − Function The event handler function
This event is emitted any time someone removes a listener.
When this event is triggered, the listener may not yet have been
removed from the array of listeners for the event .
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])

Removes all listeners, or those of the specified 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. munotes.in

Page 9

9
Node introduces another pers pective 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 t o occur either before, or after, the
processing of queued I/O events are pr ocess.nextTick and setImmediate .
process.nextTick
The primary use of nextTick in a function is to postpone the broadcast
of result events to listeners on the current execution stack until the caller
has had an opportunity to register event listeners, giving the currently
executing program a chance to bind callbacks to EventEmitter.emit
events.

Explanation

// get the reference of EventEmitter class of events module var events = req uire('events'); //create an object of EventEmitter class by using above reference var em = new events.EventEmitter(); //Subscribe for FirstEvent em.on('FirstEvent', function (data) { console.log('First subscriber: ' + data); }); // Raising FirstEven t 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() met hod 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:

To demonstrate the use stop execution of a function
Objective :

Using process.exit() method stop function execution
munotes.in

Page 10

10
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.

ASIDE: The standard callback is a function where the first argument is an
error, or null if there was no error, so if you were using a callback the
above would look like:

Explanation :
var thisIsTrue = false;

exports.test = function(request, response, cb){

if (thisIsTrue) {
response.send('All is good!');
cb(null, response)
} else {
response.send('ERROR! ERROR!');
return cb("THIS ISN'T TRUE!");
}

console.log('I do not want this to happen. If there is an error .');

}

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

Another way would be to use throw

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){}):

throw new Error('Something went wrong')

b) Stop script execution (works with Node.js):
process.exit( )

AIM:
To demonstrate the use Schedule and repetitive execution

Objective :
Using setTimeout & setInterval Schedule and repetitive execution
munotes.in

Page 11

11
Theory :
We may decide to execute a function not right now, but at a certain time
later. That‟s called “scheduling a call”.

There are two methods for it:
 setTimeout allows us to run a function once after the interval of time.
 setInterval allows us to run a function repeatedly, starting after the
interval of time, then repeating continuously at that interval.

These m ethods are not a part of JavaScript specification. But most
environments have the internal scheduler and provide these methods. In
particular, they are supported in all browsers and Node.js.

Explanation :
let timerId = setTimeout( func|code , [delay ], [arg1], [arg2], ...)

Parameters:

func|code

Function or a string of code to execute. Usually, that‟s a function. For
historical reasons, a string of code can be passed, but that‟s not
recommended.

Delay

The delay before run, in milliseconds (1000 ms = 1 seco nd), by default 0.

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:

Canceling with clearTimeout

A call to setTimeout returns a “timer identifier” timerId that we can use to
cancel the execution.

The syntax to cancel:
let timerId = setTimeout(...);
clearTimeout( timerId );
In the code below, we schedule the function and then cancel it (changed
our mind). As a result, nothing happens: munotes.in

Page 12

12

let timerId = setTimeout(() => alert("never happens"), 1000);
alert( timerId ); // timer identifier

clearTimeout( timerId );
alert( timerId); // same identifier (doesn't become null after canceling)

As we can see from alert output, in a browser the timer identifier is a
number. In other environments, this can be something else. For instance,
Node.js returns a timer object with additional methods.

Again, there is no universal specification for these methods, so that‟s fine.

For browsers, timers are described in the timers section of HTML5
standard.

setInterval

The setInterval method has the same syntax as setTimeout :

let timerId = setInterval( func|code , [delay ], [arg1], [arg2], ...)
All arguments have the same meaning. But unlike setTime out it runs the
function not only once, but regularly after the given interval of time.

To stop further calls, we should call clearInterval(timerId) .

The following example will show the message every 2 seconds. After 5
seconds, the output is stopped:

// repeat with the interval of 2 seconds
let timerId = setInterval(() => alert('tick'), 2000);

// after 5 seconds stop
setTimeout(() => { clearInterval( timerId ); alert('stop'); }, 5000);

Nested setTimeout

There are two ways of running something regularly.

One is setInterval . The other one is a nested setTimeout , like this:

/** instead of:
let timerId = setInterval(() => alert('tick'), 2000);
*/

let timerId = setTimeout (function tick() {
alert('tick');
timerId = setTimeout( tick, 2000); // (*)
}, 2000); munotes.in

Page 13

13

The setTimeout above schedules the next call right at the end of the
current one (*).

The nested setTimeout is a more flexible method than setInterval . This
way the next call may be scheduled differently, depending on the results 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.

Whenever we run a Node program, a thread is automatically created. This
thread is the only place where our entire codeba se is going to be executed.
Inside of it, something called the event loop is generated. The role of this
loop is to schedule which operations our only thread should be performing
at any given point in time.

Please note that the event loop doesn‟t get gene rated 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);
}

const timeoutScheduled = Date.now();


For example, say you schedule a timeout to execute after a 100 ms
threshold, then your script starts asynchronously reading a file which takes
95 ms:
munotes.in

Page 14

14
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 ti mer'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; console.log(`${delay}ms have passed si nce I was scheduled`); }, 100); // do someAsyncOperation which takes 95 ms to complete someAsyncOperation(() => { const startCallback = Date.now(); // do something that will take 10ms... while (Date.now() - startCallback < 10) { // do nothing } });

*****

munotes.in

Page 15

15
MODULE III

EXPERIMENT 1

AIM:

To demonstrate the Fs module file paths

Objective

Explantion of Fs module file paths

Theory :

n Node.js, file handling is handled by fs module. You can read more about
it here. We can check the path for f ile or directory in Node.js in both
Synchronous and Asynchronous way.

Note: Asynchronous version is usually preferable if you care about
application performance.

Synchronous method: Synchronous operations are great for performing
one-time file/directory operations before returning a module. To check the
path in synchronous mode in fs module, we can use statSync() method.
The fs.statSync(path) method returns the instance of fs.Stats which is
assigned to variable stats. A fs.Stats object provides informatio n about a
file. The stats.isFile() method returns true if the file path is File, otherwise
returns false. The stats.isDirectory() method returns true if file path is
Directory, otherwise returns false.

Explanation :

Example :

// Require the given module var fs = require('fs'); // Use statSync() method to store the returned // instance into variable named stats var stats = fs.statSync("/Users/divyarani/Documents/geekforgeeks/geeks.js"); // Use isFile() method to log the result to screen console.log('is fil e ? ' + stats.isFile()); var stats = fs.statSync("/Users/divyarani/Documents/geekforgeeks/geek"); // Use isDirectory() method to log the result to screen console.log('is directory ? ' + stats.isDirectory()); Output munotes.in

Page 16

16
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 numbe r 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());
});
Create a temp.txt within the same director y and write in it anything
you’d like. Run your script using node app.js and you should see in
the console the contents of your file.

Understanding the Code
We‟ll step through this with comments.
var fs = require("fs");
This line does the job of impo rting the fs package and allowing us to
utilize it within our own code.
fs.readFile("temp.txt", function(err, buf) { console.log(buf); });
AIM:
Demonstrate how to read data in SQL using node js

Objective :
Explanation how to read data in SQL using node js
munotes.in

Page 17

17
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.

Executing a simple query :

The following select.js program selects all data from the todos table of the
todoapp database:

let mysql = require('mysql'); let config = require('./config.js'); let connection = mysql.createCon nection(config); let sql = `SELECT * FROM todos`; connection.query(sql, (error, results, fields) => { if (error) { return console.error(error.message); } console.log(results); }); connection.end();
Let‟s run the select.js program.
>node select .js

[ RowDataPacket { id: 1, title: 'Learn how to insert a new row', completed: 1 }, RowDataPacket { id: 2, title: 'Insert a new row with placeholders', completed:0 }, RowDataPacket { id: 3, title: 'Insert multiple rows at a time', completed: 0 }, RowDataPacket { id: 4, title: 'It should work perfectly', completed: 1 } ] munotes.in

Page 18

18
It returned 4 rows as expected.

Passing data to the query

The following select2.js program selects only completed todo:

let mysql = require('mysql'); let config = require('./conf ig.js'); let connection = mysql.createConnection(config); let sql = `SELECT * FROM todos WHERE completed=?`; connection.query(sql, [true], (error, results, fields) => { if (error) { return console.error(error.message); } console.log(results); }); connection.end();
In this example, we used the question mark (?) as the placeholder value of
the completed field.

When we called the query() method, we passed an array as the second
argument. The placeholders will be substituted by the values of the array
in sequence.

>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 } ]
Code language: JavaScript (javascript)

The select2.js progr am returns two rows with the completed column is 1,
which means true in Node.js


*****





munotes.in

Page 19

19
MODULE IV

EXPERIMENT 1

AIM :

Write a simple program for multiplication

Objective :

The objective is to create a simple multiplier application which will
mult iply two numbers and display the result. User will enter two
numbers in two separate textboxes and the result will be displayed
immediately. This programme is to make the users understand the
concepts of Templates, Directives and Expressions

THEORY :

Befo re understanding AngularJS, user should have a basic understanding
of
 HTML
 CSS
 JavaScript

SETUP ANGULARJS DEVELOPMENT ENVIRONMENT :

The following tools arre needed to setup a development environment for
AngularJS:
 AngularJS Library
 Editor/IDE
 Browser
 Web server

AngularJS Library :

To download AngularJS library, go to angularjs.org -> click download
button, which will open the following popup. munotes.in

Page 20

20

Downloa d AngularJS Library

Select the required version from the popup and click on download
button in the popup.

CDN: AngularJS library can be included from CDN url -
https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js

Editor :

AngularJS is ev entually HTML and JavaScript code. So install any good
editor/IDE as per your choice.

The following editors are recommended:
 Sublime Text
 Aptana St udio 3
 Ultra Edit
 Eclipse
 Visual Studio

Online Editor :

The following online editors can be u sed for learning purpose.
 plnkr.co
 jsbin.com



munotes.in

Page 21

21
Web server :
Use any web server such as IIS, apache etc., locally for development
purpose

Browser :
Install any browse r 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 i s 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

setup Angular projec t in Visual Studio 2013 for web:
Create AngularJS application in any version of Visual Studio. Here,
Visual Studio 2013 for web is used. First, create new project by clicking
on New Project link on start page. This will open New Project dialog
box, as shown below.


AngularJS in Visual Studio :

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.
munotes.in

Page 22

22

AngularJS in Visual Studio

This will create an empty website project in Visual Studio.


AngularJS in Visual Studio

Now, install AngularJS library from NuGet package manager. Right
click on the project in Solution Explorer an d select Manage NuGet
Packages.
munotes.in

Page 23

23

AngularJS in Visual Studio

Search for "angular" in the Manage NuGet Packages dialog box and
install AngularJS Core.
munotes.in

Page 24

24

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.


AngularJS in Visual Studio

Now, start writing AngularJS web application.

ALGORITHM :

STEP 1:
Create a HTML document with and elements, as shown
below.



munotes.in

Page 25

25








STEP 2:
Include angular.js file in the head section




First AngularJS Application







STEP 3 :

Create a simple multiplier application which will multiply two numbers
and display the result. Enter two numbers in two separate textboxes and
the result will be displayed immediately, as shown below.



PROGRAM




First AngularJS Application



First AngularJS Application



Enter Numbers to Multiply:
x type="text" ng-model="Num2" />
= {{Num1 * Num2}}
munotes.in

Page 26

26


Try it



The above example looks like HTML c ode with some strange attributes
and braces such as ng -app, ng -model, and {{ }}. These built -in
attributes in AngularJS are called directives.

The following figure illustrates the AngularJS building blocks in the
above example


First AngularJS Applicat ion
munotes.in

Page 27

27
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.

ng-app: The ng -app directive is a starting point. If AngularJS
framework finds ng -app directive anywhere in t he HTML document
then it bootstraps (initializes) itself and compiles the HTML template.

ng-model : The ng -model directive binds HTML element to a property
on the $scope object.
In the above example, ng -model directive is added to both the textboxes
with different names Num1 and Num2. AngularJS framework will
create two properties called Num1 and Num2 in the scope and will
assign a value that are typed into textboxes.

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
1. What are the major components of angularjs?
2. Wha t is an expression?
3. What are directives?
4. What is {{ num1 * num2}}
a) Expression b) template c) directive d) none
5. Mention few editors used in angularjs?
6. What is angular seed?


*****

munotes.in

Page 28

28
EXPERIMENT 2

AIM :

Write a program to display your name with welcome note :HELLO

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 import ant 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.

How AngularJS Integrates with HTML :
 The ng -app directive indicates the start of AngularJS application.
 The ng -model directive creates a model variable named name, which
can be used with the HTML page and within the div having ng -app
directive.
 The ng -bind then uses the name model to be displayed in the HTML
tag whenever user enters input in the text box.
 Closing

tag indicates the end of AngularJS application.

Very basic HTML page is extended with AngularJS directives by loading
it from a CD N. AngularJS starts automatically when the web page has
loaded.
 The ng-app directive tells AngularJS that the
element is the
owner of the application.
 The ng-init directive initializes AngularJS application variable message .
 AngularJS outputs data st ored in the variable message where
the expression is written. In this case

.

A CDN (Content Delivery Network) is a collection of global servers that
caches and delivers content such as images, videos and Javascript files. By
pulling AngularJS from a remote server we avoid having to store it loacally munotes.in

Page 29

29
on our computers. This techniqu e is good to use during the development
process but advised against for production code.

Interacting with a user :
See if AngularJS application is able to interact with some user generated
data. How about letting the user add a name and have the “Hello” -message
customized with that name?

ALGORITHM :

Creating AngularJS Application

Step 1 : Load framework
Being a pure JavaScript framework, it can be added using

Step 2: Define AngularJS application using ng -app directive


...


Step 3: Define a model name using ng -model directive

Enter your Name:



Step 4: Bind the value of above model defined using ng -bind directive

Hello !



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 w eb browser. Enter your name and
see the result.

PROGRAM

testAngularJS.htm
AngularJS First Application

Sample Application

munotes.in

Page 30

30

Enter your Nam e:

Hello !


index.html

Hello {{yourName}}!


OUTPUT


Name:sudha

Hello sudha!

munotes.in

Page 31

31
QUESTIONS
1. How angularjs integrates with HTML?
2. What are the parts of a AngularJS appli cation?
3. Mention the tag used for loading the framework?
4. Define CDN?





*****

munotes.in

Page 32

32
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 remo ve items:

Shopping List
 Milk×
 Bread×  Cheese×
Add

THEORY :

A shopping cart is similar to original grocery shopping cart; it means that
on a website that sells products or services online, the shopping cart is a
common m etaphor that acts as online store‟s catalog and ordering process.
It is a graphical representation of a supermarket on a vendor‟s website that
keeps a list of items a customer has picked up from the online store.

Shopping cart is an infrastructure that al lows customers to review what
they have selected, make necessary modifications such as adding or
deleting products and purchase the merchandise. Customer checks off the
products that are being ordered and when finished ordering, that proceeds
to a page whe re the total order is confirmed and placed. Also, customers
will enter their shipping tax information at the checkout. Shopping cart
allows a website to build a catalog of products and integrate it into the
website pages.

Shopping cart is important infras tructure to have smooth ecommerce
transition. The shopping cart describes specialized content management
system that includes,
 website wizards
 provides portal for catalog, order and customer management
 renders product data, product categories
 merchant tool s
 shopping features
 payment options
 shipping and tax information
 passes transactional data to payment gateway
 statistics and security munotes.in

Page 33

33
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:





  • {{x}}




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:

munotes.in

Page 34

34



  • {{x}}






Step 3.

Removing Items:
We also want to be able to remove items from the shopping list.

In the controller, make a function named removeItem, which takes the
index of the item you want to remove, as a parameter. In the HTML, make
a element for each item, and give them an ng-click directive which
calls the removeItem function with the current $index.

Example
Now we can remove items from our shopping list:





  • {{x}} ×






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. munotes.in

Page 35

35
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:





  • {{x}}×




{{errortext}}




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: munotes.in

Page 36

36
>

PROGRAM:





  • {{x}}×




{{errortext}}




OUTPUT : munotes.in

Page 37

37


QUESTIONS
1. What do you me an by shopping cart?
2. How do you apply styles to your application?
3. What is error handling?


*****

munotes.in

Page 38

38
EXPERIMENT 4

AIM :

Show the use of md -dialog directive and mdDialog service and also the
use of angular dialog boxes.

OBJECTIVE :

The md-dialog , an Angula r Directive, is a container element and is used
to display a dialog box. Its element, the md-dialog -content , contains the
content of the dialog and the md-dialog -actions is responsible for the
dialog actions. The mdDialog , an Angular Service, opens a dialo g over
the application to inform the users about the information and help them
make decisions.

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 element. Inside,
use an element for the dialog's content, and use
an 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 \

munotes.in

Page 39

39

Standard Alert

Alert

Confirm Dialog Box

Confirm

Custom Dialog Box

Custom

{{status}}
munotes.in

Page 41

41


OUTPUT



QUESTIONS
1. Wha t is md-dialog and its elements?
2. What are the restrictions of md-dialog directive?
3. What are the two basic approaches for setup of md-dialog?



*****
















munotes.in

Page 42

42
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 w eb 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 cl ick 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 fro m 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 applicati ons 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', []);
munotes.in

Page 43

43

Step 2:
Define a Simple Co ntroller
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.






{{message}}





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 ad d different views to our
SPA
Include angular -route script after the main angular script.


Use the ngRoute directive to enable routing.
var app = angular.module('myApp', ['ngRoute']);

munotes.in

Page 44

44
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.












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.

Exception handling has to be accommodated when a user tries to navigate
to a route that doesn‟t exist. For simplicity, we can write an “other wise”
function to redirect the user to the “/” route.

var app = angular.module('myApp', ['ngRoute']);

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: '/'});
}); munotes.in

Page 45

45


Step 7:
Build controllers for every route specified in $ro uteProvider
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

First


{{message}}


second.html

Second


{{message}}


third.html

Third


{{message}}



Step 9:
Add links to the HTML that will help in navigating to the configured
pages







First
Second
Third



munotes.in

Page 46

46
Step 10:
Include the HTM L of routing pages to index.html file using script tag









First
Second
Third





(Whe n 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 :





munotes.in

Page 47

47




First
Second
Third






Once the HTML is run on localhost, the following page is displayed.



Observe that the hyperlinks First, Second, Third on the p age are routers
and when you click on them, navigation to the corresponding web pages
occur, without refreshing.

munotes.in

Page 48

48



QUESTIONS
1. List few applications of SPA?
2. Mention the steps to define a Simple Controller?
3. How to Add links to the HTML that will help in navigating to the
configured pages?






*****









munotes.in

Page 49

49
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 impo rtant features for a web
application that is used to authenticate or restrict unauthorized access to
member only areas and features in a web appli cation. 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.

Following are the salient features of this Registration example .

 User Registration form has following basic fields.
1. Name
2. Email
3. Password
4. Phone

 The form will have a hyperlink (top-right corner) to see a list of
users which will list all the registered users.
 Below the form, a list of registered users with Edit/Delete features is
enabled.
 When the user goes to see the list of users, he can simply click on
the Back button to come back to the registration form.
 Initially, when the application is loaded, the form ge ts displayed. To
add a new user, enter all the details as follows and click on the Submit
button.
 To update a user, use the Edit action which will display the current
details in form fields. Change the values and click on Submit button to
save the latest d etails. The updated details are displayed in the
registered user‟s table.
 To remove a user from the application, use delete action which will
erase all the details pertaining to that user and the user row will be
deleted from the table. munotes.in

Page 50

50
 To see all the use rs, click on the hyperlink „List of Users‟ on the top -
right corner of the page. It will take you to the next page where the user
details are displayed.

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




User Registraion Form - W3Adda


href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.
css">
munotes.in

Page 51

51





User Registraion Form - W3Adda





{{title}}




"Enter Name " ng-model = "newuser.name" >



"Enter Email " ng-model = "newuser.email" >



placeholder = "Enter Password " ng-model = "newuser.password" >



"Enter Phone " ng-model = "newuser.phone" >




class ="btn btn-primary" value = "Submit" >

Registered Users








munotes.in

Page 52

52











Name Email Phone Action
{{ user.name }} {{ user.email }} {{ user.phone }}
edit   ;
delete

No Users Found







On top of the the form User List link is avail able 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' : 'johndoe@gmail.com' ,
'password' : 'johndoe' ,
'phone' : '123-45-678-901'}];
munotes.in

Page 53

53
// 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 ; munotes.in

Page 54

54
};
});

Step 5 :
Create Regist ration 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" ;
}
};
}); munotes.in

Page 55

55
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" , functi on(){
var uid = 1;
var users = [{
'id' : 0,
'name' : 'John Doe',
'email' : 'johndoe@gmail.com' ,
'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];
}
} munotes.in

Page 56

56
};
// 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)); munotes.in

Page 57

57
};
$scope .searchUser = function (){
if($scope .title == "User List" ){
$scope .ifSearchUser =true;
$scope .title = "Back" ;
}
else
{
$scope .ifSearchUser = false ;
$scope .title = "User List" ;
}
};
});

OUTPUT



QUESTIONS
1. What is the use of registration controller?
2. What is the difference between registration service and controller?
3. Write the steps to create angularjs application?

*****



munotes.in

Page 58

58
EXPERIMENT 3

AIM :
To implem ent 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 an gularjs. 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 :

A form is a collection of controls like input textbox, number text, email
text and checkbox etc. In angularjs we can validate form and input field
controls (text, select, textarea) in client side and notify users for invalid
data while submitting forms with better user experience when compared to
server side validati ons. In angularjs form input field controls arE validated
by using HTML5 property required or angularjs property ng-required .

What is required or ng -required ? How to use it?

Generally by using html5 required and angularjs ng-required attributes
require d field can be validated in form. Both required and ng-
required will do the same validation so either of them can be used based
on the interest. Following is the way of defining required and ng-
required properties in angularjs applications.

1.

2. are essentially the same thing.

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 Inpu t Fields
Following is the syntax of implementing validations to input fields on
form in angularjs applications.


model="person.fname" required />
show="personForm.firstname.$error.re quired">Required!

munotes.in

Page 59

59
Observe the above syntax where it is defined required to input control
and showing span element based on validation of input control.

Angu larJS Form Validations :

Following is the simple angularjs example to validate inp ut field controls
in form.




<br>AngularJs Validate Controls in Form <br>






First Name:model="person.fname" required />
show="personForm.firstname.$error.required"> Required!



Last Name:model="person.lname" required />
show="personForm.lastname.$error.required"> Required!






{{msg}}





Observe above example where property “required” is defined to textbo x
controls and showing error messages in case if those controls are empty. munotes.in

Page 60

60
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
Followi ng 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 $invalid It tells whether field invalid or not based on rules $valid It tells whether field valid or not based on rules $touched It returns true if field has touched or blurred $untouched It tells field has not been touched or blurred yet
Accessing AngularJS Properties of Form and Input Fields

Access properties of form and input fields for validationsas shown below
- Access th e form properties like

.

- Access the Input field properties like .name>.

AngularJS Form with Input Fields Validation :
Following uses different properties of form and input fields in angularjs
application to show validation messages to user based on requirements.
munotes.in

Page 61

61



<br>AngularJs Form and Input Validation Controls <br>





First Name: model="person.fname" required />
Required!


Last Name:model="person.lname" required />
Thanks for Text







Observe above ex ample 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

AngularJS CSS Classes for Form Validation :
In angularjs different classes added to forms for validation based on their
status. Following are the classes add or removed from forms based on the
statuses. Class Description ng-pristine No fields in form has been not modified yet ng-dirty One or more fields in form has been modified ng-valid It tells whether form content valid or not based on rules ng-invalid It tells whether form content invalid or not based on rules AngularJS Applying Classes for Form Validation

Following code uses classes for form validation in angularjs applications.

munotes.in

Page 62

62


<br>AngularJs Applying classes for Form Validation <br>








First Name:model="person.fna me" required />


Last Name:model="person.lname" required />








In the above code classes are written classes form ng-valid and ng-
invalid properties.

AngularJS CSS Classes for Input Field Controls Validation
In angularjs different classes added to input field controls for validation
based on their status. Following are the classes add or removed from input
controls based on the statuses.
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 munotes.in

Page 63

63
AngularJS Applying Classes for Input Field Validation :

Following code uses classes for input fields validation in angularjs
applications.




<br>AngularJs Applying classes for Input Fields Validation <br>








First Name:model="person.fname" required />


Last Name:model="person.lname" required />







In the above code classes are written for input fields ng-valid and ng-
invalid properties.

PROGRAM




<br>AngularJs Form Input Fields Validation E xample <br> munotes.in

Page 64

64





Form validation demo app in AngularJs




model="person.name" required />
show="personFo rm.name.$error.required"> Required!




model="person.address" required />
show="personForm.address.$error.required"> Required!




model="person.mobile" required />
show="personForm.mobile.$error.required">Required number! munotes.in

Page 65

65
Invalid
mobile!





model="person.email" required />
show="personForm.email.$error.required">Required !
Invalid
Email!




model="terms" name="terms" id="terms" required />

You
must agree to the terms








{{msg}}





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?
*****

munotes.in

Page 66

66
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 us er 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.

WHEN TO USE A FILTER IN ANGULARJS? :
To display the data in the view part in a particular format AngularJS filter
can be use d. Data can be displayed in the uppercase format, lowercase
format etc. In whatever format be the entered text it can easily get
displayed in any format by angular as per the type of filter used.
AngularJS Filters can change the way of displaying the out put.

ANGULARJS FILTER IN VIEW TEMPLATE :
Filters are applied on expression to refrain the input and also AngualrJS
Filters can be applied in a view template and on the result obtained by
another filter. Chaining is the phenomenon when filters are applied t o the
already filtered content.

Syntax: munotes.in

Page 67

67
{{ expression | filter1 | filter2 | ... }}
AngularJS Filters can have arguments.

Syntax:
{{ expression | filter:argument1:argument2:... }}
WHEN WILL FILTER GET EXECUTE :
Whenever the inputs have changed in the tem plate, the filter gets to
execute.

TYPES OF BUILT -IN FILTERS IN ANGULARJS :
These are the following built -in filters, let‟s discuss them one by one:



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 :
munotes.in

Page 68

68
Lowercase Filter in AngularJS uses to convert the string i nto 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 filt er 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:
{{expression | currency : 'currency_symbol' : 'fraction'}}
4. FILTER :
It is a pplied 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:
{{ expression | filter : filter_criteria }}
5. ORDERBY :
It is used to sort the data eithe r in ascending or in descending order.

Syntax:
{{ expression | orderBy : predicate_expression : reverse}}
6. DATE :
Date filter in AngularJS use to convert the date into a string according to
the specified date format.

Syntax:
{{date_expression| date : 'format'}} The various formats are: munotes.in

Page 69

69
YYYY,MM,DD,D etc

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}}
CUSTOM FILTERS IN ANGULARJS :
Angular JS provides a way to create our own filter that is customized
filter. User can create one by registering a filter factory function in a
module. AngularJS Filter function should be a pure function. Pure
function means the same result is produced as per the given input. Also, it
should not affect an external state.

PROGRAM :
testAngularJS.htm
Angular JS Filters

AngularJS Sample Application

munotes.in

Page 70

70

Enter first name:
Enter last name:
Enter fees:
Enter subject:

Name i n Upper Case: {{student.fullName() | uppercase}}
Name in Lower Case: {{student.fullName() | lowercase}}
fees: {{student.fees | currency}}
Subject:
  • {{ subject.name + ', marks:' + subject.marks }}

OUTPUT :
Open the file testAngularJS.htm in a web br owser. 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?

*****
munotes.in

Page 72

72
EXPERIMENT 2

AIM :
Implement t he 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.

AngularJS Number Filter Syntax :
{{numberexpression | number}}

Suppose if the expression is given as {{1000 | number}} it will format the
number and return result as 1,000 .

To show number with decimal values the syntax will be as shown below

{{numberexpression | number:fractionsize}}

If the expression is given a s {{1000 | number:2}} it will format the
number and return result as 1,000.00

Default Number filter :{{numberValue | number}}


This line will format the numberValue based on current system locale and
return the formatted value in string.

Number with 4 decimal fraction :{{numberValue | number :
4}}


This line will format the numberValue based on current system locale with
decimal precision of 4 points and return the formatted value in string.

Number with null value :{{null | num ber}}

This line show whenever Number Filter encounters the numberValue a
null, it will return 0 value back.

Number with undefined value :{{undefined | number}}
munotes.in

Page 73

73
This line show whenever Number Filter encounters the numberValue as
undefined , it will return “ ” Empty String value back.

Number is NaN :{{ NanNumber | number}}


This line show whenever Number Filter encounters an Nan numberValue,
it will return “ ” Empty String value back.
var formatterNumber =$filter('number')(value, 2);

Points to keep a Note:
 If input is Nan(Not A Number), then Empty String “” is returned
 If input is null, then 0 gets returned
 If input is undefined, then “” Empty String is returned
 If input is having infinite value, then after formatting Infinity
symbol ∞ is returned
 Number formatting happens based on current locale (system time) for
eg- en_IN local the decimal separator will be “.” and group separator
will be “,”

PROGRAM
Index.html




Example - example -number -filter -production







Default formatting: {{val | number}}

No fractions: {{val | number:0}}

Negative number: {{ -val | number:4}}




Protractor.js
it('should format numbers', function() { munotes.in

Page 74

74
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');
});

it('should update', function() {
element(by.model('val')).clear();
element(by.mod el('val')).sendKeys('3374.333');
expect(element(by.id('number -default')).getText()).toBe('3,374.333');
expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
expect(element(by.binding(' -val | number:4')).getText()).toBe(' -
3,374.333 0');
});

OUTPUT :



QUESTIONS
1. How to show number with decimal values
2. How to limit size of decimal values using angularjs number filter.
3. Write the syntax of number filter?



*****

munotes.in

Page 75

75
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.

AngularJS Date Filter Syntax :
Generally the syntax of date filter
{{dateexpression | date : format}}

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.
Format Expression Result yyyy (Year) {{sampledate|date:"yyyy" }} 2016 yy (Year) {{sam pledate | date:"yy" }} 16 y (Year) {{sampledate | date:"y" }} 2016 MMMM (Month) {{sampledat | date:"MMMM" }} February MMM (Month) {{sampledate | date:"MMM" }} Feb MM (Month) {{sampledate | date:"MMM" }} 02 M (Month) {{sampledate | date:"M" }} 2 dd (Date) {{sampledate | date:"dd" }} 28 d (Date) {{sampledate | date:"d" }} 28 EEEE (Day) {{sampledate | date:"EEEE" }} Sunday EEE (Day) {{sampledate | date:"EEE" }} Sun HH (24 Hours Format) {{sampledate | date:"HH" }} 19 Format Expression Result hh (12 Hours Format) {{sampledate|date:"hh" }} 07 h (12 Hours Format) {{sampledate | date:"h" }} 7 mm (Minute) {{sampledate | date:"mm" }} 16 m (Minute) {{sampledate | date:"m" }} 16 munotes.in

Page 76

76
sss (Milli Seconds) {{sampledate | date:"sss" }} 501 ss (Seconds) {{sample date | date:"ss" }} 45 s (Seconds) {{sampledate | date:"s" }} 45 a (AM/PM) {{sampledate | date:"a" }} PM Z (TimeZone) {{sampledate | date:"a" }} 0530 ww (Week of year) {{sampledate | date:"ww" }} 09 w (Week of year) {{sampledate | date:"w" }} 9 medium {{sampledate|date:"medium" } Feb 28, 2016 7:32:55 PM short {{sampledate | date:"short" }} 2/28/16 7:33 PM fullDate {{sampledate | date:"fullDate" }} Sunday, February 28, 2016 longDate {{sampledate | date:"longDate" }} February 28, 2016 mediumDate {{sampledate | date:"medium" }} Feb 28, 2016 shortDate {{sampledate | date:"shortDate"
}} 2/28/16 mediumTime {{sampledate|date:"mediumTime"
}} 7:37:34 PM shortTime {{sampledate | date:"shortTime"
}} 7:37 PM
PROGRAM :




<br>AngularJs Date filter Example <br>





Enter Number: model="sampledate" style="width:400px" />

munotes.in

Page 77

77
Date with short expression:{{sa mpledate | date:"short" }}


Date with mediumDate expression: {{sampledate | date :
"mediumDate"}}


Date with yyyy -mm-dd hh:mm:ss expression: {{sampledate | date : "yyyy -
mm-dd hh:mm:ss" : 0}}


Date with yyyy -mm-dd hh:mm:ss expression: {{sampledate | date :
"dd/mm/yyyy 'at' hh:mma" : 0}}





OUTPUT :



QUESTIONS
1. Give out the syntax of number filter?
2. Specify any four type of date formats are available with date filter ?
3. What is the use angular date filter?


*****
munotes.in

Page 78

78
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.

How to Create Custom Filter :
In the below custom filter AngularJS example, a string is passed to the
view from the controller via the scope object, but don't want that string to
be displayed as it is. Whenever the string is displayed, a custom filter is
passed in AngularJS which will append another stri ng and display the
completed string to the user.

Few Example of Custom Filter:
Some example requirement that can be solved by creating custom filters
could be:
 Prefix or suffix any String to the input.
 Filter even/odd numbers from an array of.
 Filter base d on any custom logic e. multiple of five etc.
 Reverse a string or.

Steps to Create a Custom Filter :
 Create an AngularJS application.
 Use (dot) .filter API provide by AngularJS framework to add.
 Pss a filter name and filter function to custom.
 Write logic for transforming the input to output in return.







munotes.in

Page 79

79
Custom filter syntax :





PROGRAM :
Index.html




semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bo otstra
p/3.1.1/css/bootstrap.min.css" />


munotes.in

Page 80

80









click="main.clearTitle()">Clear Title

















repeat="movie in main.movies | filter:{ genre: main.selectedGenre, release
d: main.selectedYear, title: main.selectedTitle}">





Title Category Rele ased
{{movie.title}} {{ movie.genre}} {{movie.released}}

munotes.in

Page 81

81



Script.js

(function(){

var app = angular.module("app", []);

app.controller("mainController", function($scope, movieData) {

var typeOf = this;
typeOf.movies = [];

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", munotes.in

Page 82

82
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;
}
};
});
}
()
);




munotes.in

Page 83

83
OUTPUT





munotes.in

Page 84

84


QUESTIONS
1. How to Create Custom Filter
2. Write the steps to create custom filter
3. List out few example of custom filter?




*****

munotes.in

Page 85

85
EXPERIMENT 5

AIM :
Create an applica iton 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 D OM 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 dat a. 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.

Definition and Usage :
The ng-if directive removes the HTML element if the expression evaluates
to false. If the if statement evaluates to true, a copy of the Element is
added in the DOM. The ng-if directive is different from the ng -hide, which
hides the display of the element , where the ng -if directive completely
removes the element from the DOM.

Syntax

Supported by all HTML elements.







munotes.in

Page 86

86

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

// Create AngularJS application
var app = angular.module('demoLearningTurn',[]);

// Create Controller with name mainCtrl

app.controller('m ainCtrl', function($scope){

$scope.txtOptions = {
'1': 'Text Paragraph First',
'2': 'Text Paragraph Second',
'3': 'Text Paragraph Third',
'4': 'Text Paragraph Default'
};
});

Index.html



AngularJS Conditional directive ng-if and ng-<br>switch with example









munotes.in

Page 87

87



AngularJS Conditional directive ng-if








LearningTurn Demo
Text




AngularJS Conditional directive ng-switch








when="1" style="border: 5px solid #000; padding:10px;">Text Paragraph
First


when="2" style="border: 5px solid #000; padding:10px;">Text Paragraph
Second


when="3" style="border: 5px solid #000; padding:10px;">Text Paragraph
Third


default style="border: 5px solid #000; padding:10px;">Text Paragraph De
fault





Tutorial: AngularJS Conditional directive ngIf and ngSwitch with exam
ple




Script.js
function changeBg() {

$("#demo -text").css("background -color", "blue");
}


munotes.in

Page 88

88
OUTPUT





munotes.in

Page 89

89
QUESTIONS
1. List out the parameter values of ng -if directive
2. What is the difference betwee n [hidden]='false' and *ngIf='false' ?
3. Write the syntax of ng -if directive?


*****
munotes.in

Page 90

90
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 :

Definition and Usage :
The ng-style directive specifies the style attribute for the HTML element.
The value of the ng-style attribute must be an object, or an expression
returning an object. The object consists of CSS properties and values, in
key value pairs.

Syntax
Supported by all HTML
elements.

Parameter Values :





Overview :
The ngStyle directive allows you to set CSS style on an HTML element
conditionally.

Known Issues :
Do not use interpolation s 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:
... Value Description expression An expression which returns an object
where the keys are CSS properties, and the
values are CSS values. munotes.in

Page 91

91
as CSS class:
...
Arguments :

PROGRAM :
Index.html




Example - example -ng-style -production




click="myStyle={color:'red '}">
click="myStyle={'background -color':'blue'}">



Sample Text

myStyle={{myStyle}}




Protractor.js
var colorSpan = element(by.css('span'));

it('should check ng-style', function() {
expect(colorSpan.getCssValue('color')).toMatch(/rgba \(0, 0, 0, 1\)|rgb\(0,
0, 0\)/);
element(by.css('input[value= \'set color \']')).click();
expect(colorSpan .getCssValue('color')).toMatch(/rgba \(255, 0, 0, 1\)|rgb\
(255, 0, 0\)/);
element(by.css('input[value=clear]')).click(); Param Type Details ngStyle expression Expression which evals to an object whose keys are
CSS style names and values are corresponding values
for those CSS ke ys.
Since some CSS style names are not valid keys for an
object, they must be quoted. See the 'background -color'
style in the example below. munotes.in

Page 92

92
expect(colorSpan.getCssValue('color')).toMatch(/rgba \(0, 0, 0, 1\)|rgb\(0,
0, 0\)/);
});

Style.css
span {
color: black;
}
OUTPUT









munotes.in

Page 93

93



QUESTIONS
1. Describe the parameter values of ng -style directive?
2. At what priority level does ng -style directive work?
3. What are the two usage of ng -style directive?

*****



munotes.in

Page 94

94
EXPERIMENT 7

AIM :
Create an application to demonstrate mouse an d 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, db lclick,
mouseenter etc. The following table li sts 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

ng-click : The ng -click directive is used to provide event handler for
click event.
ng-dblclick : The directive ng -dblclick in AngularJS invokes whenever an
element with which ng -dblclick is attached is double -clicked. Angular JS will no t
override the element‟s original.
ng-focus : This directive will execute the particular code when the user focuses on
the element with which the ng -focus directive is attached.
ng-blur : This directive will execute the particular code when a user loses fo cuses
from the element with which ng -blur directive attach. munotes.in

Page 95

95
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

The order of mouse event when the mouse clicks on an element
 ng-mousedown
 ng-mouseup
 ng-click

$event Object: passed as an argument, when calling a function. The
$event object contains the Browser‟s event.

PROGRAM







AngularJS ng -click Demo:



Enter Password:



munotes.in

Page 96

96

AngularJS Mouse Events Demo:


mouseenter="enter=true;leave=false;" ng -
mouseleave="leave=true;enter=false">
Mouse Enter show="leave">Leave





OUTPUT :



In the above example, ng -click directive is used to call a
DisplayMessage() function with the 'password' parameter when a user
clicks a button. A 'password' is a model property defined using ng -
model directive in the input box. The DisplayMessage() function is
attached to a $scope object in myController, so it will be accessible
from button click as button comes under myController.
The $window service is used to display an alert.

Mouse Events :
In the above example, the ng -class dire ctive includes map of CSS
classes, so redDiv will be applied if enter=true and yellowDiv will be
munotes.in

Page 97

97
applied if leave=true. The ng -mouseenter directive sets 'enter' to true,
which will apply redDiv class to the

element. In the same way,
ng-mouseleave wil l set leave to true, which will apply yellowDiv class.

QUESTIONS
1. List out any four event directives?
2. What is the use of $event Object?
3. Differentiate between ng -focus and ng -blur directive?

*****
munotes.in

Page 98

98
EXPERIMENT 8

AIM :
Create an application to demonstrate b uiltin 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 behav ior to that DOM element or even transform the DOM
element and its children. In short, it extends the HTML.

Most of the directives in AngularJS are starting with ng- where ng
stands for Angular. AngularJS includes various built -in directives. In
addition t o this, custom directives can also be created for the
application.

The following table lists the important built -in AngularJS directives.
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-controller Attaches the controller of MVC to the view. 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 att ributes
starting with ng-prefix.
 ng-app − This directive starts an AngularJS Application.
 ng-init − This directive initializes application data. munotes.in

Page 99

99
 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 i n 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 direct ive is used for two -way data binding in AngularJS.
It binds ,