0% found this document useful (0 votes)
20 views63 pages

Module 4& 5 Angular Js

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

Module 4& 5 Angular Js

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Web Technologies 22MCA24

MODULE 4 & 5

Syllabus:

Module 4: Introduction to AngularJS, Expressions, Modules, Directives, Model, Data


binding, Controllers, Scopes, Filters

Module5 : Services, Tables, Select box, Forms, Events, Validations

1.1AngularJS Introduction

AngularJS is a popular open-source JavaScript framework developed and maintained by


Google.

It is primarily used for building dynamic, single-page web applications (SPAs).

AngularJS simplifies web development by allowing developers to extend HTML with new
attributes and bind data easily to the HTML elements.

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

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>

Advantages of AngularJS:

1. Simplified Development: AngularJS simplifies tasks such as DOM manipulation, form


validation, and client-side routing.
2. Modularity: It allows you to break down the application into smaller, reusable
components or modules.
3. Strong Community Support: Being backed by Google ensures long-term support and
vast resources for learning.
4. Two-Way Data Binding: Reduces the need for repetitive code, improving development
speed and reducing errors.
5. Testing Support: AngularJS is designed with testing in mind, allowing for unit testing
and end-to-end testing.

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 1
Web Technologies 22MCA24

2.0 Directives

 AngularJS lets you extend HTML with new attributes called Directives.
 AngularJS has a set of built-in directives which offers functionality to your applications.
 AngularJS also lets you define your own directives.

Types of Directives in AngularJS:


AngularJS directives can be classified into two main categories:
1. Core (Built-in) Directives: These are pre-defined by AngularJS and are the most
commonly used directives. They handle binding data, event handling, and more.
2. Custom Directives: These allow developers to define their own directives for custom
behavior and structure within their application.
Let’s break these down with detailed explanations and examples:

1. Core (Built-in) Directives


These are directives that AngularJS provides out-of-the-box to handle common functionality like
binding data, handling forms, event handling, conditional rendering, and more.
a. ng-app (Application Root Directive)
 Description: The ng-app directive initializes an AngularJS application. It defines the root
element of the app and establishes the application scope for Angular.
 Purpose: It kick starts the AngularJS framework within a specified DOM element.
 Example:
<div ng-app="myApp">
<!-- AngularJS application starts here -->
</div>
b. ng-model (Two-Way Data Binding)
 Description: The ng-model directive binds the value of HTML form controls (like
<input>, <select>, and <textarea>) to a property on the AngularJS scope. This creates a
two-way data binding between the UI and the model.
 Purpose: Used for syncing data between the view (UI) and the controller (model).
 Example:
<input type="text" ng-model="name">
Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 2
Web Technologies 22MCA24

<p>Your name is: {{name}}</p>


 Use case: Form input fields like text boxes, checkboxes, etc.
c. ng-bind (One-Way Data Binding)
 Description: The ng-bind directive binds the value of an AngularJS expression to the text
content of an HTML element. It updates the content dynamically when the expression
value changes.
 Purpose: Prevents the flash of uncompiled content (which happens with {{ }}
expressions) by showing the bound data once it’s ready.
 Example:
<p ng-bind="name"></p>
d. ng-init (Initialize Variables)
 Description: The ng-init directive initializes data within the scope of the AngularJS
application. It can be used to set default values for variables.
 Purpose: To provide an easy way to initialize data in the view without needing a
controller.
 Example:
<div ng-init="name='AngularJS'"></div>
<p>{{name}}</p>
e. ng-repeat (Iteration)
 Description: The ng-repeat directive repeats a set of HTML elements for each item in a
collection (such as an array or an object).
 Purpose: To iterate over an array or an object and create HTML elements dynamically
for each item.
 Example:
<ul>
<li ng-repeat="student in students">{{student.name}}</li>
</ul>
 Use case: Lists of items, tables, etc.
f. ng-if (Conditional Rendering)

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 3
Web Technologies 22MCA24

 Description: The ng-if directive conditionally includes or removes elements from the
DOM based on the value of an expression. If the expression evaluates to true, the element
is added to the DOM; if false, the element is removed.
 Purpose: Used to conditionally display or hide elements.
 Example:
<p ng-if="isVisible">This text is shown only if isVisible is true</p>
g. ng-show and ng-hide (Visibility Control)
 Description:
o ng-show: Displays an element if the expression evaluates to true (using display:
block).
o ng-hide: Hides an element if the expression evaluates to true (using display:
none).
 Purpose: Used to toggle visibility without removing the element from the DOM.
 Example:
<p ng-show="isVisible">This text is visible</p>
<p ng-hide="isHidden">This text is hidden</p>
h. ng-class (Dynamic Class Binding)
 Description: The ng-class directive dynamically binds CSS classes to an HTML element
based on the value of an expression. It can add or remove classes dynamically based on
the data in the scope.
 Purpose: Apply different styles to elements based on the model data.
 Example:
<p ng-class="{active: isActive, disabled: !isActive}">This element has dynamic classes</p>
i. ng-style (Dynamic Styling)
 Description: The ng-style directive dynamically sets CSS styles on an HTML element
based on an expression. You can apply multiple styles dynamically using an object.
 Purpose: Dynamically apply CSS styles to elements.
 Example:
<p ng-style="{'color': myColor, 'font-size': mySize}">This text has dynamic styling</p>
j. ng-click (Event Handling)
Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 4
Web Technologies 22MCA24

 Description: The ng-click directive attaches a click event handler to an HTML element.
When the element is clicked, the expression provided is evaluated.
 Purpose: Handle click events in AngularJS applications.
 Example:
<button ng-click="sayHello()">Click Me</button>
k. ng-view (Single Page Application Routing)
 Description: The ng-view directive is used in Single Page Applications (SPAs) to load
and inject different views dynamically into the same page based on the current route. It
works in conjunction with AngularJS’s routing mechanism.
 Purpose: Used to load partial templates and controllers dynamically based on the URL.
 Example:
<div ng-view></div>

2. Custom Directives
Custom directives in AngularJS allow you to create reusable components that can encapsulate
specific behaviors or functionality. Custom directives can be used to define your own HTML
tags, attributes, or class-based directives that encapsulate and modularize the behavior.
Creating a Custom Directive:
Custom directives are defined using the .directive() method of an AngularJS module.
 Basic Structure:
angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'E', // 'E' for Element, 'A' for Attribute
template: '<h1>Custom Directive Example</h1>'
};
});
 Usage Example:
<my-directive></my-directive>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 5
Web Technologies 22MCA24

Key Elements of a Custom Directive:


 restrict: Defines how the directive can be used. Possible options include:
o E for Element (e.g., <my-directive></my-directive>).

o A for Attribute (e.g., <div my-directive></div>).

o C for Class (e.g., <div class="my-directive"></div>).

o M for Comment (e.g., <!-- directive: my-directive -->).

 template or templateUrl: Defines the HTML content or external HTML file to be used
by the directive.
 scope: Specifies an isolated or shared scope for the directive.
3.0 AngularJS Expressions
AngularJS binds data to HTML using 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 }}

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

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 6
Web Technologies 22MCA24

3.1 AngularJS Numbers


AngularJS numbers are like JavaScript numbers:
<!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="quantity=1;cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div>
</body>
</html>
3.2 AngularJS Strings
AngularJS strings are like JavaScript strings:
<!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="firstName='John';lastName='Doe'">
<p>The full name is: {{ firstName + " " + lastName }}</p>
</div>
</body>
</html>
3.3 AngularJS Objects
AngularJS objects are like JavaScript objects:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 7
Web Technologies 22MCA24

<body>
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p>The name is {{ person.lastName }}</p>
</div>
</body>
</html>
3.4 AngularJS Arrays
AngularJS arrays are like JavaScript arrays:
<!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="points=[1,15,19,2,40]">
<p>The third result is {{ points[2] }}</p>
</div>
</body>
</html>
AngularJS Expressions vs. JavaScript Expressions
Like JavaScript expressions, AngularJS expressions can contain literals, operators, and variables.
Unlike JavaScript expressions, AngularJS expressions can be written inside HTML.
AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript
expressions do.
AngularJS expressions support filters, while JavaScript expressions do not.
4.0 AngularJS Controllers
AngularJS controllers control the data of AngularJS applications.
AngularJS controllers are regular JavaScript Objects.
AngularJS applications are controlled by controllers.

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 8
Web Technologies 22MCA24

The ng-controller directive defines the application controller.


A controller is a JavaScript Object, created by a standard JavaScript object constructor.
$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.

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

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 9
Web Technologies 22MCA24

</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).
5.0 Filters
AngularJS filters are used to format data before it is displayed to the user. They can be applied in
expressions, directives, or services to transform data. Filters allow you to format text, date,
currency, and more, without changing the underlying data in your application.

Types of AngularJS Filters


1. Text Filters:
o uppercase: Converts text to uppercase.

o lowercase: Converts text to lowercase.

o limitTo: Limits the number of items in an array or characters in a string.

2. Number Filters:
o number: Formats a number as text using a local-specific format (e.g., adding
commas or decimal points).
o currency: Formats a number as a currency value, based on the locale and
currency symbol.
o date: Formats a date object or timestamp into a specified date format.
Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 10
Web Technologies 22MCA24

3. Array Filters:
o filter: Filters an array based on a criteria or function.

o orderBy: Orders the items in an array based on a specified field or expression.

4. Custom Filters:
o AngularJS allows you to create custom filters for specific data transformations
that are not covered by built-in filters.
Using Filters
1. Text Filters
uppercase and lowercase:
<p>{{ 'hello world' | uppercase }}</p> <!-- Output: HELLO WORLD -->
<p>{{ 'HELLO WORLD' | lowercase }}</p> <!-- Output: hello world -->
limitTo:
<p>{{ 'AngularJS Filters are powerful' | limitTo: 7 }}</p> <!-- Output: Angular -->
2. Number Filters
number:
<p>{{ 1234567.89 | number:2 }}</p> <!-- Output: 1,234,567.89 -->
currency:
<p>{{ 1234.56 | currency:'€' }}</p> <!-- Output: €1,234.56 -->
date:
<p>{{ today | date:'fullDate' }}</p> <!-- Output: e.g., Wednesday, September 25, 2024 -->
3. Array Filters
filter:
<!-- Assuming `students` is an array of objects with a `name` property -->
<p ng-repeat="student in students | filter:searchText">{{ student.name }}</p>
<input type="text" ng-model="searchText" placeholder="Search students">
orderBy:
<ul>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 11
Web Technologies 22MCA24

<li ng-repeat="student in students | orderBy:'name'">{{ student.name }}</li>


</ul>
4. Custom Filters
To create a custom filter, define it in an AngularJS module using the .filter() method. Here's an
example of a custom filter:
Custom Filter Definition:
angular.module('myApp', [])
.filter('reverse', function() {
return function(input) {
if (!input) return;
return input.split('').reverse().join('');
};
});
Using Custom Filter in HTML:
<p>{{ 'AngularJS' | reverse }}</p> <!-- Output: SJralugnA -->
Detailed Example
Here's a full example using various built-in filters:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS Filters Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script>
angular.module('myApp', [])
.controller('MyController', function($scope) {

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 12
Web Technologies 22MCA24

$scope.today = new Date();


$scope.amount = 1234.56;
$scope.students = [
{ name: 'John', age: 18 },
{ name: 'Jane', age: 22 },
{ name: 'Alex', age: 20 }
];
$scope.searchText = '';
});
</script>
</head>
<body ng-controller="MyController">

<!-- Text Filters -->


<p>{{ 'hello world' | uppercase }}</p>
<p>{{ 'HELLO WORLD' | lowercase }}</p>

<!-- Number Filters -->


<p>{{ amount | number:2 }}</p>
<p>{{ amount | currency:'€' }}</p>

<!-- Date Filter -->


<p>{{ today | date:'fullDate' }}</p>

<!-- Array Filters -->


<input type="text" ng-model="searchText" placeholder="Search students">
<ul>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 13
Web Technologies 22MCA24

<li ng-repeat="student in students | filter:searchText | orderBy:'name'">


{{ student.name }} ({{ student.age }} years old)
</li>
</ul>
<!-- Custom Filter -->
<script>
angular.module('myApp').filter('reverse', function() {
return function(input) {
if (!input) return;
return input.split('').reverse().join('');
};
});
</script>
<p>{{ 'AngularJS' | reverse }}</p>
</body>
</html>
6.0 AngularJS 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
1. $location service.
The $location service has methods which return information about the location of the current
web page:
Example:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 14
Web Technologies 22MCA24

<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>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $location) {
$scope.myUrl = $location.absUrl();
});
</script>

</body>
</html>
2.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.
<!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>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 15
Web Technologies 22MCA24

<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) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
</script>

</body>
</html>
3.The $timeout Service
The $timeout service is AngularJS' version of the window.setTimeout function.
<!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">

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 16
Web Technologies 22MCA24

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

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

</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>
4.The $interval Service
The $interval service is AngularJS' version of the window.setInterval function.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 17
Web Technologies 22MCA24

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

<p>The time is:</p>

<h1>{{theTime}}</h1>

</div>

<p>The $interval service runs a function every specified millisecond.</p>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});
</script>

</body>
</html>
Create Your Own Service

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

Create a service named hexafy:

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 18
Web Technologies 22MCA24

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:

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

</div>

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

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 19
Web Technologies 22MCA24

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

7.0 Angular JS Events

An Events in AngularJS can be used to perform particular tasks, based on the action taken. Both
Angular Event & the HTML Event will be executed & will not overwrite with an HTML Event.
It can be added using the Directives mentioned below:

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 20
Web Technologies 22MCA24

1. ng-mousemove: The movement of the mouse leads to the execution of the event.

2. ng-mouseup: Movement of the mouse upwards leads to the execution of the event.

3. ng-mousedown: Movement of the mouse downwards leads to the execution of the event.

4. ng-mouseenter: Click of the mouse button leads to the execution of the event.

5. ng-mouseover: Hovering the mouse leads to the execution of the event.

6. ng-cut: Cut operation leads to the execution of the event.

7. ng-copy: Copy operation leads to the execution of the event.

8. ng-keypress: Press of key leads to the execution of the event.

9. ng-keyup: Press of upward arrow key leads to the execution of the event.

10. ng-keydown: Press of downward arrow key leads to the execution of the event.

11. ng-click: Single click leads to the execution of the event.

12. ng-dblclick: Double click leads to the execution of the event.

13. ng-blur: Fired when an HTML element loses its focus.

14. ng-change: It is used whenever the value of an input element changes.

15. ng-focus: It is used to apply custom behavior when an element is focused.

16. ng-paste: It is used to specify custom behavior functions when the text in input fields is
pasted into an HTML element.

17. ng-mouseleave: It is used to apply custom behavior when a mouse-leave event occurs on a
specific HTML element.

<!DOCTYPE html>

<html>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 21
Web Technologies 22MCA24

<head>

<script src=

"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">

</script>

</head>

<body>

<p>

Move the mouse over NCEH

to increase the Total Count.

</p>

<div ng-app="App1"

ng-controller="Ctrl1">

<h1 ng-mousemove="count = count + 1">

NCEH

</h1>

<h2>Total Count:</h2>

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

</div>

<script>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 22
Web Technologies 22MCA24

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

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

$scope.count = 0;

});

</script>

</body>

</html>

1. ng-click - Click Event

The ng-click directive is used to specify a behavior when an element is clicked.

Example:

<!DOCTYPE html><html ng-app="myApp"><head>

<title>AngularJS ng-click Example</title>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script></
head><body ng-controller="myCtrl">

<button ng-click="showMessage()">Click me!</button>

<p>{{message}}</p>

<script>

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

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

$scope.message = "";

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 23
Web Technologies 22MCA24

$scope.showMessage = function() {

$scope.message = "Button clicked!";

};

});

</script>

</body></html>

2. ng-dblclick - Double Click Event

The ng-dblclick directive handles double-click events on an element.

Example:

<button ng-dblclick="resetMessage()">Double-click me!</button><p>{{message}}</p>

<script>

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

$scope.resetMessage = function() {

$scope.message = "Message reset on double-click!";

};

});</script>

3. ng-keyup - Keyup Event

The ng-keyup directive is used to call a function when a key is released.

Example:

<input type="text" ng-keyup="showKey($event)"><p>{{key}}</p>

<script>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 24
Web Technologies 22MCA24

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

$scope.key = "";

$scope.showKey = function(event) {

$scope.key = "Key pressed: " + event.key;

};

});</script>

4. ng-submit - Form Submission Event

The ng-submit directive is used to handle form submission.

Example:

<form ng-submit="submitForm()">

<input type="text" ng-model="name" placeholder="Enter name">

<button type="submit">Submit</button></form><p>{{name}}</p>

<script>

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

$scope.submitForm = function() {

$scope.name = "Submitted name: " + $scope.name;

};

});</script>

5. ng-mouseover - Mouse Over Event

The ng-mouseover directive triggers an action when the mouse pointer hovers over an element.

Example:

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 25
Web Technologies 22MCA24

<div ng-mouseover="hoverMessage()">Hover over this text!</div><p>{{message}}</p>

<script>

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

$scope.hoverMessage = function() {

$scope.message = "Mouse over event triggered!";

};

});</script>

6. ng-focus and ng-blur - Focus and Blur Events

These directives handle focus and blur events on input elements.

Ex0ample:

<input type="text" ng-focus="onFocus()" ng-blur="onBlur()"><p>{{message}}</p>

<script>

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

$scope.message = "";

$scope.onFocus = function() {

$scope.message = "Input is focused";

};

$scope.onBlur = function() {

$scope.message = "Input lost focus";

};

});</script>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 26
Web Technologies 22MCA24

$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) {

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 27
Web Technologies 22MCA24

$scope.x = myE.clientX;

$scope.y = myE.clientY;

});

</script>

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

</body>

</html>

8.0 AngularJS Forms

 Forms are collection of controls that is input field, buttons, checkbox and these can
be validatedreal time. As soon as a user of the form completes writing a field and moves to
the next one itgets validated and suggests the user where he might have went wrong.

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

Input Controls

Input controls are the HTML input elements:

1. input elements

2. select elements

3. button elements

4. textarea elements

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 28
Web Technologies 22MCA24

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:

<!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">

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

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 29
Web Technologies 22MCA24

1. Checkbox

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

<!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">

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

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

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 30
Web Technologies 22MCA24

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

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

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 31
Web Technologies 22MCA24

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

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

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

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 32
Web Technologies 22MCA24

<option value="tuts">Tutorials

<option value="cars">Cars

</select>

</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
dropdown list.</p>

</body>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 33
Web Technologies 22MCA24

</html>

9.0 Angular Js Form Validation

AngularJS provides a comprehensive set of built-in tools to handle form validation, allowing you
to easily manage the state of form inputs, display error messages, and ensure data integrity
before submission. It tracks form and field validity through different states and offers validation
feedback through model properties such as $valid, $invalid, $touched, $dirty, etc.

1. Form Model and Control States: AngularJS forms track the state of form controls and
provide properties like $valid, $invalid, $dirty, $touched, and $untouched to handle form
validation.

2. Built-In Validators: AngularJS provides several built-in validation directives, such as:

 ng-required: Validates that a field is required.

 ng-minlength / ng-maxlength: Enforces minimum/maximum length for input fields.

 ng-pattern: Validates input against a regular expression pattern.

 type="email": Validates that the input is in email format.

3. Custom Validation: You can also create custom validation rules using directives and
$validators.

Form States in AngularJS

$valid: True if the form/field is valid.

$invalid: True if the form/field is invalid.

$dirty: True if the form/field has been modified.

$touched: True if the form/field has been focused and then blurred.

$untouched: True if the form/field has never been blurred.

Example: Basic AngularJS Form with Validation

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 34
Web Technologies 22MCA24

<!DOCTYPE html>

<html ng-app="myApp">

<head>

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

</head>

<body ng-controller="myCtrl">

<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>

<!-- Username field with required validation -->

<div>

<label>Username:</label>

<input type="text" name="username" ng-model="user.username" ng-required="true" />

<span ng-show="userForm.username.$error.required && userForm.username.


$touched">Username is required!</span>

</div>

<!-- Email field with email format validation -->

<div>

<label>Email:</label>

<input type="email" name="email" ng-model="user.email" ng-required="true" />

<span ng-show="userForm.email.$error.required && userForm.email.$touched">Email


is required!</span>

<span ng-show="userForm.email.$error.email && userForm.email.$touched">Invalid


email format!</span>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 35
Web Technologies 22MCA24

</div>

<!-- Password field with minlength validation -->

<div>

<label>Password:</label>

<input type="password" name="password" ng-model="user.password" ng-


required="true" ng-minlength="6" />

<span ng-show="userForm.password.$error.required && userForm.password.


$touched">Password is required!</span>

<span ng-show="userForm.password.$error.minlength && userForm.password.


$touched">Password must be at least 6 characters long!</span>

</div>

<!-- Submit button enabled only if form is valid -->

<button type="submit" ng-disabled="userForm.$invalid">Submit</button>

</form>

<!-- Feedback on form submission -->

<p>{{message}}</p>

<script>

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

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

$scope.user = {}; // User model

$scope.submitForm = function(isValid) {

if (isValid) {

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 36
Web Technologies 22MCA24

$scope.message = "Form submitted successfully!";

} else {

$scope.message = "There are validation errors!";

};

});

</script>

</body>

</html>

Detailed Explanation of Validation in the Example

Form and Input Fields:

The form is created using the <form> tag, and the name="userForm" attribute assigns it a
reference.

Each input field (username, email, and password) is bound to a model using ng-model.

Validation is added to these fields using built-in directives like ng-required, ng-minlength, and
the HTML type="email" for email validation.

Validation Feedback:

Error messages are displayed using ng-show when certain conditions are met, such as when the
field is invalid (userForm.username.$error.required) and has been interacted with
(userForm.username.$touched).

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 37
Web Technologies 22MCA24

For example, if the username field is empty and the user has clicked and then clicked away from
it, the error message "Username is required!" will be displayed.

Submit Button and Form Submission:

The form submission is handled by ng-submit="submitForm(userForm.$valid)", which only


allows submission if the form is valid (userForm.$valid).

The submit button is disabled (ng-disabled="userForm.$invalid") if the form is invalid.

Built-In Validators in AngularJS

ng-required: Ensures that the field is filled out.

<input type="text" ng-model="user.name" ng-required="true">

ng-minlength / ng-maxlength: Ensures that the input length is within a defined range.

<input type="text" ng-model="user.password" ng-minlength="6" ng-


maxlength="12">

ng-pattern: Validates the input against a custom regular expression.

<input type="text" ng-model="user.phone" ng-pattern="/^\


d{10}$/">

Email Validation: Using the HTML5 type="email" ensures the input is in valid email format.

<input type="email" ng-model="user.email">

Custom Validation in AngularJS

You can create custom validation rules using AngularJS directives. Custom validators are added
using $validators in a directive.

<form name="userForm">

<label>Password:</label>

<input type="password" name="password" ng-


model="user.password" special-char />

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 38
Web Technologies 22MCA24

<span ng-show="userForm.password.
$error.specialChar">Password must contain a special
character!</span>

</form>

<script>

app.directive('specialChar', function() {

return {

require: 'ngModel',

link: function(scope, element, attrs, ngModel) {

ngModel.$validators.specialChar = function(value) {

return /[!@#$%^&*]/.test(value); // must contain at least


one special character

};

};

});

</script>

In this example:

The specialChar custom directive validates that the password contains at least one special
character using a regular expression.

Select Box

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 39
Web Technologies 22MCA24

AngularJS provides two primary directives for creating select (dropdown) boxes: ng-options and
ng-repeat. The ng-options directive is specifically designed for filling a dropdown list with
options, making it the preferred choice when working with arrays or objects.

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:

Code:

<!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"];

});

</script>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 40
Web Technologies 22MCA24

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

Code:

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

<script>

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

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 41
Web Technologies 22MCA24

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.

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"}
];

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>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 42
Web Technologies 22MCA24

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

<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"}

];

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 43
Web Technologies 22MCA24

});

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

Using ng-options:

<!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.model for x in cars">

</select>

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

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

</div>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 44
Web Technologies 22MCA24

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

AngularJS Tables

In AngularJS, tables are typically created using the <table> element combined with AngularJS
directives like ng-repeat for dynamically displaying data from an array.

The ng-repeat directive is perfect for displaying tables.

Displaying Data in a Table

Displaying tables with angular is very simple:

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 45
Web Technologies 22MCA24

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

</body>

</html>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 46
Web Technologies 22MCA24

Displaying with CSS Style

To add some CSS to the page:

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

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

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 47
Web Technologies 22MCA24

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

</body>

</html>

Display with orderBy Filter

To sort the table, add an orderBy filter:

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 48
Web Technologies 22MCA24

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

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

<table>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 49
Web Technologies 22MCA24

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

</html>

Display with uppercase Filter

To display uppercase, add an uppercase filter:

<!DOCTYPE html>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 50
Web Technologies 22MCA24

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

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

<table>

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

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 51
Web Technologies 22MCA24

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

</html>

Display the Table Index ($index)

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

<!DOCTYPE html>

<html>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 52
Web Technologies 22MCA24

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

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

<table>

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

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

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 53
Web Technologies 22MCA24

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

</html>

Model

In AngularJS, a model is the part of the MVC (Model-View-Controller) architecture that


represents the data and business logic. It is responsible for maintaining application data and
synchronizing it with the view using two-way data binding.

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 54
Web Technologies 22MCA24

Working with Models in AngularJS

In AngularJS, the model is typically a JavaScript object that resides in the $scope. The controller
initializes and manages the model, while the view binds to it.

<!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">

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

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 55
Web Technologies 22MCA24

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

Code:

<!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">

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>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 56
Web Technologies 22MCA24

</body>

</html>

Validate User Input

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

Code:

<!DOCTYPE html>

<html>

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

Application Status

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 57
Web Technologies 22MCA24

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

<!DOCTYPE html>

<html>

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

CSS Classes

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 58
Web Technologies 22MCA24

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

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

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

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 59
Web Technologies 22MCA24

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.

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";
});

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 60
Web Technologies 22MCA24

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

<!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 ng-bind="firstname"></p>

</div>

<script>

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

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

$scope.firstname = "John";

$scope.lastname = "Doe";

});

</script>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 61
Web Technologies 22MCA24

<p>Use the ng-bind directive to bind the innerHTML of an element to a property in the data
model.</p>

</body>

</html>

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

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>First name: {{firstname}}</p>

</div>

<script>

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

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

$scope.firstname = "John";

$scope.lastname = "Doe";

});

</script>

<p>You can use double braces to display content from the data model.</p>

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 62
Web Technologies 22MCA24

</body>

</html>

Refer w3 schools for data binding

Ms Yashaswini Y
Assistant Professor, Dept of MCA,NCEH Page 63

You might also like