0% found this document useful (0 votes)
8 views

WEB TECHNOLOGIES_MODUEL_3(MMC105)DOM and Events

AngularJS is an MVVM framework developed by Google for creating Single Page Applications and dynamic web apps, offering advantages like less coding and extensive UI. Key features include two-way data binding, MVC pattern, and easy server communication. The document provides guidance on using AngularJS, including directives, expressions, and module creation, along with examples for practical understanding.

Uploaded by

gasachin587
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)
8 views

WEB TECHNOLOGIES_MODUEL_3(MMC105)DOM and Events

AngularJS is an MVVM framework developed by Google for creating Single Page Applications and dynamic web apps, offering advantages like less coding and extensive UI. Key features include two-way data binding, MVC pattern, and easy server communication. The document provides guidance on using AngularJS, including directives, expressions, and module creation, along with examples for practical understanding.

Uploaded by

gasachin587
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
You are on page 1/ 113

WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

AngularJS Introduction
What is AngularJs?
AngularJs is an MVVM framework and that help us to create Single Page Applications (SPA) and dynamic web apps.
AngularJS will be maintained and developed by Google Inc.

AngularJs is supported to MVVM and stands for Model-View-Whatever. It's also known as MV*. The (*)
means "whatever you want to do...”.

AngularJS Advantages
If we use angularjs in our applications we have the following advantages.

1. Less Coding

2. More Extensive UI

3. Developed by Google Inc

AngularJS Features
The following are the features of angularjs.

1. Two-way data binding

2. MVC pattern

3. Template and Custom directive

4. Server Communication and REST friendly

5. dynamic page Linking

6. Validations

7. Dependency injection

The angularjs uses prefix “ng" for data binding and it handles all the DOM and AJAX requests easily.

Why do we need to use AngularJs?


AngularJs is a framework not a library like jQuery etc. and it does not depend on jQuery instead, it will use jQLite.

The key reasons to use AngularJs as given below.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 1|Page


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

1. Supported to two-way data binding

2. Write Less code

3. Scope inheritable

4. DOM manipulations

5. Partial Views

6. Easy to used Routes

7. Extensible declarative UI

8. Create custom directives very easy

9. Filters Flexibility

10. Supported to REST communication

How to use AngularJs?


Before You Start AngularJs, follow the easy steps. The steps as given bellows.

1. Need to installed plug-ins

Manually we can download AngularJs framework from angularjs site http://angularjs.org/ or we can include following
CDN in header section of our application to use angularjs

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

2. Need to Understand basic overviews

a. ngApp

b. ng-controller

c. ngModule etc.

3. Getting started with an AngularJs Applications

AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.

AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 2|Page


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

AngularJS is a JavaScript Framework


AngularJS is a JavaScript framework written in JavaScript.

AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

AngularJS Extends HTML


AngularJS extends HTML with ng-directives.

The ng-app directive defines an AngularJS application.

The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

The ng-bind directive binds application data to the HTML view.

AngularJS Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>

</body>
</html>

Example explained:

AngularJS starts automatically when the web page has loaded.

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.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 3|Page


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

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

AngularJS Directives
As you have already seen, AngularJS directives are HTML attributes with an ng prefix.

The ng-init directive initializes AngularJS application variables.

AngularJS Example
<div ng-app="" ng-init="firstName='John'">

<p>The name is <span ng-bind="firstName"></span></p>

</div>

Alternatively with valid HTML:

AngularJS Example
<div data-ng-app="" data-ng-init="firstName='John'">

<p>The name is <span data-ng-bind="firstName"></span></p>

</div>

You can use data-ng-, instead of ng-, if you want to make your page HTML valid.

You will learn a lot more about directives later in this tutorial.

AngularJS Expressions
AngularJS expressions are written inside double braces: {{ expression }}.

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

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 4|Page


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

AngularJS Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

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

</body>
</html>

AngularJS expressions bind AngularJS data to HTML the same way as the ng-bind directive.

AngularJS Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p>{{name}}</p>
</div>

</body>
</html>

You will learn more about expressions later in this tutorial.

AngularJS Applications
AngularJS modules define AngularJS applications.

AngularJS controllers control AngularJS applications.

The ng-app directive defines the application, the ng-controller directive defines the controller.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 5|Page


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

AngularJS Example
<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 = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>

AngularJS modules define applications:

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

AngularJS controllers control applications:

AngularJS Controller
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});

AngularJS Expressions
AngularJS binds data to HTML using Expressions.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 6|Page


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

AngularJS Expressions
AngularJS expressions can be written inside double braces: {{ expression }}.

AngularJS expressions can also be written inside a directive: ng-bind="expression".

AngularJS will resolve the expression, and return the result exactly where the expression is written.

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

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

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

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

</body>
</html>

If you remove the ng-app directive, HTML will display the expression as it is, without solving it:

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div>
<p>My first expression: {{ 5 + 5 }}</p>
</div>

</body>
</html>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 7|Page


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

You can write expressions wherever you like, AngularJS will simply resolve the expression and return the result.

Example: Let AngularJS change the value of CSS properties.

Change the color of the input box below, by changing its value:

lightblue

Example
<div ng-app="" ng-init="myCol='lightblue'">

<input style="background-color:{{myCol}}" ng-model="myCol">

</div>

AngularJS Numbers
AngularJS numbers are like JavaScript numbers:

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

<p>Total in dollar: {{ quantity * cost }}</p>

</div>

Same example using ng-bind:

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

<p>Total in dollar: <span ng-bind="quantity * cost"></span></p>

</div>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 8|Page


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

Using ng-init is not very common. You will learn a better way to initialize data in the chapter about controllers.

AngularJS Strings
AngularJS strings are like JavaScript strings:

Example
<div ng-app="" ng-init="firstName='John';lastName='Doe'">

<p>The name is {{ firstName + " " + lastName }}</p>

</div>

Same example using ng-bind:

Example
<div ng-app="" ng-init="firstName='John';lastName='Doe'">

<p>The name is <span ng-bind="firstName + ' ' + lastName"></span></p>

</div>

AngularJS Objects
AngularJS objects are like JavaScript objects:

Example
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">

<p>The name is {{ person.lastName }}</p>

</div>

Same example using ng-bind:

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 9|Page


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

Example
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">

<p>The name is <span ng-bind="person.lastName"></span></p>

</div>

AngularJS Arrays
AngularJS arrays are like JavaScript arrays:

Example
<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is {{ points[2] }}</p>

</div>

Same example using ng-bind:

Example
<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is <span ng-bind="points[2]"></span></p>

</div>

AngularJS Modules
An AngularJS module defines an application.

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.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 10 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

Creating a Module
A module is created by using the AngularJS function angular.module

<div ng-app="myApp">...</div>

<script>

var app = angular.module("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.

Adding a Controller
Add a controller to your application, and refer to the controller with the ng-controller directive:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

{{ firstName + " " + lastName }}

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 11 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</div>

<script>

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

app.controller("myCtrl", function($scope) {

$scope.firstName = "John";

$scope.lastName = "Doe";

});

</script>

</body>

</html>

Adding a Directive
AngularJS has a set of built-in directives which you can use to add functionality to your application.

For a full reference, visit our AngularJS directive reference.

In addition you can use the module to add your own directives to your applications:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 12 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<div ng-app="myApp" w3-test-directive></div>

<script>

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

app.directive("w3TestDirective", function() {

return {

template : "I was made in a directive constructor!"

};

});

</script>

</body>

</html>

Modules and Controllers in Files


It is common in AngularJS applications to put the module and the controllers in JavaScript files.

In this example, "myApp.js" contains an application module definition, while "myCtrl.js" contains the controller:

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

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


{{ firstName + " " + lastName }}
</div>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 13 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<script src="myApp.js"></script>
<script src="myCtrl.js"></script>

</body>
</html>

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

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

Without the [] parameter, you are not creating a new module, but retrieving an existing one.

myCtrl.js
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName= "Doe";
});

AngularJS Directives
AngularJS directives are extended HTML attributes with the prefix ng-.

The ng-app directive initializes an AngularJS application.

The ng-init directive initializes application data.

The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

Read about all AngularJS directives in our AngularJS directive reference.

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 14 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<div ng-app="" ng-init="firstName='John'">

<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>The ng-app directive also tells AngularJS that the <div> element is the "owner" of the AngularJS
application.

Data Binding
The {{ firstName }} expression, in the example above, is an AngularJS data binding expression.

Data binding in AngularJS binds AngularJS expressions with AngularJS data.

{{ firstName }} is bound with ng-model="firstName".

In the next example two text fields are bound together with two ng-model directives:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 15 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

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

<h2>Cost Calculator</h2>

Quantity: <input type="number" ng-model="quantity">

Price: <input type="number" ng-model="price">

<p><b>Total in dollar:</b> {{quantity * price}}</p>

</div>

</body>

</html>

Using ng-init is not very common. You will learn how to initialize data in the chapter about controllers.

Repeating HTML Elements


The ng-repeat directive repeats an HTML element:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="" ng-init="names=['Jani','Hege','Kai']">

<p>Looping with ng-repeat:</p>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 16 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<ul>

<li ng-repeat="x in names">

{{ x }}

</li>

</ul>

</div>

</body>

</html>

The ng-repeat directive actually clones HTML elements once for each item in a collection.

The ng-repeat directive used on an array of objects:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="" ng-init="names=[

{name:'Jani',country:'Norway'},

{name:'Hege',country:'Sweden'},

{name:'Kai',country:'Denmark'}]">

<p>Looping with objects:</p>

<ul>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 17 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<li ng-repeat="x in names">

{{ x.name + ', ' + x.country }}</li>

</ul>

</div>

</body>

</html>

AngularJS is perfect for database CRUD (Create Read Update Delete) applications.
Just imagine if these objects were records from a database.

The ng-app Directive


The ng-app directive defines the root element of an AngularJS application.

The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded.

The ng-init Directive


The ng-init directive defines initial values for an AngularJS application.

Normally, you will not use ng-init. You will use a controller or module instead.

You will learn more about controllers and modules later.

The ng-model Directive


The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 18 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

The ng-model directive can also:

 Provide type validation for application data (number, email, required).


 Provide status for application data (invalid, dirty, touched, error).
 Provide CSS classes for HTML elements.
 Bind HTML elements to HTML forms.

Read more about the ng-model directive in the next chapter.

Create New Directives


In addition to all the built-in AngularJS directives, you can create your own directives.

New directives are created by using the .directive function.

To invoke the new directive, make an HTML element with the same tag name as the new directive.

When naming a directive, you must use a camel case name, w3TestDirective, but when invoking it, you must use -
separated name, w3-test-directive:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="" ng-init="names=[

{name:'Jani',country:'Norway'},

{name:'Hege',country:'Sweden'},

{name:'Kai',country:'Denmark'}]">

<p>Looping with objects:</p>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 19 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<ul>

<li ng-repeat="x in names">

{{ x.name + ', ' + x.country }}</li>

</ul>

</div>

</body>

</html>

You can invoke a directive by using:

 Element name
 Attribute
 Class
 Comment

The examples below will all produce the same result:

Element name

<w3-test-directive></w3-test-directive>

Attribute

<div w3-test-directive></div>

Class

<div class="w3-test-directive"></div>

Comment

<!-- directive: w3-test-directive -->

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 20 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

Restrictions
You can restrict your directives to only be invoked by some of the methods.

Example
By adding a restrict property with the value "A", the directive can only be invoked by attributes:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="myApp">

<w3-test-directive></w3-test-directive>

<div w3-test-directive></div>

<script>

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

app.directive("w3TestDirective", function() {

return {

restrict : "A",

template : "<h1>Made by a directive!</h1>"

};

});

</script>

<p><strong>Note:</strong> By setting the <strong>restrict</strong> property to "A", only the HTML element
with the "w3-test-directive" attribute has invoked the directive.</p>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 21 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</body>

</html>

The legal restrict values are:

 E for Element name


 A for Attribute
 C for Class
 M for Comment

By default the value is EA, meaning that both Element names and attribute names can invoke the directive.

AngularJS ng-model Directive


The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

In angularjs ng-model directive is used to get value of input controls like textbox, label, etc and bind that value to application
data. Generally, the syntax of ng-model directive in angularjs like as shown below.

Syntax of ng-model Directive in AngularJS


Following is the syntax of using ng-model directive in angularjs applications.

<div ng-app="">
<input type="text" id="txtname" ng-model="name" />
<p>Your Username: {{name}}</p>
</div>

The ng-model Directive


With the ng-model directive you can bind the value of an input field to a variable created in AngularJS.

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 22 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<body>

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

Name: <input ng-model="name">

</div>

<script>

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

app.controller('myCtrl', function($scope) {

$scope.name = "John Doe";

});

</script>

<p>Use the ng-model directive to bind the value of the input field to a property made in the controller.</p>

</body>

</html>

Two-Way Binding
The binding goes both ways. If the user changes the value inside the input field, the AngularJS property will also
change its value:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 23 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<body>

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

Name: <input ng-model="name">

<h1>You entered: {{name}}</h1>

</div>

<script>

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

app.controller('myCtrl', function($scope) {

$scope.name = "John Doe";

});

</script>

<p>Change the name inside the input field, and you will see the name in the header changes accordingly.</p>

</body>

</html>

Validate User Input


The ng-model directive can provide type validation for application data (number, e-mail, required):

Example
<!DOCTYPE html>

<html>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 24 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<form ng-app="" name="myForm">

Email:

<input type="email" name="myAddress" ng-model="text">

<span ng-show="myForm.myAddress.$error.email">Not a valid e-mail address</span>

</form>

<p>Enter your e-mail address in the input field. AngularJS will display an errormessage if the address is not an e-
mail.</p>

</body>

</html>

In the example above, the span will be displayed only if the expression in the ng-show attribute returns true.

If the property in the ng-model attribute does not exist, AngularJS will create one for you.

Application Status
The ng-model directive can provide status for application data (valid, dirty, touched, error):

Example

<!DOCTYPE html>

<html>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 25 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<form ng-app="" name="myForm" ng-init="myText = '[email protected]'">

Email:

<input type="email" name="myAddress" ng-model="myText" required>

<p>Edit the e-mail address, and try to change the status.</p>

<h1>Status</h1>

<p>Valid: {{myForm.myAddress.$valid}} (if true, the value meets all criteria).</p>

<p>Dirty: {{myForm.myAddress.$dirty}} (if true, the value has been changed).</p>

<p>Touched: {{myForm.myAddress.$touched}} (if true, the field has been in focus).</p>

</form>

</body>

</html>

OUTPUT:

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 26 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

CSS Classes
The ng-model directive provides CSS classes for HTML elements, depending on their status:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<style>

input.ng-invalid {

background-color: lightblue;

</style>

<body>

<form ng-app="" name="myForm">

Enter your name:

<input name="myName" ng-model="myText" required>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 27 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</form>

<p>Edit the text field and it will get/lose classes according to the status.</p>

<p><b>Note:</b> A text field with the "required" attribute is not valid when it is empty.</p>

</body>

</html>

OUTPUT:

The ng-model directive adds/removes the following classes, according to the status of the form field:

 ng-empty
 ng-not-empty
 ng-touched
 ng-untouched
 ng-valid
 ng-invalid
 ng-dirty
 ng-pending
 ng-pristine

AngularJS Data Binding


Data binding in AngularJS is the synchronization between the model and the view.

In angularjs, the ng-bind directive is used to bind/replace the text content of any particular HTML element with the value of a
given expression that is used against the ng-bind in angularjs application. The value of the specified HTML element will be
updated whenever the value of the given expression will change in angularjs ng-bind directive.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 28 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

AngularJS ng-bind Directive Syntax


Following is the syntax of using ng-bind directive in angularjs applications.

<div ng-app="">
Enter Name to Display:
<input type="text" ng-model="name">
you entered : <span ng-bind="name"></span>
</div>

Data Model
AngularJS applications usually have a data model. The data model is a collection of data available for the
application.

Example
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstname = "John";
$scope.lastname = "Doe";
});

HTML View
The HTML container where the AngularJS application is displayed, is called the view.

The view has access to the model, and there are several ways of displaying model data in the view.

You can use the ng-bind directive, which will bind the innerHTML of the element to the specified model property:

Example
<p ng-bind="firstname"></p>

You can also use double braces {{ }} to display content from the model:

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 29 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

Example
<p>First name: {{firstname}}</p>

AngularJS Controllers

AngularJS controllers control the data of AngularJS applications.

AngularJS controllers are regular JavaScript Objects.

AngularJS Controllers
The controllers in angularjs is used to control data of angularjs applications. The AngularJs controller is an object that is
created by using JavaScript constructor.

The angularjs controller will handle DOM elements with the help of using ng-controller directive.

Syntax of AngularJS Controller


Following is the way of defining controller and accessing with ng-controller directive in angularjs application.

<script type="text/javascript">
var app = angular.module('angularctrlapp', []);
app.controller('angularctrl', function ($scope) {
$scope.msg = 'Welcome to Tutlane.com';
});
</script>

<div ng-app="angularctrlapp" ng-controller="angularctrl">


{{msg}}
</div>

Explanation of AngularJS Controller Syntax


If you observe above syntax we mentioned ng-app it will act as a starting point of angularjs application and angularjs
functionality will be applicable to the elements inside of div. For more info on ng-app check this angularjs ng-app directive.

Generally we will define controller with angularjs module. If you observe above code we defined angularjs module with
variable “app” and adding controller to that module. To access controller properties in angularjs application we will use ng-
controller directive. If you observe we are accessing controller properties by defining ng-controller="angularctrl".
Here angularctrl is a JavaScript function.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 30 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

In angularjs controllers are invoked by using angularjs $scope object because of that we initialized $scope object in
controller function.

What is $scope? The $scope in angularjs is an application object. It holds all the variables and functions of controller and
allow us to access those variables and function in application view.

If you observe above syntax we are able to access “msg” variable in view because of defining variable “msg”
with $scope object. We will learn more about $scope in next chapters.

Now we will see how to use controllers in angularjs application with full example.

Example of AngularJS Controller


Following is the example of using controller in angularjs application.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
AngularJs Controllers Example
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('angularctrlapp', []);
app.controller('angularctrl', function ($scope) {
$scope.fname = "Welcome to";
$scope.lname = "Tutlane";
});
</script>
</head>
<body>
<div ng-app="angularctrlapp" ng-controller="angularctrl">
First Name: {{fname}}<br />
Last Name: {{lname}}<br />
Full Name: <b>{{fname +" "+ lname}}</b>
</div>
</body>
</html>
If we run above example we will get $scope variables fname and lname values from controller and we can show it in
application.

Output of AngularJS Controllers Example


Following is the result of using controllers in angularjs applications.

First Name: welcome to

Last Name: Tutlane

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 31 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

Full Name: welcome to Tutlane


In controller we can define functions / methods and we can access that functions in our angularjs applications.

AngularJS Controllers
AngularJS applications are controlled by controllers.

The ng-controller directive defines the application controller.

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

AngularJS Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="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>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 32 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

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

app.controller('myCtrl', function($scope) {

$scope.firstName = "John";

$scope.lastName = "Doe";

});

</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).

Controller Methods
The example above demonstrated a controller object with two properties: lastName and firstName.

A controller can also have methods (variables as functions):

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 33 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

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

First Name: <input type="text" ng-model="firstName"><br>


Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>

Controllers In External Files


In larger applications, it is common to store controllers in external files.

Just copy the code between the <script> tags into an external file named personController.js:

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

First Name: <input type="text" ng-model="firstName"><br>


Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}

</div>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 34 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<script src="personController.js"></script>

Another Example
For the next example we will create a new controller file:

angular.module('myApp', []).controller('namesCtrl', function($scope) {


$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}
];
});

Save the file as namesController.js:

And then use the controller file in an application:

AngularJS Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<ul>

<li ng-repeat="x in names">

{{ x.name + ', ' + x.country }}

</li>

</ul>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 35 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</div>

<script src="namesController.js"></script>

</body>

</html>

AngularJS Scope
The scope is the binding part between the HTML (view) and the JavaScript (controller).

The scope is an object with the available properties and methods.

The scope is available for both the view and the controller.

AngularJS Scopes
In angularjs, we have a two main parts one is view (HTML) and another one is controllers. We know that 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 but how they (view and controller) communicate to each other? Well, here scope came
into a picture in angularjs.

Generally, when we create controller in angularjs we will send $scope object 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.

So, scope is an object which holds variables and functions in controller and allow us to access that data between Views and
Controller.

In simple words, we can say that scope works as a glue between view (html) and controller and facilitate them to
communicate with each other. The scope values will available in both view and controller.

Syntax of using AngularJS Scope


Following is the syntax of using scope in angularjs applications.

<script type="text/javascript">
var app = angular.module('angularscopeapp', []);
app.controller('angularctrl', function ($scope) {
$scope.fname = "Welcome to";

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 36 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

$scope.lname = "Tutlane";
});
</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


If you observe above syntax while 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.

We will see how to use $scope in angularjs application with complete example

AngularJS Scopes Example


Following is the example of using scope in angularjs application.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
AngularJs Scope Object Example
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('angularscopeapp', []);
app.controller('angularctrl', function ($scope) {
$scope.fname = "Welcome to";
$scope.lname = "Tutlane";
$scope.getname = function () {
return $scope.fname +" "+ $scope.lname;
};
});
</script>
</head>
<body ng-app="angularscopeapp">
<div ng-controller="angularctrl">
First Name: {{fname}}<br />
Last Name: {{lname}}<br />
Full Name: <b>{{getname()}}</b>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 37 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</div>
</body>
</html>
In above example if you observe we defined variables and functions with $scope object and accessing those values in html.
Now we will run and see the output of above angularjs application.

Output of AngularJS Scopes Example


Following is the result of using scope in angularjs applications.

First Name: Welcome to

Last Name: Tutlane

Full Name: Welcome to Tutlane

How to Use the Scope?


When you make a controller in AngularJS, you pass the $scope object as an argument:

Example
Properties made in the controller, can be referred to in the view:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<h1>{{carname}}</h1>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 38 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</div>

<script>

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

app.controller('myCtrl', function($scope) {

$scope.carname = "Volvo";

});

</script>

<p>The property "carname" was made in the controller, and can be referred to in the view by using the {{ }}
brackets.</p>

</body>

</html>

When adding properties to the $scope object in the controller, the view (HTML) gets access to these properties.

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

Understanding the Scope


If we consider an AngularJS application to consist of:

 View, which is the HTML.


 Model, which is the data available for the current view.
 Controller, which is the JavaScript function that makes/changes/removes/controls the data.

Then the scope is the Model.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 39 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

The scope is a JavaScript object with properties and methods, which are available for both the view and the
controller.

Example
If you make changes in the view, the model and the controller will be updated:

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

<input ng-model="name">

<h1>My name is {{name}}</h1>

</div>

<script>

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

app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});

</script>

Know Your Scope


It is important to know which scope you are dealing with, at any time.

In the two examples above there is only one scope, so knowing your scope is not an issue, but for larger
applications there can be sections in the HTML DOM which can only access certain scopes.

Example
When dealing with the ng-repeat directive, each repetition has access to the current repetition object:

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

<ul>
<li ng-repeat="x in names">{{x}}</li>
</ul>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 40 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</div>

<script>

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

app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
});

</script>

Each <li> element has access to the current repetition object, in this case a string, which is referred to by using x.

Root Scope
All applications have a $rootScope which is the scope created on the HTML element that contains the ng-
app directive.

The rootScope is available in the entire application.

If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the
current scope.

Example
A variable named "color" exists in both the controller's scope and in the rootScope:

<body ng-app="myApp">

<p>The rootScope's favorite color:</p>


<h1>{{color}}</h1>

<div ng-controller="myCtrl">
<p>The scope of the controller's favorite color:</p>
<h1>{{color}}</h1>
</div>

<p>The rootScope's favorite color is still:</p>


<h1>{{color}}</h1>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 41 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<script>

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


app.run(function($rootScope) {
$rootScope.color = 'blue';
});
app.controller('myCtrl', function($scope) {
$scope.color = "red";
});

</script>
</body>

AngularJS Filters
Filters can be added in AngularJS to format data.

AngularJS Filters
In angularjs, filters are used to change the appearance of an expressions by formatting while displaying it to users.

In angularjs, filter is a concept that work with a separation of record based on column and we can apply filters to expressions
and directives by using the pipe (|) character.

Sytax of using Filters in AngularJS


Following is the syntax of using filters with expression in angularjs.

{{expression | filter}}

If you observe above syntax, we defined an expression with pipe (I) character, whenever this compiled and executed it will
change the appearance of expression.

Suppose, if we define expression like {{100 | currency}} it will formats the number 100 as currency using currency filter. If
we execute this expression, we will get the result like $100.00.

In angularjs, we can apply filters to result of another filter. Generally, we call it as chaining and the syntax will be like as
shown below.

{{expression | filter1 | filter2 | …..}}

In angularjs we can format expressions by applying filters with arguments that syntax will be like as shown below.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 42 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

{{expression | filter:argument1:argument2:……}}

Suppose, if we define expression like {{1000 | number:3}} it will format the number 1000 with 3 decimal points using
number expression. If we execute this expression we will get result like 1,000.000.

AngularJS Filters Example


Following is the example of using filters with expressions in angularjs application.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
AngularJs Filters example
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="">
Enter Number1:<input type="text" ng-model="number1" /><br /><br />
Enter Number2:<input type="text" ng-model="number2" />
<p>Result of Multiplication: {{number1 * number2 | currency}}</p>
</div>
</body>
</html>

If we run above example we will get result like as shown below

Output of AngularJS Filters Example


Following is the output of using filters with expressions in angularjs.

AngularJS Filter Types


In angularjs we have different type of filters available those are

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 43 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

File Type Description

lowercase This filter is used to converts string to lowercase

uppercase This filter is used to converts string to uppercase

orderby This filter is used to order an array by using specified expression

currency This filter is used to convert number to currency

filter This filter is used to get subset of items from array and returned as array

date This filter is used to convert date to string based on defined format

json It allows you to convert javascript objects into json string

limitTo This filter is used to create new array or string with specified number of elements

number It formats number as text

AngularJS Filters
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.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 44 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

 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 format strings to upper case:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

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

</div>

<script>

angular.module('myApp', []).controller('personCtrl', function($scope) {

$scope.firstName = "John",

$scope.lastName = "Doe"

});

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 45 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</script>

</body>

</html>

The lowercase filter format strings to lower case:

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 46 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

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

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

</div>

<script>
angular.module('myApp', []).controller('personCtrl', function($scope) {
$scope.firstName = "John",
$scope.lastName = "Doe"
});
</script>

</body>
</html>

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:

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 47 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

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

<p>Looping with objects:</p>


<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 48 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

];
});
</script>

</body>
</html>

The currency Filter


The currency filter formats a number as currency:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<h1>Price: {{ price | currency }}</h1>

</div>

<script>

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

app.controller('costCtrl', function($scope) {

$scope.price = 58;

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 49 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

});

</script>

<p>The currency filter formats a number to a currency format.</p>

</body>

</html>

Read more about the currency filter in our AngularJS currency Filter Reference

The filter Filter


The filter filter selects a subset of an array.

The filter filter can only be used on arrays, and it returns an array containing only the matching items.

Example
Return the names that contains the letter "i":

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

<ul>
<li ng-repeat="x in names | filter : 'i'">
{{ x }}
</li>
</ul>

</div>

Read more about the filter filter in our AngularJS filter Filter Reference

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 50 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

Filter an Array Based on User Input


By setting the ng-model directive on an input field, we can use the value of the input field as an expression in a
filter.

Type a letter in the input field, and the list will shrink/grow depending on the match:

 Jani
 Carl
 Margareth
 Hege
 Joe
 Gustav
 Birgit
 Mary
 Kai

Example
<div ng-app="myApp" ng-controller="namesCtrl">

<p><input type="text" ng-model="test"></p>

<ul>
<li ng-repeat="x in names | filter : test">
{{ x }}
</li>
</ul>

</div>

Sort an Array Based on User Input


Click the table headers to change the sort order::

Name Country

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 51 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

Jani Norway

Carl Sweden

Margareth England

Hege Norway

Joe Denmark

Gustav Sweden

Birgit Denmark

Mary England

Kai Norway

By adding the ng-click directive on the table headers, we can run a function that changes the sorting order of the
array:

Example
<div ng-app="myApp" ng-controller="namesCtrl">

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 52 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<table border="1" width="100%">


<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
$scope.orderByMe = function(x) {
$scope.myOrderBy = x;
}
});
</script>

Custom Filters
You can make your own filters by registering a new filter factory function with your module:

Example
Make a custom filter called "myFormat":

<ul ng-app="myApp" ng-controller="namesCtrl">


<li ng-repeat="x in names">

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 53 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

{{x | myFormat}}
</li>
</ul>

<script>

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


app.filter('myFormat', function() {
return function(x) {
var i, c, txt = "";
for (i = 0; i < x.length; i++) {
c = x[i];
if (i % 2 == 0) {
c = c.toUpperCase();
}
txt += c;
}
return txt;
};
});
app.controller('namesCtrl', function($scope) {
$scope.names = ['Jani', 'Carl', 'Margareth', 'Hege', 'Joe', 'Gustav', 'Birgit', 'Mary', 'Kai'];
});

</script>

The myFormat filter will format every other character to uppercase.

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

What is a Service?
In AngularJS, a service is a function, or object, that is available for, and limited to, your AngularJS application.

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

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 54 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

What is Service in AngularJs?


In angularjs, service is the function which is used to handle the server communication over the browser with help
of XMLHttpRequest object and $http.

In angularjs, we have a 30 built in services like $http, $location, $timeout, $interval, etc… and these are used to share the
data and its behaviours in the controller, directive, filters and other services over the apps. In angularjs we can create our own
custom services also based on our requirement.

In angularjs, service will create singleton instance over the angular apps and call the services using the service name in the
controller.

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

Example
Use the $location service in a controller:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<p>The url of this page is:</p>

<h3>{{myUrl}}</h3>

</div>

<p>This example uses the built-in $location service to get the absolute url of the page.</p>

<script>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 55 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

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

app.controller('myCtrl', function($scope, $location) {

$scope.myUrl = $location.absUrl();

});

</script>

</body>

</html>

OUTPUT:

Note that the $location service is passed in to the controller as an argument. In order to use the service in the
controller, it must be defined as a dependency.

Why use Services?


For many services, like the $location service, it seems like you could use objects that are already in the DOM, like
the window.location object, and you could, but it would have some limitations, at least for your AngularJS
application.

AngularJS constantly supervises your application, and for it to handle changes and events properly, AngularJS
prefers that you use the $location service instead of the window.location object.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 56 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

The $http Service


The $http service is one of the most common used services in AngularJS applications. The service makes a request
to the server, and lets your application handle the response.

Example
Use the $http service to request data from the server:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<p>Today's welcome message is:</p>

<h1>{{myWelcome}}</h1>

</div>

<p>The $http service requests a page on the server, and the response is set as the value of the "myWelcome"
variable.</p>

<script>

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

app.controller('myCtrl', function($scope, $http) {

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 57 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

$http.get("welcome.htm").then(function (response) {

$scope.myWelcome = response.data;

});

});

</script>

</body>

</html>

This example demonstrates a very simple use of the $http service. Learn more about the $http service in
the AngularJS Http Tutorial.

The $timeout Service


The $timeout service is AngularJS' version of the window.setTimeout function.

Example
Display a new message after two seconds:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<p>This header will change after two seconds:</p>

<h1>{{myHeader}}</h1>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 58 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</div>

<p>The $timeout service runs a function after a specified number of milliseconds.</p>

<script>

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

app.controller('myCtrl', function($scope, $timeout) {

$scope.myHeader = "Hello World!";

$timeout(function () {

$scope.myHeader = "How are you today?";

}, 2000);

});

</script>

</body>

</html>

The $interval Service


The $interval service is AngularJS' version of the window.setInterval function.

Example
Display the time every second:

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


app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 59 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

$scope.theTime = new Date().toLocaleTimeString();


}, 1000);
});

Create Your Own Service


To create your own service, connect your service to the module:

Create a service named hexafy:

app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});

To use your custom made service, add it as a dependency when defining the controller:

Example
Use the custom made service named hexafy to convert a number into a hexadecimal number:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<p>The hexadecimal value of 255 is:</p>

<h1>{{hex}}</h1>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 60 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</div>

<p>A custom service with a method that converts a given number into a hexadecimal number.</p>

<script>

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

app.service('hexafy', function() {

this.myFunc = function (x) {

return x.toString(16);

});

app.controller('myCtrl', function($scope, hexafy) {

$scope.hex = hexafy.myFunc(255);

});

</script>

</body>

</html>

Use a Custom Service Inside a Filter


Once you have created a service, and connected it to your application, you can use the service in any controller,
directive, filter, or even inside other services.

To use the service inside a filter, add it as a dependency when defining the filter:

The service hexafy used in the filter myFormat:

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 61 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

app.filter('myFormat',['hexafy', function(hexafy) {
return function(x) {
return hexafy.myFunc(x);
};
}]);

You can use the filter when displaying values from an object, or an array:

<ul>
<li ng-repeat="x in counts">{{x | myFormat}}</li>
</ul>

AngularJS Tables
The ng-repeat directive is perfect for displaying tables.

AngularJS Tables
In angularjs if we want to show data in table formats it’s better to use ng-repeat directive because the table will contain data
in repeated format.

In angularjs the ng-repeat directive will loop through the array data objects in the DOM elements and help us to show data in
tables easily.

Syntax of AngularJS Tables


Following is the syntax of using ng-repeat directive in angularjs to display data in tables

<tr ng-repeat="user in users">


<td>{{user.name}}</td>
<td>{{user.age}}</td>
<td>{{user.location}}</td>
</tr>

Displaying Data in a Table


Displaying tables with angular is very simple:

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 62 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

AngularJS Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<table>

<tr ng-repeat="x in names">

<td>{{ x.Name }}</td>

<td>{{ x.Country }}</td>

</tr>

</table>

</div>

<script>

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

app.controller('customersCtrl', function($scope, $http) {

$http.get("customers.php")

.then(function (response) {$scope.names = response.data.records;});

});

</script>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 63 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</body>

</html>

OUTPUT:

Displaying with CSS Style


To make it nice, add some CSS to the page:

CSS Style
<!DOCTYPE html>

<html>

<style>

table, th , td {

border: 1px solid grey;

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 64 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

border-collapse: collapse;

padding: 5px;

table tr:nth-child(odd) {

background-color: #f1f1f1;

table tr:nth-child(even) {

background-color: #ffffff;

</style>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<table>

<tr ng-repeat="x in names">

<td>{{ x.Name }}</td>

<td>{{ x.Country }}</td>

</tr>

</table>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 65 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</div>

<script>

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

app.controller('customersCtrl', function($scope, $http) {

$http.get("customers.php")

.then(function (response) {$scope.names = response.data.records;});

});

</script>

</body>

</html>

OUTPUT:

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 66 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

Display with orderBy Filter


To sort the table, add an orderBy filter:

AngularJS Example
<!DOCTYPE html>

<html>

<style>

table, th , td {

border: 1px solid grey;

border-collapse: collapse;

padding: 5px;

table tr:nth-child(odd) {

background-color: #f1f1f1;

table tr:nth-child(even) {

background-color: #ffffff;

</style>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 67 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

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

<table>

<tr ng-repeat="x in names | orderBy : 'Country'">

<td>{{ x.Name }}</td>

<td>{{ x.Country }}</td>

</tr>

</table>

</div>

<script>

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

app.controller('customersCtrl', function($scope, $http) {

$http.get("customers.php")

.then(function (response) {$scope.names = response.data.records;});

});

</script>

</body>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 68 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</html>

Display with uppercase Filter


To display uppercase, add an uppercase filter:

AngularJS Example
<!DOCTYPE html>

<html>

<style>

table, th , td {

border: 1px solid grey;

border-collapse: collapse;

padding: 5px;

table tr:nth-child(odd) {

background-color: #f1f1f1;

table tr:nth-child(even) {

background-color: #ffffff;

</style>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 69 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<body>

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

<table>

<tr ng-repeat="x in names">

<td>{{ x.Name }}</td>

<td>{{ x.Country | uppercase }}</td>

</tr>

</table>

</div>

<script>

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

app.controller('customersCtrl', function($scope, $http) {

$http.get("customers.php")

.then(function (response) {$scope.names = response.data.records;});

});

</script>

</body>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 70 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</html>

Display the Table Index ($index)


To display the table index, add a <td> with $index:

AngularJS Example
<!DOCTYPE html>

<html>

<style>

table, th , td {

border: 1px solid grey;

border-collapse: collapse;

padding: 5px;

table tr:nth-child(odd) {

background-color: #f1f1f1;

table tr:nth-child(even) {

background-color: #ffffff;

</style>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 71 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<body>

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

<table>

<tr ng-repeat="x in names">

<td>{{ $index + 1 }}</td>

<td>{{ x.Name }}</td>

<td>{{ x.Country }}</td>

</tr>

</table>

</div>

<script>

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

app.controller('customersCtrl', function($scope, $http) {

$http.get("customers.php")

.then(function (response) {$scope.names = response.data.records;});

});

</script>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 72 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</body>

</html>

Using $even and $odd


AngularJS Example
<!DOCTYPE html>

<html>

<style>

table, td {

border: 1px solid grey;

border-collapse: collapse;

padding: 5px;

</style>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<table>

<tr ng-repeat="x in names">

<td ng-if="$odd" style="background-color:#f1f1f1">

{{ x.Name }}</td>

<td ng-if="$even">

{{ x.Name }}</td>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 73 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<td ng-if="$odd" style="background-color:#f1f1f1">

{{ x.Country }}</td>

<td ng-if="$even">

{{ x.Country }}</td>

</tr>

</table>

</div>

<script>

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

app.controller('customersCtrl', function($scope, $http) {

$http.get("customers.php")

.then(function (response) {$scope.names = response.data.records;});

});

</script>

</body>

</html>

AngularJS Select Boxes


AngularJS lets you create dropdown lists based on items in an array, or an object.

In angularjs, by using select boxes we can achieve dropdown functionality and we can bind data to dropdown list / select box
using ng-repeat or ng-options directives.

By using ng-model directive in angularjs we can get selected value of select box / dropdown list and we can set the value of
dropdown list and also it will acts as data provider between scope and select box / dropdown list.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 74 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

Creating a Select Box Using ng-options


If you want to create a dropdown list, based on an object or an array in AngularJS, you should use the ng-
options directive:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<select ng-model="selectedName" ng-options="x for x in names">

</select>

</div>

<script>

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

app.controller('myCtrl', function($scope) {

$scope.names = ["Emil", "Tobias", "Linus"];

});

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 75 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</script>

<p>This example shows how to fill a dropdown list using the ng-options directive.</p>

</body>

</html>

ng-options vs ng-repeat
You can also use the ng-repeat directive to make the same dropdown list:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<select>

<option ng-repeat="x in names">{{x}}</option>

</select>

</div>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 76 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<script>

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

app.controller('myCtrl', function($scope) {

$scope.names = ["Emil", "Tobias", "Linus"];

});

</script>

<p>This example shows how to fill a dropdown list using the ng-repeat directive.</p>

</body>

</html>

Because the ng-repeat directive repeats a block of HTML code for each item in an array, it can be used to create
options in a dropdown list, but the ng-options directive was made especially for filling a dropdown list with
options.

What Do I Use?
You can use both the ng-repeat directive and the ng-options directive:

Assume you have an array of objects:

$scope.cars = [
{model : "Ford Mustang", color : "red"},
{model : "Fiat 500", color : "white"},
{model : "Volvo XC90", color : "black"}
];

Example
Using ng-repeat:

<!DOCTYPE html>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 77 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<p>Select a car:</p>

<select ng-model="selectedCar">

<option ng-repeat="x in cars" value="{{x.model}}">{{x.model}}</option>

</select>

<h1>You selected: {{selectedCar}}</h1>

</div>

<script>

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

app.controller('myCtrl', function($scope) {

$scope.cars = [

{model : "Ford Mustang", color : "red"},

{model : "Fiat 500", color : "white"},

{model : "Volvo XC90", color : "black"}

];

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 78 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

});

</script>

<p>When you use the ng-repeat directive to create dropdown lists, the selected value must be a string.</p>

<p>In this example you will have to choose between the color or the model to be your selected value.</p>

</body>

</html>

When using the value as an object, use ng-value insead of value:

Example
Using ng-repeat as an object:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<p>Select a car:</p>

<select ng-model="selectedCar">

<option ng-repeat="x in cars" ng-value="{{x}}">{{x.model}}</option>

</select>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 79 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<h1>You selected a {{selectedCar.color}} {{selectedCar.model}}</h1>

</div>

<script>

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

app.controller('myCtrl', function($scope) {

$scope.cars = [

{model : "Ford Mustang", color : "red"},

{model : "Fiat 500", color : "white"},

{model : "Volvo XC90", color : "black"}

];

});

</script>

<p>When you use the ng-repeat directive to create dropdown lists, the selected value must be a string.</p>

<p>In this example you will have to choose between the color or the model to be your selected value.</p>

</body>

</html>

Example
Using ng-options:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 80 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<body>

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

<p>Select a car:</p>

<select ng-model="selectedCar" ng-options="x.model for x in cars">

</select>

<h1>You selected: {{selectedCar.model}}</h1>

<p>Its color is: {{selectedCar.color}}</p>

</div>

<script>

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

app.controller('myCtrl', function($scope) {

$scope.cars = [

{model : "Ford Mustang", color : "red"},

{model : "Fiat 500", color : "white"},

{model : "Volvo XC90", color : "black"}

];

});

</script>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 81 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<p>When you use the ng-options directive to create dropdown lists, the selected value can be an object.</p>

<p>In this example you can display both the model and the color of the selected element.</p>

</body>

</html>When the selected value is an object, it can hold more information, and your application can be more
flexible.

We will use the ng-options directive in this tutorial.

The Data Source as an Object


In the previous examples the data source was an array, but we can also use an object.

Assume you have an object with key-value pairs:

$scope.cars = {
car01 : "Ford",
car02 : "Fiat",
car03 : "Volvo"
};

The expression in the ng-options attribute is a bit different for objects:

Example
Using an object as the data source, x represents the key, and y represents the value:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 82 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<p>Select a car:</p>

<select ng-model="selectedCar" ng-options="x for (x, y) in cars">

</select>

<h1>You selected: {{selectedCar}}</h1>

</div>

<p>This example demonstrates the use of an object as the data source when creating a dropdown list.</p>

<script>

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

app.controller('myCtrl', function($scope) {

$scope.cars = {

car01 : "Ford",

car02 : "Fiat",

car03 : "Volvo"

});

</script>

</body>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 83 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</html>

The selected value will always be the value in a key-value pair.

The value in a key-value pair can also be an object:

Example
The selected value will still be the value in a key-value pair, only this time it is an object:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<p>Select a car:</p>

<select ng-model="selectedCar" ng-options="x for (x, y) in cars">

</select>

<h1>You selected: {{selectedCar.brand}}</h1>

<h2>Model: {{selectedCar.model}}</h2>

<h3>Color: {{selectedCar.color}}</h3>

<p>Note that the selected value represents an object.</p>

</div>

<script>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 84 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

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

app.controller('myCtrl', function($scope) {

$scope.cars = {

car01 : {brand : "Ford", model : "Mustang", color : "red"},

car02 : {brand : "Fiat", model : "500", color : "white"},

car03 : {brand : "Volvo", model : "XC90", color : "black"}

});

</script>

</body>

</html>

The options in the dropdown list does not have to be the key in a key-value pair, it can also be the value, or a
property of the value object:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<p>Select a car:</p>

<select ng-model="selectedCar" ng-options="y.brand for (x, y) in cars">

</select>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 85 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<h1>You selected: {{selectedCar.brand}}</h1>

<h2>Model: {{selectedCar.model}}</h2>

<h3>Color: {{selectedCar.color}}</h3>

<p>The visible text inside the dropdown list can also be a property of the value object.</p>

</div>

<script>

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

app.controller('myCtrl', function($scope) {

$scope.cars = {

car01 : {brand : "Ford", model : "Mustang", color : "red"},

car02 : {brand : "Fiat", model : "500", color : "white"},

car03 : {brand : "Volvo", model : "XC90", color : "black"}

});

</script>

</body>

</html>

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

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 86 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

Controls (input, select, textarea) are ways for a user to enter data. A Form is a collection of controls for the purpose of
grouping related controls together.
Form and controls provide validation services, so that the user can be notified of invalid input before submitting a form. This
provides a better user experience than server-side validation alone because the user gets instant feedback on how to correct
the error. Keep in mind that while client-side validation plays an important role in providing good user experience, it can
easily be circumvented and thus can not be trusted. Server-side validation is still necessary for a secure application.

Input Controls
Input controls are the HTML input elements:

 input elements
 select elements
 button elements
 textarea elements

Data-Binding
Input controls provides data-binding by using the ng-model directive.

<input type="text" ng-model="firstname">

The application does now have a property named firstname.

The ng-model directive binds the input controller to the rest of your application.

The property firstname, can be referred to in a controller:

Example
<!DOCTYPE html>

<html lang="en">

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 87 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<form>

First Name: <input type="text" ng-model="firstname">

</form>

</div>

<script>

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

app.controller('formCtrl', function($scope) {

$scope.firstname = "John";

});

</script>

</body>

</html>

It can also be referred to elsewhere in the application:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="">

<form>

First Name: <input type="text" ng-model="firstname">

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 88 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</form>

<h1>You entered: {{firstname}}</h1>

</div>

<p>Change the name inside the input field, and you will see the name in the header changes accordingly.</p>

</body>

</html>

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
Show the header if the checkbox is checked:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="">

<form>

Check to show a header:

<input type="checkbox" ng-model="myVar">

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 89 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</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>

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
Display some text, based on the value of the selected radio button:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="">

<form>

Pick a topic:

<input type="radio" ng-model="myVar" value="dogs">Dogs

<input type="radio" ng-model="myVar" value="tuts">Tutorials

<input type="radio" ng-model="myVar" value="cars">Cars

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 90 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</form>

<div ng-switch="myVar">

<div ng-switch-when="dogs">

<h1>Dogs</h1>

<p>Welcome to a world of dogs.</p>

</div>

<div ng-switch-when="tuts">

<h1>Tutorials</h1>

<p>Learn from examples.</p>

</div>

<div ng-switch-when="cars">

<h1>Cars</h1>

<p>Read about cars.</p>

</div>

</div>

<p>The ng-switch directive hides and shows HTML sections depending on the value of the radio buttons.</p>

</body>

</html>

The value of myVar will be either dogs, tuts, or cars.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 91 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

Selectbox
Bind select boxes to your application with the ng-model directive.

The property defined in the ng-model attribute will have the value of the selected option in the selectbox.

Example
Display some text, based on the value of the selected option:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="">

<form>

Select a topic:

<select ng-model="myVar">

<option value="">

<option value="dogs">Dogs

<option value="tuts">Tutorials

<option value="cars">Cars

</select>

</form>

<div ng-switch="myVar">

<div ng-switch-when="dogs">

<h1>Dogs</h1>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 92 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<p>Welcome to a world of dogs.</p>

</div>

<div ng-switch-when="tuts">

<h1>Tutorials</h1>

<p>Learn from examples.</p>

</div>

<div ng-switch-when="cars">

<h1>Cars</h1>

<p>Read about cars.</p>

</div>

</div>

<p>The ng-switch directive hides and shows HTML sections depending on the value of the dropdown list.</p>

</body>

</html>The value of myVar will be either dogs, tuts, or cars.

An AngularJS Form Example


First Name:

Last Name:

RESET

form = {"firstName":"John","lastName":"Doe"}

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 93 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

master = {"firstName":"John","lastName":"Doe"}

Application Code
<!DOCTYPE html>

<html lang="en">

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<form novalidate>

First Name:<br>

<input type="text" ng-model="user.firstName"><br>

Last Name:<br>

<input type="text" ng-model="user.lastName">

<br><br>

<button ng-click="reset()">RESET</button>

</form>

<p>form = {{user}}</p>

<p>master = {{master}}</p>

</div>

<script>

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

app.controller('formCtrl', function($scope) {

$scope.master = {firstName:"John", lastName:"Doe"};

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 94 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

$scope.reset = function() {

$scope.user = angular.copy($scope.master);

};

$scope.reset();

});

</script>

</body>

</html>

The novalidate attribute is new in HTML5. It disables any default browser validation.

Example Explained
The ng-app directive defines the AngularJS application.

The ng-controller directive defines the application controller.

The ng-model directive binds two input elements to the user object in the model.

The formCtrl controller sets initial values to the master object, and defines the reset() method.

The reset() method sets the user object equal to the master object.

The ng-click directive invokes the reset() method, only if the button is clicked.

The novalidate attribute is not needed for this application, but normally you will use it in AngularJS forms, to
override standard HTML5 validation.

AngularJS Events
AngularJS has its own HTML events directives.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 95 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

AngularJS Events
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

The event directives allows us to run AngularJS functions at certain user events.

An AngularJS event will not overwrite an HTML event, both events will be executed.

Mouse Events
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.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 96 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

Example
Increase the count variable when the mouse moves over the H1 element:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<h1 ng-mousemove="count = count + 1">Mouse Over Me!</h1>

<h2>{{ count }}</h2>

</div>

<script>

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

app.controller('myCtrl', function($scope) {

$scope.count = 0;

});

</script>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 97 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</body>

</html>

The ng-click Directive


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

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<button ng-click="count = count + 1">Click Me!</button>

<p>{{ count }}</p>

</div>

<script>

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

app.controller('myCtrl', function($scope) {

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 98 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

$scope.count = 0;

});

</script>

</body>

</html>

You can also refer to a function:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<button ng-click="myFunction()">Click Me!</button>

<p>{{ count }}</p>

</div>

<script>

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

app.controller('myCtrl', function($scope) {

$scope.count = 0;

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 99 | P a g e
WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

$scope.myFunction = function() {

$scope.count++;

});

</script>

</body>

</html>

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:

Click Me

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<button ng-click="myFunc()">Click Me!</button>

<div ng-show="showMe">

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 100 | P a g e


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<h1>Menu:</h1>

<div>Pizza</div>

<div>Pasta</div>

<div>Pesce</div>

</div>

</div>

<script>

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

app.controller('myCtrl', function($scope) {

$scope.showMe = false;

$scope.myFunc = function() {

$scope.showMe = !$scope.showMe;

});

</script>

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

</body>

</html>

The showMe variable starts out as the Boolean value false.

The myFunc function sets the showMe variable to the opposite of what it is, by using the ! (not) operator.

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 101 | P a g e


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

$event Object
You can pass the $event object as an argument when calling the function.

The $event object contains the browser's event object:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

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

<h1 ng-mousemove="myFunc($event)">Mouse Over Me!</h1>

<p>Coordinates: {{x + ', ' + y}}</p>

</div>

<script>

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

app.controller('myCtrl', function($scope) {

$scope.myFunc = function(myE) {

$scope.x = myE.clientX;

$scope.y = myE.clientY;

});

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 102 | P a g e


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</script>

<p>Mouse over the heading to display the value of clientX and clientY from the event object.</p>

</body>

</html>

AngularJS Form Validation


AngularJS can validate input data.

Form Validation
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.

You can use standard HTML5 attributes to validate input, or you can make your own validation functions.

Client-side validation cannot alone secure user input. Server side validation is also necessary.

Required
Use the HTML5 attribute required to specify that the input field must be filled out:

Example
The input field is required:

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 103 | P a g e


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="">

<p>Try writing in the input field:</p>

<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>

<p>The input's valid state is:</p>


<h1>{{myForm.myInput.$valid}}</h1>

</body>
</html>

E-mail
Use the HTML5 type email to specify that the value must be an e-mail:

Example
The input field has to be an e-mail:

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 104 | P a g e


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="">

<p>Try writing an E-mail address in the input field:</p>

<form name="myForm">
<input type="email" name="myInput" ng-model="myInput">
</form>

<p>The input's valid state is:</p>


<h1>{{myForm.myInput.$valid}}</h1>
<p>Note that the state of the input field is "true" before you start writing in it, even if it does not contain an e-mail
address.</p>

</body>
</html>

Form State and Input State


AngularJS is constantly updating the state of both the form and the input fields.

Input fields have the following states:

 $untouched The field has not been touched yet


 $touched The field has been touched
 $pristine The field has not been modified yet
 $dirty The field has been modified
 $invalid The field content is not valid
 $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:

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 105 | P a g e


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

 $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.

You can use these states to show meaningful messages to the user. Example, if a field is required, and the user
leaves it blank, you should give the user a warning:

Example
Show an error message if the field has been touched AND is empty:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="">

<p>Try leaving the first input field blank:</p>

<form name="myForm">

<p>Name:

<input name="myName" ng-model="myName" required>

<span ng-show="myForm.myName.$touched && myForm.myName.$invalid">The name is required.</span>

</p>

<p>Address:

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 106 | P a g e


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<input name="myAddress" ng-model="myAddress" required>

</p>

</form>

<p>We use the ng-show directive to only show the error message if the field has been touched AND is
empty.</p>

</body>

</html>

CSS Classes
AngularJS adds CSS classes to forms and input fields depending on their states.

The following classes are added to, or removed from, input fields:

 ng-untouched The field has not been touched yet


 ng-touched The field has been touched
 ng-pristine The field has not been modified yet
 ng-dirty The field has been modified
 ng-valid The field content is valid
 ng-invalid The field content is not valid
 ng-valid-key One key for each validation. Example: ng-valid-required, useful when there are more than one
thing that must be validated
 ng-invalid-key Example: ng-invalid-required

The following classes are added to, or removed from, forms:

 ng-pristine No fields has not been modified yet


 ng-dirty One or more fields has been modified
 ng-valid The form content is valid
 ng-invalid The form content is not valid
 ng-valid-key One key for each validation. Example: ng-valid-required, useful when there are more than one
thing that must be validated

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 107 | P a g e


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

 ng-invalid-key Example: ng-invalid-required

The classes are removed if the value they represent is false.

Add styles for these classes to give your application a better and more intuitive user interface.

Example
Apply styles, using standard CSS:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<style>

input.ng-invalid {

background-color:pink;

input.ng-valid {

background-color:lightgreen;

</style>

<body ng-app="">

<p>Try writing in the input field:</p>

<form name="myForm">

<input name="myName" ng-model="myName" required>

</form>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 108 | P a g e


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<p>The input field requires content, and will therefore become green when you write in it.</p>

</body>

</html>Forms can also be styled:

Example
Apply styles for unmodified (pristine) forms, and for modified forms:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<style>

form.ng-pristine {

background-color:lightblue;

form.ng-dirty {

background-color:pink;

</style>

<body ng-app="">

<form name="myForm">

<p>Try writing in the input field:</p>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 109 | P a g e


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<input name="myName" ng-model="myName" required>

<p>The form gets a "ng-dirty" class when the form has been modified, and will therefore turn pink.</p>

</form>

</body>

</html>

Custom Validation
To create your own validation function is a bit more tricky; You have to add a new directive to your application,
and deal with the validation inside a function with certain specified arguments.

Example
Create your own directive, containing a custom validation function, and refer to it by using my-directive.

The field will only be valid if the value contains the character "e":

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="myApp">

<p>Try writing in the input field:</p>

<form name="myForm">

<input name="myInput" ng-model="myInput" required my-directive>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 110 | P a g e


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</form>

<p>The input's valid state is:</p>

<h1>{{myForm.myInput.$valid}}</h1>

<script>

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

app.directive('myDirective', function() {

return {

require: 'ngModel',

link: function(scope, element, attr, mCtrl) {

function myValidation(value) {

if (value.indexOf("e") > -1) {

mCtrl.$setValidity('charE', true);

} else {

mCtrl.$setValidity('charE', false);

return value;

mCtrl.$parsers.push(myValidation);

};

});

</script>

<p>The input field must contain the character "e" to be consider valid.</p>

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 111 | P a g e


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

</body>

</html>

Example Explained:
In HTML, the new directive will be referred to by using the attribute my-directive.

In the JavaScript we start by adding a new directive named myDirective.

Remember, when naming a directive, you must use a camel case name, myDirective, but when invoking it, you
must use - separated name, my-directive.

Then, return an object where you specify that we require ngModel, which is the ngModelController.

Make a linking function which takes some arguments, where the fourth argument, mCtrl, is the ngModelController,

Then specify a function, in this case named myValidation, which takes one argument, this argument is the value of
the input element.

Test if the value contains the letter "e", and set the validity of the model controller to either true or false.

At last, mCtrl.$parsers.push(myValidation); will add the myValidation function to an array of other functions, which
will be executed every time the input value changes.

Validation Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<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="myForm.user.$dirty && myForm.user.$invalid">

Prof.Sachin.G.A,Dept.of.MCA, CIT,Mandya 112 | P a g e


WEB TECHNOLOGIES(Moduel 4 & 5)MMC105

<span ng-show="myForm.user.$error.required">Username is required.</span>


</span>
</p>

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

<p>
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
</p>

</form>

<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.user = 'John Doe';
$scope.email = '[email protected]';
});
</script>

</body>
</html>

The HTML form attribute novalidate is used to disable default browser validation.

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.Sachin.G.A,Dept.of.MCA, CIT,Mandya 113 | P a g e

You might also like