0% found this document useful (0 votes)
143 views43 pages

Angular JS Unit-4

Filter, Forms and Ajax Filters 4.1 Built-in Filters - upper case and lower case filters, date ,currency and number formatting , orderBy, filter ,custom filter, 4.2 Angular JS Forms – Working with AngularJS forms, model binding, custom model update triggers, custom validation, $http service 4.3 Ajax implementation using $http

Uploaded by

Tulshiram Kamble
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
143 views43 pages

Angular JS Unit-4

Filter, Forms and Ajax Filters 4.1 Built-in Filters - upper case and lower case filters, date ,currency and number formatting , orderBy, filter ,custom filter, 4.2 Angular JS Forms – Working with AngularJS forms, model binding, custom model update triggers, custom validation, $http service 4.3 Ajax implementation using $http

Uploaded by

Tulshiram Kamble
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 43

Unit – 4

Filter, Forms and Ajax Filters


Filter
• Filters can be added in AngularJS to format data to display on UI
without changing the original format.
• Filters can be added to an expression or directives using the pipe (|)
symbol.
• Syntax
{{expression | filterName:parameter }}
AngularJS Filters
• AngularJS provides filters to transform data of different data types.
The following table shows the significant filters:
• currency: It is used to convert a number into a currency format.
• date: It is used to convert a date into a specified format.
• filter: It is used to filter the array and object elements and return the
filtered items.
• lowercase: It is used to convert a string into lowercase letters.
• uppercase: It is used to convert a string into uppercase letters.
• number: It is used to convert a number into a string or text.
• orderBy: It sorts an array based on specified predicate expressions.
Built-in filters
Upper case
• The uppercase Filter in AngularJS is used to change a string to
uppercase string or letters.
• Syntax:
{{string | uppercase}}
Example
<html>
<head> <script src="angular.min.js"></script></head>
<body ng-app="app" >
<h1> Uppercase Built in filter </h1>
<h2>uppercase Filter </h2>
<div ng-controller=“upper">
<p> <span> {{msg | uppercase}} </span>: filter used to convert String to uppercase format.
<p>
</div>
<script>
angular.module('app', []).controller(‘upper', function($scope) { $scope.msg = ‘uppercase '; });
</script>
</body>
</html>
Lower case
• The lowercase filter is used to convert a string into lowercase letters.
• Syntax:
{{expression|lowercase}}
Example
<html>
<head> <script src="angular.min.js"></script></head>
<body ng-app="app" >
<h1> Lowercase Built in filter </h1>
<div ng-controller=“lower">
<p> <span> {{msg | Lowercase}} </span>: filter used to convert String to Lowercase
format.
<p>
</div>
<script> angular.module('app', []).controller(‘ lower', function($scope) { $scope.msg =
‘LOWERCASE'; });
</script>
</body>
</html>
Date
• AngularJS date filter is used to convert a date into a specified format.
• When the date format is not specified, the default date format is
‘MMM d, yyyy’.
• Syntax:
{{ date | date : format : timezone }}

Here are some common format options:


• 'short': Short date format (e.g., "M/d/yy"). e.g. 9/7/23.
• 'medium': Medium date format (e.g., "MMM d, y h:mm:ss a").
e.g. Sep 7, 2023 12:34:56 PM
• 'fullDate': Full date format (e.g., "EEEE, MMMM d, y").
e.g. Thursday, September 7,2023.
• 'yyyy-MM-dd': Custom format for ISO-like date e.g., "2023-09-07".
Example
<html>
<head> <script src="angular.min.js"></script></head>
<body>
<div ng-app=“dateApp" ng-controller="dateCntrl">
<p>{{ today | date : "dd.MM.y" }}</p>
</div>
<script>
var app = angular.module(‘dateApp', []);
app.controller('dateCntrl', function($scope) {
$scope.today = new Date();
});
</script>
</body>
</html>
Currency
• AngularJS currency filter is used to convert a number into a currency
format. If no currency format is specified currency filter uses the
local currency format.
• Syntax:
{{ currency_expression | currency : symbol : fractionSize}}
• Parameters:
It contains 2 parameters as mentioned above and described below:
symbol: It is an optional parameter. It is used to specify the currency
symbol. The currency symbol can be any character or text.
fractionSize: It is an optional parameter. It is used to specify the
number of decimals.
Example
<html>
<head><script src="angular.min.js"> </script></head>
<body>
<h3>AngularJS currency Filter</h3>
<div ng-app=“currencyApp" ng-controller="currencyCntrl">
<h3> Currency filter with currency symbol and fraction size. </h3>
<p>Amount : {{ amount | currency : "₹" :2}}</p> 75.65
</div>
<script>
var app = angular.module(‘currencyApp ', []);
app.controller('currencyCntrl', function ($scope) { $scope.amount =
75.648; });
</script>
</body>
</html>
Number
• AngularJS number filter is used to convert a number into a string or
text.
• We can also define a limit to display a number of decimal digits.
• The number filter rounds off the number to specified decimal digits.
• Syntax:
{{ string| number : fractionSize}}
Parameter Values: It contains single parameter value fractionSize which
is of type number and used to specify the number of decimals.
Example
<html>
<head> <script src="angular.min.js"></script></head>
<body>
<div ng-app=“numApp" ng-controller="numberCntrl">
<h3>Number filter with fraction size.</h3>
<p>Number : {{ value| number : 2}}</p> 75598.55
</div>
<script>
var app = angular.module(‘numApp', []);
app.controller('numberCntrl', function($scope) {
$scope.value = 75598.548;
});
</script>
</body>
</html>
orderBy
• An orderBy Filter in AngularJS is used to sort the given array to the specific
order.
• The default order of sorting the string is in alphabetical order whereas the
numbers are numerically sorted.
• By default, all the items are sorted in ascending order, if the ordering
sequence is not specified.
• Syntax:
{{orderBy_expression | orderBy: expression: reverse: comparator}}
• Parameter Values:
expression: This parameter value can be used to determine the order while
filtering the items. It can be the following types:
reverse: It is an optional parameter that will be required to reverse the order
of the array if its value is set to true.
Example
<html> <script>
var app = angular.module('myApp', []);
<head> <script src="angular.min.js"> app.controller('orderCtrl', function($scope) {
</script></head> $scope.customers = [{
"name": "Amber",
<body> "city": “Pune"
<div ng-app="myApp" }, {
"name": "lakshay ",
ng-controller="orderCtrl"> "city": "vizag"
<h3>AngularJS orderBy Filter</h3> }, {
"name": "karan",
<ul> "city": "London"
<li ng-repeat="x in customers | orderBy }, {
: 'name'"> "name": "bhaskar",
"city": “Mumbai"
{{x.name + ", " + x.city}} }, ];
</li> });
</script>
</ul>
<p>The array items are arranged by "name".</p>
</div </body>
</html>
Filter
• In other words, this filter selects a subset (a smaller array containing elements that
meet the filter criteria) of an array from the original array.
• Syntax:
{{arrayexpression | filter: expression : comparator : anyPropertyKey}}

Parameter Values:
• arrayexpression: The source array on which the filter will be applied.
• expression: It is used to select the items from the array after the filter conditions
are met. It can be of String type, Function type, or Object type.
• comparator: It is used to determine the value by comparing the expected value
from the filter expression, and the actual value from the object array.
• anyPropertyKey: It is an optional parameter having the special property that is used
to match the value against the given property. It is of String type & its default value
is $.
Example
<html>
<head><script src="angular.min.js"></script></head>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<h3>AngularJS filter Filter</h3>
<ol>
<li ng-repeat="x in names | filter : 'e‘ "> {{ x }} </li>
</ol>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = ['Jani','Carl', ‘esha’,’Rahul’,’Mathew', 'Joey ];
});
</script>
</body></html>
Custom filter
• Sometimes the built-in filters in Angular cannot meet the needs or
requirements for filtering output. In such a case, an AngularJS custom filter
can be created, which can pass the output in the required manner.
• To crate it the same way we have created controllers & modules.
• With the help of angular.filter we can create custom filter.
Syntax:
app.filter( filtername, function()
{ return function (input, value1,value2)
{ var input; return output;}
}
);
Example

<html> <body ng-app=”myapp”>


<head><script <div ng-controller=”CustomCtrl”>
src="angular.min.js"></script>
<p>
<script>
var app=angular.module(‘myapp’,[]); {{name |convertUppercase}}
app.filter(‘convertUppercase’,function() </p>
{ return function(item) </div>
{return item.toUppercase();
</body>
};
}); </html>
app.controller(‘Custromctrl’,function($scop
e)
{
$scope.name=’angularJS’;
});
</script>
</head>
Angular JS Forms
• Forms are very important medium when we want to collect some
data from the user.
• Like user registration form to collect information or data.
• A form will take input from user and send it to a back end application
such as CGI,PHP script.
• These back end applications will perform required processing on the
data based on defined business logic inside the application.
Working with AngularJS forms
• AngularJS facilitates you to create a form enriches (enhance) with data
binding and validation of input controls.
• Input controls are ways for a user to enter data. A form is a collection of
controls for the purpose of grouping related data together.
• Following are the input controls used in AngularJS forms:
• input elements
• select elements
• button elements
• textarea elements
• In AngularJS data binding to input controls can be done by using ng-model
directive.
• The ng-model directive in AngularJS used to bind & get data from input
controls & it will provide two way data binding by synchronizing data between
model to view & vice-versa.
data binding Example

<html>
<head> <script src="angular.min.js"> </script>
<script>
var app=angular.module(‘myapp’,[]);
app.controller(‘formctrl’,function($scope)
{ $scope.pname=”sachin”;
$scope.gname=”cricket”;
});
</script></head>
<body >
<div ng-app=”myapp” ng-controller=” formctrl”>
Player’s Name:<input type=”text” ng-model=”pname”/><br>
Game Name:<input type=”text” ng-model=” gname”/><br>
<p> Detail Information: {{pname+” “+gname}}</p>
</div>
</body></html>
<html> <body>
<head> <div ng-app="myapp" ng-controller="formCtrl">
<script src="angular.min.js"></script> <form novalidate>
<script> P_name:<input type="text" ng-model="product.name“/>
var app = angular.module('myapp', []);
app.controller('formCtrl', function ($scope) { P_qut:<input type="number" ng-model="product.qut“/>
$scope.master = {};
$scope.product = {}; Pay_type:<input type="radio" ng-model="product.type"
value="cash“ /> Cash
$scope.save = function (product) {
$scope.master = angular.copy(product); <input type="radio" ng-model="product.type"
}; value="credit“ /> Credit
$scope.reset = function () {
// $scope.product = angular.copy($scope.master); <input type="button" ng-click="reset()" value="Reset"/>
$scope.product = {}; // Clear the product data <input type="button" ng-click="save(product)"
$scope.master = {}; // Clear the master data value="Save"/>
}; </form>
$scope.reset(); <p>Product Form: {{product | json}}</p>
}); <p>Master: {{master | json}}</p>
</script> </div>
</head> </body>
</html>
Angular form validation
• Validation is the process ensuring that data is correct, complete,
accurate.
• Following list of basic angular form validation options available for an
input field:

Directive Description
ng-required It set required attribute on an input field
ng- minlenght It set minlength attribute on an input field
ng- maxlenght It set maxlength attribute on an input field
Ng-pattern It set pattern validation error key if the ng model value does
not match the specified expression.
<html ng-app="validationApp">
<head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script></
head>

<body ng-controller="validationCtrl">
<form name="myForm" novalidate>
Name: <input type="text" id="name" name="name" ng-model="user.name" ng-required="true">
<span ng-show="myForm.name.$error.required">Name is required.</span>

Email:<input type="email" id="email" name="email" ng-model="user.email" ng-required="true" ng-


pattern="/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.pattern">Invalid email format.</span>

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


minlength="6" ng-maxlength="12">
<span ng-show="myForm.password.$error.minlength">Password is too short.</span>
<span ng-show="myForm.password.$error.maxlength">Password is too long.</span>

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


</form>
<script>
angular.module('validationApp', [])
.controller('validationCtrl', function ($scope) {
$scope.user = {};
});
</script>
</body>
</html>
• We create an AngularJS application called validationApp and a controller
called validationCtrl.
• Inside the form, we use various AngularJS directives to apply validation rules
to form fields:
• ng-required="true" ensures that the field is required.
• ng-pattern="/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/" enforces a
pattern for the email field.
• ng-minlength and ng-maxlength specify minimum and maximum length
requirements for the password field.
• We use the ng-show directive to display error messages when validation fails.
• The "Submit" button is disabled when the form is invalid using ng-
disabled="myForm.$invalid".
Angular form validation Properties /
Using CSS classes

• AngularJS provide properties on forms to keep track of all its controls.


Property Class Description

$valid Ng-valid Return true if all the containing forms and controls are valid.

$invalid Ng-invalid Return true if at least one containing control or form is invalid.

$pristine Ng-pristine Return true if user has not interacted with the form yet.

$dirty Ng-dirty Return true if user has already interacted with the form.

$touched Ng-touched Return true if the input has been blurred.

$submitted Ng-submit Return true if user has submitted the form even if its invalid
<html ng-app="validationApp">
<head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> </head>
<body ng-controller="validationCtrl">

<form name="myForm" ng-submit="submitForm()" novalidate>

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

<div ng-show="myForm.name.$error.required && myForm.name.$dirty">Name is required.</div>

Email:<input type="email" id="email" name="email" ng-model="user.email" ng-required="true">

<div ng-show="myForm.email.$error.required && myForm.email.$dirty">Email is required.</div>

<br>

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


</form>

<div ng-show="myForm.$submitted">
<p ng-show="myForm.$valid">Form submitted successfully!</p>
<p ng-show="myForm.$invalid">Form contains errors. Please correct them.</p>
</div>
<script>
angular.module('validationApp', [])
.controller('validationCtrl', function ($scope) {
$scope.user = {};

$scope.submitForm = function () {
if ($scope.myForm.$valid) {
// Form is valid, perform submission logic here
console.log('Form submitted with data:', $scope.user);
}
};
});
</script>
</body>
</html>
Form 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.
• ng-mousemove: The movement of the mouse leads to the execution of the event.
• ng-mouseup: Movement of the mouse upwards leads to the execution of the event.
• ng-mousedown: Movement of the mouse downwards leads to the execution of the event.
• ng-mouseenter: Click of the mouse button leads to the execution of the event.
• ng-mouseover: Hovering the mouse leads to the execution of the event.
• ng-cut: Cut operation leads to the execution of the event.
• ng-copy: Copy operation leads to the execution of the event.
• ng-keypress: Press of key leads to the execution of the event.
• ng-keyup: Press of upward arrow key leads to the execution of the event.
• ng-keydown: Press of downward arrow key leads to the execution of the event.
• ng-click: Single click leads to the execution of the event.
• ng-dblclick: Double click leads to the execution of the event.
• ng-focus: It is used to apply custom behavior when an element is focused.
• ng-paste: It is used to specify custom behavior functions when the text in input fields is pasted into an HTML element.
<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">
<p>Number: {{ number }}</p>
<button ng-click="incrementNumber()">Increment</button>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.number = 0;
$scope.incrementNumber = function () {
$scope.number++;
};
});
</script>
</body></html>
Custom model Update triggers
• If any changes had made to the content, It will trigger a model update and
form validation.
• With the help of ng-model-options directive, we can override this behavior
and bind only specified events.
• Syntax
<input ng-model=“player.name” ng-model-options=“Object”/>
• E.g.
ng-model-options=“{updateOn:’blur’}” will update and validate only after the
control loses focus.
Ng-model-options

updateOn debounce allowInvalid getterSetter timezone


• Update On: This option controls when the model is updated with the input control's
value changes. You can set it to various events like 'blur', 'default', 'keydown', 'keyup',
'keypress', etc. The default is 'default', which typically means the model is updated on the
input event.

• Debounce: The debounce option introduces a delay before updating the model after the
input control's value changes. It is specified in milliseconds. This can be useful to reduce
the frequency of model updates when the user is typing quickly.

• Allow Invalid: When set to true, this option allows the model to be updated even if the
input control contains an invalid value according to its validation rules. By default, it's set
to false.

• Getter Setter: You can specify custom getter and setter functions to control how the
value is retrieved from and stored in the model. This can be useful for formatting or
transforming data.
<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">
<p>Type in the input field below:</p>
<input type="text" ng-model="inputValue" ng-model-options="{ debounce: 500 }">
<p>Model Value: {{ inputValue }}</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.inputValue = '';
$scope.$watch('inputValue', function (newVal, oldVal) {
if (newVal !== oldVal) { console.log('Model Value Updated:', newVal); }
});
});
</script>
</body>
</html>
AngularJS service
• AngularJS service are JavaScript function or object, who’s responsible
to perform specific tasks and can be reused throughout the
application.
• It provide many inbuilt services. In AngularJS services starts with “$”.
• Example: $http, $window, $location etc.
• These AngularJS services interact with controller, model or custom
directives.
$http service

• It makes the request to the server, in order to handle the response by


the application.
• The $http service is used to send or receive data from the remote
server using browser's XMLHttpRequest or JSONP.
• $http is a service as an object. It includes following shortcut methods.
Method Description
$http.get() Perform Http GET request.
$http.head()Perform Http HEAD request.
$http.post() Perform Http POST request.
$http.put() Perform Http PUT request.
<html ng-app="myApp">
<head> <script src="angular.min.js"></script></head>
<body ng-controller="UserController">
<h1>User List</h1>
<ul> <li ng-repeat="user in users">{{ user.name }}</li> </ul>
<script>
var app = angular.module('myApp', []);
app.controller('UserController', function ($scope, $http) {
$http.get('https://jsonplaceholder.typicode.com/users')
.then(response => $scope.users = response.data)
.catch(error => console.error('Error fetching data:', error));
});
</script>
</body>
Ajax implementation using $http
• AJAX is an acronym which stands for Asynchronous JavaScript and
XML.
• It is important tool in any web application. It is a group of inter-
related technologies like JavaScript, DOM, XML, HTML/XHTML, CSS,
and XMLHttpRequest.
• As name indicate it performs asynchronous activity that will increase
the performance. To enhance the performance of our application we
can use Ajax in AngularJS application.
• AJAX allow us to send & receive data asynchronously without
reloading the web page. So it is fast
• As you can see in the above example, XMLHttpRequest object plays a important
role.
• User sends a request from the UI and a javascript call goes to XMLHttpRequest
object.
• HTTP Request is sent to the server by XMLHttpRequest object.
• Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
• Data is retrieved.
• Server sends XML data or JSON data to the XMLHttpRequest callback function.
• HTML and CSS data is displayed on the browser.
• AngularJS provide $http service to read data from the server.
• The server make a database call to get the desired records or data.
• AngularJS need data in JSON (JavaScript Object Notation) format.
• Once the data is ready, $http can be used to get the data from server.
JSON file format
[
{ “Name”:”Sagar Ghathkar”,
“RollNo”:”101”,
“Percentage”:”60%”
},
{ “Name”:”Sachin Thakare”,
“RollNo”:”102”,
“Percentage”:”65%”
},
]

You might also like