[go: up one dir, main page]

0% found this document useful (0 votes)
35 views15 pages

UNIT 5 - Ost

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

Unit-V

AngularJS : The Basics of AngularJS:


AngularJS is a very powerful JavaScript Framework. It is used in Single Page
Application (SPA) projects. It extends HTML DOM with additional attributes and
makes it more responsive to user actions. AngularJS is open source, completely free,
and used by thousands of developers around the world. It is licensed under the
Apache license version 2.0.

Why to Learn AngularJS?


AngularJS is an open-source web application framework. It was originally developed
in 2009 by Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest
version is 1.2.21.
• AngularJS is a efficient framework that can create Rich Internet Applications
(RIA).
• AngularJS provides developers an options to write client side applications
using JavaScript in a clean Model View Controller (MVC) way.
• Applications written in AngularJS are cross-browser compliant. AngularJS
automatically handles JavaScript code suitable for each browser.
• AngularJS is open source, completely free, and used by thousands of
developers around the world. It is licensed under the Apache license version
2.0.
Overall, AngularJS is a framework to build large scale, high-performance, and easyto-
maintain web applications.

Hello World using AngularJS.


Just to give you a little excitement about AngularJS, I'm going to give you a small
conventional AngularJS Hello World program, You can try it using Demo link.
Live Demo
<html>
<head>
<title>AngularJS First Application</title>
</head>

<body>
<h1>Sample Application</h1>

<div ng-app = "">


<p>Enter your Name: <input type = "text" ng-model =
"name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
</div>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.m
in.js">
</script>

</body>
</html>

Overall, AngularJS is a framework to build large scale, high-performance, and easyto-


maintain web applications.

Directives and Expressions:

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/angu
lar.min.js"></script>
<body>

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

</body>
</html>

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
<div ng-app="" ng-init="firstName='John'">

<p>Name: <input type="text" ng-model="firstName"></p>


<p>You wrote: {{ firstName }}</p>

</div>
MVC:
Model View Controller or MVC as it is popularly called, is a software design pattern
for developing web applications. A Model View Controller pattern is made up of the
following three parts −
• Model − It is the lowest level of the pattern responsible for maintaining data.
• View − It is responsible for displaying all or a portion of the data to the user.
• Controller − It is a software Code that controls the interactions between the
Model and View.
MVC is popular because it isolates the application logic from the user interface layer
and supports separation of concerns. The controller receives all requests for the
application and then works with the model to prepare any data needed by the view.
The view then uses the data prepared by the controller to generate a final presentable
response. The MVC abstraction can be graphically represented as follows.
The Model
The model is responsible for managing application data. It responds to the request
from view and to the instructions from controller to update itself.

The View
A presentation of data in a particular format, triggered by the controller's decision to
present the data. They are script-based template systems such as JSP, ASP, PHP
and very easy to integrate with AJAX technology.

The Controller
The controller responds to user input and performs interactions on the data model
objects. The controller receives input, validates it, and then performs business
operations that modify the state of the data model.
AngularJS is a MVC based framework. In the coming chapters, we will see how
AngularJS uses MVC methodology.

Filters- Built-inFilters:

AngularJS filter is a tool, which we can use to format the data. With this filter, the
user can see and modify according to the requirement. It is added in angular to
format the data that is being displayed on the view part.
Syntax of Filter
With pipe character (|), we can add filters in angularJS.

Filters can club with the expression as well as a directive.

Syntax:
{{expression| name_of_filter}}

-Types of Built-in Filters:

Number Formats a numeric data as text with comma and fraction.


Currency Formats numeric data into specified currency format and fraction.
Date Formats date to string in specified format.
Uppercase Converts string to upper case.
Lowercase Converts string to lower case.
Filter Filters an array based on specified criteria and returns new array.
orderBy Sorts an array based on specified predicate expression.
Json Converts JavaScript object into JSON string
limitTo Returns new array containing specified number of elements from an existing array.

AngularJS Modules
A module in AngularJS is a container of the different parts of an
application such as controller, service, filters, directives, factories
etc. It supports separation of concern using modules.

AngularJS stops polluting global scope by containing AngularJS


specific functions in a module.

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


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
<div ng-app="" ng-init="firstName='John'">

<p>Name: <input type="text" ng-model="firstName"></p>


<p>You wrote: {{ firstName }}</p>

</div>

Built-in directives
Directives are classes that add additional behavior to elements in your Angular
applications. Use Angular's built-in directives to manage forms, lists, styles, and what
users see.

Built-in attribute directives


Attribute directives listen to and modify the behavior of other HTML elements,
attributes, properties, and components.

Many NgModules such as the RouterModule and the FormsModule define their own
attribute directives. The most common attribute directives are as follows:

• NgClass—adds and removes a set of CSS classes.


• NgStyle—adds and removes a set of HTML styles.
• NgModel—adds two-way data binding to an HTML form element.

Built-in directives use only public APIs. They do not have special access to any private
APIs that other directives can't access.

Adding and removing classes with NgClass


Add or remove multiple CSS classes simultaneously with ngClass.

To add or remove a single class, use class binding rather than NgClass.
Using NgClass with an expression

On the element you'd like to style, add [ngClass] and set it equal to an expression. In
this case, isSpecial is a boolean set to true in app.component.ts.
Because isSpecial is true, ngClass applies the class of special to the <div>.

Working with foms:

AngularJS enriches form filling and validation. We can use ng-click event to handle
the click button and use $dirty and $invalid flags to do the validation in a seamless
way. Use novalidate with a form declaration to disable any browser-specific
validation. The form controls make heavy use of AngularJS events. Let us have a
look at the events first.

Events
AngularJS provides multiple events associated with the HTML controls. For example,
ng-click directive is generally associated with a button. AngularJS supports the
following events −

• ng-click
• ng-dbl-click
• ng-mousedown
• ng-mouseup
• ng-mouseenter
• ng-mouseleave
• ng-mousemove
• ng-mouseover
• ng-keydown
• ng-keyup
• ng-keypress
• ng-change

ng-click
Reset data of a form using on-click directive of a button.
<input name = "firstname" type = "text" ng-model = "firstName"
required>
<input name = "lastname" type = "text" ng-model = "lastName"
required>
<input name = "email" type = "email" ng-model = "email" required>
<button ng-click = "reset()">Reset</button>

<script>
function studentController($scope) {
$scope.reset = function() {
$scope.firstName = "Mahesh";
$scope.lastName = "Parashar";
$scope.email = "MaheshParashar@tutorialspoint.com";
}

$scope.reset();
}
</script>

Validate Data
The following can be used to track error.
• $dirty − states that value has been changed.
• $invalid − states that value entered is invalid.
• $error − states the exact error.

Example
The following example will showcase all the above-mentioned directives.
testAngularJS.htm
Live Demo

<html>
<head>
<title>Angular JS Forms</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.m
in.js"></script>

<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>

</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller =
"studentController">

<form name = "studentForm" novalidate>


<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input name = "firstname" type = "text" ng-
model = "firstName" required>
<span style = "color:red" ng-show =
"studentForm.firstname.$dirty && studentForm.firstname.$invalid">
<span ng-show =
"studentForm.firstname.$error.required">First Name is
required.</span>
</span>
</td>
</tr>

<tr>
<td>Enter last name: </td>
<td><input name = "lastname" type = "text" ng-
model = "lastName" required>
<span style = "color:red" ng-show =
"studentForm.lastname.$dirty && studentForm.lastname.$invalid">
<span ng-show =
"studentForm.lastname.$error.required">Last Name is
required.</span>
</span>
</td>
</tr>

<tr>
<td>Email: </td><td><input name = "email" type
= "email" ng-model = "email" length = "100" required>
<span style = "color:red" ng-show =
"studentForm.email.$dirty && studentForm.email.$invalid">
<span ng-show =
"studentForm.email.$error.required">Email is required.</span>
<span ng-show =
"studentForm.email.$error.email">Invalid email address.</span>
</span>
</td>
</tr>

<tr>
<td>
<button ng-click = "reset()">Reset</button>
</td>
<td>
<button ng-disabled =
"studentForm.firstname.$dirty &&
studentForm.firstname.$invalid ||
studentForm.lastname.$dirty &&
studentForm.lastname.$invalid ||
studentForm.email.$dirty &&
studentForm.email.$invalid" ng-
click="submit()">Submit</button>
</td>
</tr>

</table>
</form>
</div>

<script>
var mainApp = angular.module("mainApp", []);

mainApp.controller('studentController', function($scope)
{
$scope.reset = function() {
$scope.firstName = "Mahesh";
$scope.lastName = "Parashar";
$scope.email =
"MaheshParashar@tutorialspoint.com";
}

$scope.reset();
});
</script>

</body>
</html>

Output
Open the file testAngularJS.htm in a web browser and see the result.

AngularJS Model Binding


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>

AngularJS Forms
The HTML form is a collection of input controls where user can enter
the data. Here, you will learn how to display AngularJS form and
submit the data.

An AngularJS Form Example


We will create following Student Information form with submit and
reset functionality.
Sample AngularJS Form

The following is the code of the above form.

Example: AngularJS Form


<!DOCTYPE html>
<html ng-app="studentApp">
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-controller="studentController">
<h1>Student Information:</h1>
<form ng-submit="submitStudnetForm()" >
<label for="firstName" >First Name: </label><br />
<input type="text" id="firstName" ng-
model="student.firstName" /> <br />

<label for="lastName">Last Name</label><br />


<input type="text" id="lastName" ng-
model="student.lastName" /> <br />
<label for="dob" >DoB</label><br />
<input type="date" id="dob" ng-model="student.DoB" />
<br /><br />
<label for="gender" >Gender</label> <br />
<select id="gender" ng-model="student.gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select><br /> <br />
<span>Training Type:</span><br />
<label><input value="online" type="radio"
name="training" ng-model="student.trainingType" />Online</label><br />
<label><input value="onsite" type="radio"
name="training" ng-model="student.trainingType" />OnSite</label> <br
/><br />
<span>Subjects</span><br />
<label><input type="checkbox" ng-
model="student.maths" />Maths</label> <br />
<label><input type="checkbox" ng-
model="student.physics" />Physics</label> <br />
<label><input type="checkbox" ng-
model="student.chemistry" />Chemistry</label><br /><br />

<input type="submit" value="Submit" />


<input type="reset" ng-click="resetForm()" value="Reset" />
</form>
<script>
//1. create app module
var studentApp = angular.module('studentApp', []);

//2. create controller


studentApp.controller("studentController", function ($scope,
$http) {

//3. attach originalStudent model object


$scope.originalStudent = {
firstName: 'James',
lastName: 'Bond',
DoB: new Date('01/31/1980'),
gender: 'male',
trainingType: 'online',
maths: false,
physics: true,
chemistry: true
};

//4. copy originalStudent to student. student will be bind


to a form
$scope.student = angular.copy($scope.originalStudent);

//5. create submitStudentForm() function. This will be


called when user submits the form
$scope.submitStudnetForm = function () {
var onSuccess = function (data, status, headers,
config) {
alert('Student saved successfully.');
};

var onError = function (data, status, headers, config)


{
alert('Error occured.');
}

$http.post('/student/submitData', {
student:$scope.student })
.success(onSuccess)
.error(onError);

};

//6. create resetForm() function. This will be called on


Reset button click.
$scope.resetForm = function () {
$scope.student =
angular.copy($scope.OriginalStudent);
};
});
</script>
</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:

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

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


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

You might also like