0% found this document useful (0 votes)
16 views28 pages

Module 5 AngularJs

AngularJS is an open-source JavaScript framework developed by Google for building single-page applications (SPAs) that enhance performance by updating only parts of a web page. It follows the MVC architecture, where the Model manages data, the View displays data, and the Controller handles user input. AngularJS uses directives to extend HTML functionality, supports data binding, and facilitates communication between the view and controller through the $scope object.

Uploaded by

swasthi u shetty
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views28 pages

Module 5 AngularJs

AngularJS is an open-source JavaScript framework developed by Google for building single-page applications (SPAs) that enhance performance by updating only parts of a web page. It follows the MVC architecture, where the Model manages data, the View displays data, and the Controller handles user input. AngularJS uses directives to extend HTML functionality, supports data binding, and facilitates communication between the view and controller through the $scope object.

Uploaded by

swasthi u shetty
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 5 AngularJS

INTRODUCTION TO Angular JS

• Angular JS is an open source JavaScript framework written in Javascript that is used to


build web applications.
• Angular Js is developed by Google.
• It is an excellent framework for building single phase applications (SPA).
• 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(only required part of the web page gets refreshed, for ex;ESPN Live cricket
score)
• The page does not reload or transfer control to another page during the process. This
ensures high performance and loading pages faster.
• AngularJS is a JavaScript-based front-end web framework and is used to design Single
Page Applications.

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 1


Module 5 AngularJS
AngularJS MVC Architecture

• MVC stands for Model View Controller.


• The MVC pattern is made up of the following three parts:
• Model: It is responsible for managing application data. It responds to the requests from
view and to the instructions from controller to update itself.
• View: It is responsible for displaying all data or only a portion of data to the users. It also
specifies the data in a particular format triggered by the controller's decision to present the
data.
• Controller: It is responsible to control the relation between models and views. It responds
to user input and performs interactions on the data model objects. The controller receives
input, validates it, and then performs operations.
AngularJS is distributed as a JavaScript file, and can be added to a web page with a script
tag:
Example:
<script src="[Link]
[Link]"></script>

AngularJS First Example

• AngularJS applications are a mix of HTML and JavaScript. The first thing you need
is an HTML page.

<!DOCTYPE html>
<html>
<head>
.
.
</head>
<body>
.
.
</body>
</html>

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 2


Module 5 AngularJS
• Second, you need to include the AngularJS JavaScript file in the HTML page so we
can use AngularJS:

<!DOCTYPE html>
<html>
<head>
<script src="[Link]
></script>
</head>
<body>
.
.
</body>
</html>

Example:
<!DOCTYPE html>
<html>
<script src="[Link]
[Link]"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
</body>
</html>

• The ng-app directive tells AngularJS that the <div> element is the "owner" of an
AngularJS application.

• The ng-model directive binds the value of the input field to the application variable name.

• The ng-bind directive binds the content of the <p> element to the application
variable name.

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 3


Module 5 AngularJS
AngularJS Directives
• AngularJS facilitates you to extend HTML with new attributes. These attributes are called
directives.
• There is a set of built-in directive in AngularJS which offers functionality to your
applications.
• Directives are special HTML attributes starting with ng- prefix.
• Following are the most common directives:
❖ ng-app: This directive starts an AngularJS Application.
❖ The ng-init directive initializes AngularJS application variables.
❖ The ng-model directive binds the value of HTML controls (input, select, textarea)
to application data.

ng-app directive
• ng-app directive defines the root element.
• It is also used to load various AngularJS modules in AngularJS Application.
• The ng-app directive also tells AngularJS that the <div> element is the "owner" of the
AngularJS application.
• Example 1:

<!DOCTYPE html>
<html>
<script
src="[Link]
<body>
<div ng-app="" ng-init="firstName='abhi'">
<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>
</div>
</body>
</html>

Data Binding

• The {{ firstName }} expression, in the above example, is an AngularJS data binding


expression.
• Data binding in AngularJS binds AngularJS expressions with AngularJS data.
• In the above example {{ firstName }} is bound with ng-model="firstName".

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 4


Module 5 AngularJS
Example 2:

• In this example two text fields are bound together with two ng-model directives:

<div ng-app="" ng-init="quantity=1;price=5">


Quantity: <input type="number" ng-model="quantity">
Costs: <input type="number" ng-model="price">
Total in dollar: {{ quantity * price }}
</div>

Repeating HTML Elements


• The ng-repeat directive repeats an HTML element:

<!DOCTYPE html>
<html>
<script
src="[Link]
<body>
<div ng-app="" ng-init="names=['','Mahesh','Abhi']">
<p>Looping with ng-repeat:</p>
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>
</body>
</html>

Looping with ng-repeat:


• Mahesh
• Abhi

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 5


Module 5 AngularJS
Example
<!DOCTYPE html>
<html>
<script
src="[Link]
<body>
<div ng-app="" ng-init="firstName=''">
<p>The name is <span ng-bind="firstName"></span></p>
</div>
</body>
</html>
OUTPUT:
The name is

AngularJS Expressions
• In AngularJS, expressions are used to bind application data to HTML.
• AngularJS expressions are written inside double braces: {{ expression }}.
• AngularJS expressions can also be written inside a directive: ng-bind="expression".

• AngularJS expressions are much like JavaScript expressions: They can contain literals,
operators, and variables.

Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}

• AngularJS will "output" data exactly where the expression is written:

Example:

<!DOCTYPE html>
<html>
<script
src="[Link]
<body>

<div ng-app="">
<p>My first expression: {{ 6 + 5 }}</p>
</div>

</body>
</html>

OUTPUT:
My first expression: 11

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 6


Module 5 AngularJS

Differences between AngularJS Expressions vs. JavaScript Expressions

• Like JavaScript expressions, AngularJS expressions can contain literals, operators, and
variables.
• Unlike JavaScript expressions, AngularJS expressions can be written inside HTML.
• AngularJS expressions do not support conditionals, loops, and exceptions, while
JavaScript expressions do.
• AngularJS expressions support filters, while JavaScript expressions do not.

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 7


Module 5 AngularJS
AngularJS Modules
❖ An AngularJS module defines an application.
❖ A module in AngularJS is a container of the different parts of an application such as
controller, service, filters, directives, factories etc.
❖ The module is a container for the different parts of an application.
❖ The module is a container for the application controllers.
❖ Controllers always belong to a module.

Creating a Module

❖ A module is created by using the AngularJS function [Link]

Example:

<div ng-app="myApp">...</div>
<script>
var app = [Link]("myApp", []);
</script>

❖ The "myApp" parameter refers to an HTML element in which the application will run.

❖ Now you can add controllers, directives, filters, and more, to your AngularJS application.

Meaning

var app = [Link]("myApp", []);

❖ The [] parameter in the module definition can be used to define dependent


modules.

Example:

1) Create Application Module


An AngularJS application must create a top level application module. This application module can contain
other modules, controllers, filters, etc.

<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/[Link]"></script>
</head>
<body ng-app="myApp">
@* HTML content *@
<script>
var myApp = [Link]('myApp', []);

</script>
</body>
</html>

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 8


Module 5 AngularJS
Explanation:
❖ In the above example, the [Link]() method creates an application module, where the
first parameter is a module name which is same as specified by ng-app directive.
❖ The second parameter is an array of other dependent modules []. In the above example we are
passing an empty array because there is no dependency.
❖ The [Link]() method returns specified module object if no dependency is specified.

2) Create controller Module


Create controller module in myApp module.
Example:
<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/[Link]"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
{{message}}
</div>
<script>
var myApp = [Link]("myApp", []);

[Link]("myController", function ($scope) {


$[Link] = "Hello Welcome to MCA Department!";
});
</script>
</body>
</html>

Explanation:
❖ In the above example, we have created a controller named "myController" using
[Link]() method.
❖ Here, myApp is an object of a module, and controller() method creates a controller inside
"myApp" module.

3) Modules in Separate Files

In the above example, we created application module and controller in the same HTML file. However, we can
create separate JavaScript files for each module as shown below.

Example:

<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/[Link]"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
{{message}}
</div>
<script src="[Link]" ></script>
<script src="[Link]" ></script>
</body>
</html>

[Link]
var myApp = [Link]("myApp", []);

[Link]
[Link]("myController", function ($scope) {
$[Link] = "Hello Welcome to MCA Department!";
});

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 9


Module 5 AngularJS
AngularJS Scopes ($scope) with Example
• In angularjs, we have a two main parts one is view (HTML) and another one is controllers
• The view represents whatever (data from data model) the data we want to show it on
page and controller will hold all the variables and functions which we used to show it on
page
• Scope variable helps to communicate between view & controller.
• We create controller in angularjs we will send $scopeobject as a parameter and set
controller properties (variables and functions) in $scope object. In view we can access
those $scope properties and show data that values in page.
• Scope is an object which holds variables and functions in controller and allow us to
access that data between Views and Controller.
• Scope works as a intermediate between view (html) and controller and facilitate them to
communicate with each other.

Example:

<script type="text/javascript">
var app = [Link]('angularscopeapp', []);
[Link]('angularctrl', function ($scope) {
$[Link] = "Welcome to";
$[Link] = "JCEMCA";
});
</script>
<div ng-app="angularscopeapp" ng-controller="angularctrl">
First Name: {{fname}}<br />
Last Name: {{lname}}<br />
Full Name: <b>{{fname +" "+ lname}}</b>
</div>
Explanation of AngularJS Scope Syntax

• In above example we are defining controller in angularjs we are sending $scope object as an
argument and assigned parameters (fname, lname) to $scope object.
• Once we add properties to $scope object in controller we will get access to use those properties in
view (HTML).
• In view we can access those $scope properties by defining like {{fname}} we don’t need to prefix
with $scope.

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 10


Module 5 AngularJS
AngularJS Controllers
❖ The controller in AngularJS is a JavaScript function that maintains the application data
and behavior using $scope object.
❖ The ng-controller directive is used to specify a controller in HTML element, which will
add behavior or maintain the data in that HTML element and its child elements.
❖ The following example demonstrates attaching properties to the $scope object inside a
controller and then displaying property value in HTML.
Example: AngularJS Controller

<!DOCTYPE html>
<html >
<head>
<title>AngualrJS Controller</title>
<script src="~/Scripts/[Link]"></script>
</head>
<body ng-app="myNgApp">
<div ng-controller="myController">
{{message}}
</div>
<script>
var ngApp = [Link]('myNgApp', []);

[Link]('myController', function ($scope) {


$[Link] = "Hello World!";
});
</script>
</body>
</html>

Result:

Hello World!
❖ In the above example, ng-controller="myController" directive is applied to the <div> element
where "myController" is the name of the controller. Inside div element, we have specified
{{message}} expression.
❖ The $ sign is used as prefix in all the built-in objects in AngularJS, so that we can differentiate
AngularJS built-in objects and other objects.
❖ Now, to create "myController", we need to create an application module. The module defines an
application and keeps its parts like controllers, services etc. out of global scope. (You will learn
about the module in the next section.) After creating a module, we add a controller function using
the controller() method where the first parameter should be the name of the controller and second
parameter should be a function for the controller. The controller function includes $scope
parameter which will be injected by AngularJS framework.

❖ AngularJS controllers control the data of AngularJS applications.


❖ AngularJS controllers are regular JavaScript Objects.
❖ AngularJS applications are controlled by controllers.
❖ The ng-controller directive defines the application controller.

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 11


Module 5 AngularJS

Example
<!DOCTYPE html>
<html>
<script
src="[Link]
<body>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope) {
$[Link] = "";
$[Link] = "xyz";
});
</script>
</body>
</html>

Application explained:

❖ The AngularJS application is defined by ng-app="myApp". The application runs inside


the <div>.

❖ The ng-controller="myCtrl" attribute is an AngularJS directive. It defines a controller.

❖ The myCtrl function is a JavaScript function.

❖ AngularJS will invoke the controller with a $scope object.

❖ In AngularJS, $scope is the application object (the owner of application variables and
functions).

❖ The controller creates two properties (variables) in the scope (firstName and lastName).

❖ The ng-model directives bind the input fields to the controller properties (firstName and
lastName).

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 12


Module 5 AngularJS

AngularJS Filters
• Filters can be added in AngularJS to format data.
• AngularJS provides filters to transform data:
• currency: Format a number to a currency format.
• date: Format a date to a specified format.
• filter: Select a subset of items from an array.
• json: Format an object to a JSON string.
• limitTo: Limits an array/string, into a specified number of elements/characters.
• lowercase: Format a string to lower case.
• number: Format a number to a string.
• orderBy: Orders an array by an expression.
• uppercase: Format a string to upper case.
Adding Filters to Expressions

• Filters can be added to expressions by using the pipe character |, followed by a filter.

• The uppercase filter Convert strings to upper case:

Example

<!DOCTYPE html>
<html>
<script
src="[Link]
<body>
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ lastName | uppercase }}</p>
</div>
<script>
[Link]('myApp', []).controller('personCtrl', function($scope) {
$[Link] = "",
$[Link] = "xyz"
});
</script>
</body>
</html>

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 13


Module 5 AngularJS
❖ The lowercase filter converts strings to lower case:

<div ng-app="myApp" ng-controller="personCtrl">

<p>The name is {{ lastName | lowercase }}</p>

</div>

Adding Filters to Directives

Filters are added to directives, like ng-repeat, by using the pipe character |, followed by a filter:

Example

The orderBy filter sorts an array:

<!DOCTYPE html>
<html>
<script src="[Link]
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<p>Looping with objects:</p>
<ul>
<li ng-repeat="x in names | orderBy:'department'">
{{ [Link] + ', ' + [Link] }}
</li>
</ul>
</div>
<script>
[Link]('myApp', []).controller('namesCtrl', function($scope) {
$[Link] = [
{name:'',department:'MCA'},
{name:'Harish',department:'CS'},
{name:'Rajesh',department:'Mechanical'},
{name:'Mahesh',department:'civil'},];
});
</script>
</body>
</html>

OUTPUT:

Looping with objects:

• Mahesh, civil
• Harish, CS
• , MCA
• Rajesh, Mechanical

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 14


Module 5 AngularJS

The filter Filter

❖ The filter Filter can only be used on arrays because it selects a subset of an array.
❖ It returns an array containing only the matching items.
❖ This example will return the names that contain the letter "o".

Example:

<!DOCTYPE html>
<html>
<script src="[Link]
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | filter : 'o'">
{{ x }}
</li>
</ul>
</div>
<script>
[Link]('myApp', []).controller('namesCtrl', function($scope) {
$[Link] = [
'', 'Roopa',
'Rajesh',
'Mahesh',
'John',
'Santosh',
'Satish',
];
});
</script>
<p>This example displays only the names containing the letter "o".</p>
</body>
</html>

OUTPUT:

Roopa
John
Santosh

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 15


Module 5 AngularJS
AngularJS Services
• In AngularJS you can make your own service, or use one of the many built-in services.

• In AngularJS, a service is a function, or object.

• AngularJS has about 30 built-in services. One of them is the $location service.

•The $location service has methods which return information about the location of the
current web page:
Example

Use the $location service in a controller:

var app = [Link]('myApp', []);


[Link]('customersCtrl', function($scope, $location) {
$[Link] = $[Link]();
});

The $timeout Service

• The $timeout service is AngularJS' version of the [Link] function.

Example:

• Display a new message after two seconds:

var app = [Link]('myApp', []);


[Link]('myCtrl', function($scope, $timeout) {
$[Link] = "Hello Students!";
$timeout(function () {
$[Link] = "Welcome to JCE MCA Department";
}, 3000);
});

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 16


Module 5 AngularJS
The $interval Service

o The $interval service is AngularJS' version of the [Link] function.

Example

Display the time every second:

var app = [Link]('myApp', []);


[Link]('myCtrl', function($scope, $interval) {
$[Link] = new Date().toLocaleTimeString();
$interval(function () {
$[Link] = new Date().toLocaleTimeString();
}, 1000);
});

AngularJS Events
• AngularJS has its own HTML events directives.
• You can add AngularJS event listeners to your HTML elements by using one or more of
these directives:
• ng-blur
• ng-change
• ng-click
• ng-copy
• ng-cut
• ng-dblclick
• ng-focus
• ng-keydown
• ng-keypress
• ng-keyup
• ng-mousedown
• ng-mouseenter
• ng-mouseleave
• ng-mousemove
• ng-mouseover
• ng-mouseup
• ng-paste

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 17


Module 5 AngularJS

Mouse Events

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 18


Module 5 AngularJS
Mouse events occur when the cursor moves over an element, in this order:

1. ng-mouseover
2. ng-mouseenter
3. ng-mousemove
4. ng-mouseleave

Or when a mouse button is clicked on an element, in this order:

1. ng-mousedown
2. ng-mouseup
3. ng-click

You can add mouse events on any HTML element.

Example

Increase the count variable when the mouse moves over the h1 element:

<!DOCTYPE html>
<html>
<script src="[Link]
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-mousemove="count = count + 1">Mouse Over Me!</h1>
<h2>{{ count }}</h2>
</div>
<script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope) {
$[Link] = 0;
});
</script>
</body>
</html>

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 19


Module 5 AngularJS
The ng-click Directive
The ng-click directive defines AngularJS code that will be executed when the element is being
clicked.

Example
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="count = count + 1">Click me!</button>
<p>{{ count }}</p>
</div>
<script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope) {
$[Link] = 0;
});
</script>

Toggle, True/False

If you want to show a section of HTML code when a button is clicked, and hide when the button
is clicked again, like a dropdown menu, make the button behave like a toggle switch:

<!DOCTYPE html>
<html>
<script src="[Link]
<body>

<div ng-app="myApp" ng-controller="myCtrl">


<button ng-click="myFunc()">Click Me!</button>
<div ng-show="showMe">
<h1>Breakfast Menu:</h1>
<div>Idli</div>
<div>Masala Dosa</div>
<div>Plain Dosa</div>
</div>
</div>
<script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope) {
$[Link] = false;
$[Link] = function() {
$[Link] = !$[Link];
}
});
</script>

<p>Click the button to show/hide the menu.</p>


Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 20
Module 5 AngularJS

</body>
</html>

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 21


Module 5 AngularJS
AngularJS Forms
Forms in AngularJS provides data-binding and validation of input controls.

Input Controls

Input controls are the HTML input elements:

• input elements
• select elements
• button elements
• textarea elements

Checkbox

A checkbox has the value true or false. Apply the ng-model directive to a checkbox, and use its
value in your application.

Example:

<!DOCTYPE html>
<html>
<script src="[Link]
<body>

<div ng-app="">
<form>
Check to show a header:
<input type="checkbox" ng-model="myVar">
</form>
<h1 ng-show="myVar">My Header</h1>
</div>

<p>The header's ng-show attribute is set to true when the checkbox is checked.</p>

</body>
</html>

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 22


Module 5 AngularJS
Radiobuttons

❖ Bind radio buttons to your application with the ng-model directive.

❖ Radio buttons with the same ng-model can have different values, but only the selected one
will be used.

Example
<!DOCTYPE html>
<html>
<script src="[Link]
<body ng-app="">

<form>
Pick a topic:
<input type="radio" ng-model="myVar" value="HTML">HTML
<input type="radio" ng-model="myVar" value="Javascript">Javascript
<input type="radio" ng-model="myVar" value="PHP">PHP
</form>

<div ng-switch="myVar">
<div ng-switch-when="HTML">
<h1>HTML</h1>
<p>Welcome to a world of [Link] is web progamming language</p>
</div>
<div ng-switch-when="Javascript">
<h1>Javascript</h1>
<p>This is client-side scripting language.</p>
</div>
<div ng-switch-when="PHP">
<h1>PHP</h1>
<p>This is server-side scripting language.</p>
</div>
</div>
<p><b>The ng-switch directive hides and shows HTML sections depending on the value of the
radio buttons.</b></p>

</body>
</html>

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 23


Module 5 AngularJS

AngularJS Form Validation


❖ AngularJS can validate input data.
❖ AngularJS offers client-side form validation.
❖ AngularJS monitors the state of the form and input fields (input, textarea, select), and lets you notify the user
about the current state.
❖ AngularJS also holds information about whether they have been touched, or modified, or not.
❖ AngularJS includes the following validation directives.
Directive Description
ng-required Sets required attribute on an input field.
ng- Sets minlength attribute on an input field.
minlength
ng- Sets maxlength attribute on an input field. Setting the attribute to a negative or non-numeric
maxlength value, allows view values of any length.
ng-pattern Sets pattern validation error key if the ngModel value does not match the specified RegEx
expression.

❖ Example to implement validation in the student form which contains First Name, Last Name and Email fields.

<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/[Link]"></script>
</head>
<body ng-app >
<form name="studentForm" novalidate>
<label for="firstName">First Name: </label> <br />
<input type="text" name="firstName" ng-model="[Link]" ng-required="true" />
<span ng-show="[Link].$touched && [Link].$[Link]">First name is
required.</span><br /><br />
<label for="lastName">Last Name</label><br />
<input type="text" name="lastName" ng-minlength="3" ng-maxlength="10" ng-model="[Link]" />
<span ng-show="[Link].$touched && [Link].$[Link]">min 3
chars.</span>
<span ng-show="[Link].$touched && [Link].$[Link]">Max 10
chars.</span><br /><br />
<label for="dob">Email</label><br />
<input type="email" id="email" ng-model="[Link]" name="email" />
<span ng-show="[Link].$touched && [Link].$[Link]">Please enter valid
email id.</span><br /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 24


Module 5 AngularJS

Let's understand the above example step by step:

1. Apply novalidate attribute in <form> tag. The novalidate attribute will disable the browser's default
validation.
2. Set the name attribute in <form> and other elements, which will be used to obtain a reference of the
elements.
3. Now, set ng-required="true" on the input element of First Name. Also, set name attribute to the name of
model property, "firstName" in this case.
4. Create <span> element to specify an error message with every input filed where the validation directive is
applied.
5. Set ng-show directives to <span> element to an expression "[Link].$touched &&
[Link].$[Link]". This expression will return true if a user tabbed out without
entering FirstName.
6. The same way set ng-minlength & ng-maxlength directives to last name. Also, set ng-show directive to
"[Link].$touched && [Link].$[Link]" expression to <span>
element adjacent to LastName input field.
7. Create another <span> for maxlength validation message.
8. Email will be validated automatically with input type=email. Also, create <span> for email validation
message.

We have applied an expression "[Link].$touched && [Link].$[Link]" to


the <span>, in the above example. $touched & $error are built-in properties which return the state of the specified
input controls and form. Let's learn about the state properties.

State Properties

❖ Angular includes properties which return the state of form and input controls.
❖ The state of the form and control changes based on the user's interaction and validation errors. These built-
in properties can be accessed using form name or input control name.
❖ To check the form status use [Link], and to check the state of input control,
use [Link].

The following lists the state properties.

❖ AngularJS is constantly updating the state of both the form and the input fields.
❖ Input fields have the following states:

1) $untouched The field has not been touched yet


2) $touched The field has been touched
3) $pristine The field has not been modified yet
4) $dirty The field has been modified
5) $invalid The field content is not valid
6) $valid The field content is valid

They are all properties of the input field, and are either true or false.

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
• $submitted The form is submitted

They are all properties of the form, and are either true or false.

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 25


Module 5 AngularJS
Example:2
<!DOCTYPE html>
<html>
<script src="[Link]
<body>

<h2>Validation Example</h2>

<form ng-app="myApp" ng-controller="validateCtrl"


name="myForm" novalidate>

<p>Username:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="[Link].$dirty && [Link].$invalid">
<span ng-show="[Link].$[Link]">Username is required.</span>
</span>
</p>

<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="[Link].$dirty && [Link].$invalid">
<span ng-show="[Link].$[Link]">Email is required.</span>
<span ng-show="[Link].$[Link]">Invalid email address.</span>
</span>
</p>

<p>
<input type="submit"
ng-disabled="[Link].$dirty && [Link].$invalid ||
[Link].$dirty && [Link].$invalid">
</p>

</form>

<script>
var app = [Link]('myApp', []);
[Link]('validateCtrl', function($scope) {
$[Link] = '';
$[Link] = '.ad@[Link]';
});
</script>

</body>
</html>
Example Explained

❖ The AngularJS directive ng-model binds the input elements to the model.

❖ The model object has two properties: user and email.

❖ Because of ng-show, the spans with color:red are displayed only when user or email is $dirty and $invalid.

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 26


Module 5 AngularJS
AngularJS Validation CSS Classes
AngularJS includes following CSS classes to allow styling of form and input controls based on the state
of form field.

CSS class Description


ng-valid Angular will set this CSS class if the input field is valid without errors.
ng-invalid Angular will set this CSS class if the input does not pass validations.
ng-pristine Angular will set this CSS class if a user has not interacted with the control yet.
ng-dirty Angular will set this CSS class if the value of form field has been changed.
ng-touched Angular will set this CSS class if a user tabbed out from the input control.
ng-untouched Angular will set this CSS class if a user has not tabbed out from the input
control.
ng-submitted Angular will set this CSS class if the form has been submitted.

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 27


Module 5 AngularJS

Question Bank Module 5

1. Briefly discuss the use of filter in Angular JS with an example.


2. What is Angular JS? Explain the following Angular JS directives:
(i) ng_app (ii) ng_model (iii) ng_bind
3. How do you do validation using AngularJS
4. Explain AngularJS directives with examples.
5. Write an Angular JS program to use expressions.
6. What is a Angular JS Service? Explain any three of them by using code snippet.
7. Write an Angular JS program to demonstrate client-side form validation.
8. What is AngularJS data binding? Write a AngularJS program to add controller.
9. What are AngularJS filters? Write a AngularJS program to show how you can add filters
expression.
10. What is AngularJS service? Explain any 4 of them. Write a AngularJS program to show how
you can use $location service.

Prof. Rajendra M. Jotawar Dept. of MCA, AIT, Bangalore 28

You might also like