0% found this document useful (0 votes)
8 views50 pages

AngularJS Services and Table Features

web technologies module 5

Uploaded by

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

AngularJS Services and Table Features

web technologies module 5

Uploaded by

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

Module 5

Services
• services are singleton objects that are used to organize and
share code across the application.
• They help maintain reusability, modularity, and separation
of concerns by handling tasks like data fetching, logging,
authentication, and business logic.
Types of Services in AngularJS
1. Built-in Services
AngularJS has many predefined services such as:
• $http – Makes AJAX requests to fetch/send data.
• $route – Used for routing in ngRoute module.
• $location – Accesses and manipulates browser URL.
• $timeout – Executes a function after a delay.
• $interval – Repeats a function at specified intervals.
• $log – Logs messages to the console.
1. $http Service (AJAX & API Requests)
Used for making HTTP requests to fetch/send data
from/to a server.
Example: Fetch data using $[Link]()
[Link]('HttpController', function($scope,
$http) {

$[Link]('[Link]
posts')
.then(function(response) {
$[Link] = [Link];
}, function(error) {
[Link]("Error fetching data", error);
});
});
3. $timeout Service (Execute After Delay)
• Executes a function after a given time.
Example:
[Link]('TimeoutController',
function($scope, $timeout) {
$[Link] = "Loading...";

$timeout(function() {
$[Link] = "Data Loaded!";
}, 3000);
});
4. $interval Service (Repeated Execution)
• Runs a function at regular intervals.
Example:
[Link]('IntervalController', function($scope,
$interval) {
$[Link] = 0;

var stop = $interval(function() {


$[Link]++;
}, 1000);

$[Link] = function() {
$[Link](stop);
};
});
5. $log Service (Logging)
Provides logging methods like log(), warn(), info(),
and error().
Example:
[Link]('LogController', function($scope,
$log) {
$[Link]("This is a log message.");
$[Link]("This is an info message.");
$[Link]("This is a warning message.");
$[Link]("This is an error message.");
});
2. $q Service (Promise Handling)
Used to manage asynchronous operations with promises.
Example: Handling Promises
[Link]('asyncService', function($q, $timeout) {
return {
getData: function() {
var deferred = $[Link]();
$timeout(function() {
[Link]("Data Loaded!");
}, 2000);
return [Link];
}
};
});
[Link]('PromiseController', function($scope, asyncService) {
[Link]().then(function(data) {
$[Link] = data;
});
});
6. $location Service (URL Manipulation)
Used to read and modify the browser's URL.
Example:
[Link]('LocationController', function($scope,
$location) {
$[Link] = $[Link]();
});
7. $rootScope Service (Global Scope)
A parent scope available throughout the application.
Example:
[Link](function($rootScope) {
$[Link] = "My AngularJS App";
});
[Link]('MainController', function($scope) {
$[Link] = "Welcome!";
});
8. $window Service (Browser Window)
• Provides access to browser window properties and methods.
Example:
[Link]('WindowController', function($scope,
$window) {
$[Link] = function() {
$[Link]("Hello from AngularJS!");
};
});
9. $document Service (DOM Manipulation)
Provides access to the document object.
Example:
[Link]('DocumentController', function($scope,
$document) {
$[Link]('body').css('background-color', '#f4f4f4');
});
10. $filter Service (Data Formatting)
• Applies filters to transform data.
Example:
[Link]('FilterController',
function($scope, $filter) {
var date = new Date();
$[Link] = $filter('date')(date,
'dd-MM-yyyy');
});
11. $route Service (Routing)
• Enables single-page application (SPA) routing (requires
ngRoute module).
Example:
var app = [Link]('myApp', ['ngRoute']);
[Link](function($routeProvider) {
$routeProvider
.when('/home', {
template: '<h1>Home Page</h1>'
})
.when('/about', {
template: '<h1>About Page</h1>'
})
.otherwise({
redirectTo: '/home'
});
});
12. $resource Service (RESTful API Communication)
• Requires ngResource module to work with RESTful
APIs.
Example:
var app = [Link]('myApp', ['ngResource']);
[Link]('PostService', function($resource) {
return
$resource('[Link]
:id', {id: '@id'});
});
[Link]('ResourceController', function($scope,
PostService) {
$[Link] = [Link](); // Fetch all posts
});
Table
Creating a table in AngularJS with various features like
data population, filtering, sorting, uppercase
transformation, and displaying the index ($index) can
be done using AngularJS directives and built-in filters.
1. Populate and Display Data in a Table
In AngularJS, we use ng-repeat to loop through an array of
objects and display the data inside a table.
The controller holds an array of objects (e.g., a list of
people).The ng-repeat directive iterates over this array and
dynamically generates table rows (<tr>).
Example <table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr ng-repeat="person in people">
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
</table>
Controller (JavaScript)
var app = [Link]('myApp', []);

[Link]('TableController', function($scope) {
$[Link] = [
{ id: 1, name: 'A', age: 25 },
{ id: 2, name: 'B', age: 30 },
{ id: 3, name: 'C', age: 28 }
];
});
2. AngularJS In-Built Filter (filter)
AngularJS provides the filter service to search and filter data
dynamically in the table.
The filter filter allows us to display only the rows that match
the search [Link] ng-model directive binds the input
field to a variable, which is then used inside the filter.
Example
<input type="text" ng-model="searchText" placeholder="Search by name">
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr ng-repeat="person in people | filter: { name: searchText }">
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr></table>
3. Sort Table with orderBy Filter
• Sorting is achieved using the orderBy filter,
allowing users to sort table data by clicking a
button.
• The orderBy filter sorts the data based on a
selected column.
• The reverse flag is used to toggle ascending /
descending order.
<button ng-click="sortColumn='name'; reverse=!reverse">Sort by
Name</button>
<button ng-click="sortColumn='age'; reverse=!reverse">Sort by
Age</button>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr ng-repeat="person in people | orderBy:sortColumn:reverse">
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
</table>
Clicking "Sort by Name" sorts names alphabetically.
Clicking "Sort by Age" sorts ages numerically.
The reverse flag toggles sorting between ascending and descending.
4. Display Table with uppercase Filter
To convert text to uppercase, we use the uppercase filter.
• AngularJS provides a uppercase filter that transforms text inside an
expression ({{ }}).
• This is useful when we want names or any text to always appear in
uppercase.
Example
<table border="1">
<tr>
<th>ID</th>
<th>Name (Uppercase)</th>
<th>Age</th>
</tr>
<tr ng-repeat="person in people">
<td>{{ [Link] }}</td>
<td>{{ [Link] | uppercase }}</td>
<td>{{ [Link] }}</td>
</tr>
</table>
5. Display Table Index ($index)
• AngularJS provides a special variable $index, which represents the current index
of an item in an array.
• The $index variable inside ng-repeat helps to display the row number in the
table.
• Since $index starts from 0, adding +1 makes it start from 1.
Example
<table border="1">
<tr>
<th>Index</th>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr ng-repeat="person in people">
<td>{{ $index + 1 }}</td> <!-- Starts from 1 instead of 0 -->
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
</table>
Select Box (Dropdown)
1. Basic Select Box Using ng-model
• The ng-model directive is used to bind the selected
value of the dropdown to a scope variable.
Example
<select ng-model="selectedOption">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<p>Selected Value: {{ selectedOption }}</p>
2. Dynamic Select Box Using ng-repeat
• If you have a list of items in your AngularJS
controller, you can populate a select box
dynamically using ng-repeat.
Example
<select ng-model="selectedPerson">
<option ng-repeat="person in people" value="{{
[Link] }}">{{ [Link] }}</option>
</select>

<p>Selected ID: {{ selectedPerson }}</p>


Controller (JavaScript)
var app = [Link]('myApp', []);
[Link]('DropdownController',
function($scope) {
$[Link] = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
});
3. Using ng-options for Better Performance
• Instead of using ng-repeat, AngularJS provides the
ng-options directive, which is more efficient.
Example
<select ng-model="selectedPerson" ng-
options="[Link] as [Link] for person in
people">
<option value="">Select a person</option> <!--
Default option -->
</select>

<p>Selected Person ID: {{ selectedPerson }}</p>


4. Preselecting a Default Value
• You can preselect an option by setting a default
value in the controller.
Example
<select ng-model="selectedPerson" ng-
options="[Link] as [Link] for person in
people">
</select>

<p>Selected Person ID: {{ selectedPerson }}</p>


Controller
$[Link] = 2; // Preselect Bob
5. Using Objects as Values in ng-options
• Instead of selecting only an ID, you can store the entire
object.
Example
<select ng-model="selectedPerson" ng-options="person
as [Link] for person in people">
</select>

<p>Selected Person Name: {{ [Link]


}}</p>
<p>Selected Person Age: {{ [Link] }}</p>
Controller
$[Link] = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 28 }
];
6. Handling Empty or Default Option
• If you want an empty option as a placeholder, simply
include:
<option value="">-- Select a Person --</option>
7. Disable an Option in a Select Box
• You can disable specific options using ng-disabled.
Example
<select ng-model="selectedPerson">
<option ng-repeat="person in people" value="{{
[Link] }}" ng-disabled="[Link] == 2">
{{ [Link] }}
</option>
</select>
Forms
1. Basic Form with ng-model
• AngularJS uses ng-model to bind form inputs to a
variable in $scope.
Example
<form>
<label>Name:</label>
<input type="text" ng-model="[Link]">

<label>Email:</label>
<input type="email" ng-model="[Link]">

<p>Your Name: {{ [Link] }}</p>


<p>Your Email: {{ [Link] }}</p>
</form>
2. Form Submission with ng-submit
• The ng-submit directive is used to handle form submission.
Example
<form ng-submit="submitForm()">
<label>Name:</label>
<input type="text" ng-model="[Link]" required>

<label>Email:</label>
<input type="email" ng-model="[Link]" required>

<button type="submit">Submit</button>
</form>

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


Controller (JavaScript)
var app = [Link]('myApp', []);
[Link]('FormController', function($scope) {
$[Link] = {};
$[Link] = function() {
$[Link] = "Form submitted
successfully!";
};
});
Checkbox, Radio Buttons, and Select
Box in Forms
Checkbox (ng-model)
<label>
<input type="checkbox" ng-model="[Link]"> I
agree to the terms.
</label>
<p>Checkbox Value: {{ [Link] }}</p>
Radio Buttons (ng-model)
<label><input type="radio" ng-model="[Link]"
value="Male"> Male</label>
<label><input type="radio" ng-model="[Link]"
value="Female"> Female</label>
<p>Selected Gender: {{ [Link] }}</p>
Select Box (ng-model + ng-options)
<select ng-model="[Link]" ng-options="country for
country in countries">
<option value="">Select a Country</option>
</select>
<p>Selected Country: {{ [Link] }}</p>

Reset Form Using ng-click


<button type="button" ng-click = "resetForm()“ > Reset
</button>
Controller
$[Link] = function() {
$[Link] = {}; // Reset user data
$[Link].$setPristine(); // Reset validation state
};
EVENTS
• AngularJS provides event handling mechanisms
through directives such as ng-click, ng-show, ng-
hide, and other event listener directives.
1. The ng-click Directive
• The ng-click directive is used to handle click
events in AngularJS.
Example: Handling a Click Event
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>ng-click Example</title>
<script
src="[Link]
script>
</head>
<body ng-controller="myController">
<button ng-click="showMessage()">Click Me</button>
<p>{{ message }}</p>
<script>
var app = [Link]("myApp", []);
[Link]("myController", function($scope) {
$[Link] = function() {
$[Link] = "Button Clicked!";
};
});
</script>
</body>
</html>
2. Showing HTML Elements Using ng-show
• The ng-show directive conditionally displays an
element based on a Boolean expression.
Example: Show a Message on Button Click
<button ng-click="isVisible = true">Show
Message</button>
<p ng-show="isVisible">Hello, this message is now
visible!</p>
• Clicking the button sets isVisible to true, making
the paragraph visible.
3. Hiding HTML Elements Using ng-hide
• The ng-hide directive hides an element based on a
boolean expression.
Example: Hide a Message on Button Click
<button ng-click="isHidden = true">Hide
Message</button>
<p ng-hide="isHidden">This message will disappear
when you click the button.</p>
• Clicking the button sets isHidden to true, hiding
the paragraph.
4. AngularJS Event Listener Directives
AngularJS provides several event directives for handling
user interactions.
Example: Keypress Event (ng-keypress)
<input type="text" ng-
keypress="showKey($event)">
<p>You pressed: {{ keyPressed }}</p>
<script>
var app = [Link]("myApp", []);
[Link]("myController", function($scope)
{
$[Link] = function(event) {
$[Link] =
[Link]([Link]);
};
});
</script>
Validations
1. Form Validation Using HTML5
• HTML5 provides built-in validation attributes like required, type,
minlength, maxlength, and pattern.
Example: HTML5 Form Validation
<form name="myForm" novalidate>
<label>Name:</label>
<input type="text" name="username" ng-model="[Link]" required>
<span class="error" ng-
show="[Link].$[Link]">Name is required.</span>
<br><br>
<label>Email:</label>
<input type="email" name="email" ng-model="[Link]" required>
<span class="error" ng-show="[Link].$[Link]">Email is
required.</span>
<span class="error" ng-show="[Link].$[Link]">Invalid email
format.</span>
<br><br>
<button type="submit" ng-
disabled="myForm.$invalid">Submit</button>
</form>
2. Form Validation Using $dirty, $valid, $invalid,
$pristine
• AngularJS provides form states to track input
changes and validation.
Key Form Properties:
$dirty
• Becomes true when the user modifies the input.
• Initially false when the form loads.
• Useful for showing validation errors only after the user has
interacted with the field.
Example:
<span class="error" ng-show="[Link].$dirty &&
[Link].$invalid">
Name is required.
</span>
$pristine
• Opposite of $dirty: It remains true until the user interacts
with the input.
• Becomes false once the user types something in the field.
Example:
<p>Form Pristine: {{ myForm.$pristine }}</p>
$valid
• true if all validation rules are met for the input.
• false if the field contains invalid data.
Example:
<span class="valid" ng-show="[Link].$valid">✔
Valid</span>
invalid
• true when the input fails validation.
• false when the input meets all requirements.
Example:
<span class="error" ng-show="[Link].$dirty &&
[Link].$invalid">
Invalid email format.
</span>
Real-time Form State Tracking
<p>Form Valid: {{ myForm.$valid }}</p>
<p>Form Dirty: {{ myForm.$dirty }}</p>
<p>Form Pristine: {{ myForm.$pristine }}</p>
Disabling the Submit Button Until Valid
<button ng-disabled="myForm.$invalid“>
Submit</button>
<form name="myForm" novalidate>
<label>Username:</label>
<input type="text" name="username" ng-model = “ user.
name " required>
<span class="error" ng-show="[Link].$dirty &&
[Link].$invalid">
Name is required.
</span>
<br><br>
<p>Form Valid: {{ myForm.$valid }}</p>
<p>Form Dirty: {{ myForm.$dirty }}</p>
<p>Form Pristine: {{ myForm.$pristine }}</p>
<button ng-disabled="myForm.$invalid">Submit</button>
</form>
3. Form Validation Using AngularJS Auto-Validate
• AngularJS has third-party auto-validation
libraries like angular-auto-validate.
Steps to Use angular-auto-validate
[Link] AngularJS and [Link]
project:
<script
src="[Link]
js/1.8.2/[Link]"></script>
<script
src="[Link]
auto-validate/1.19.1/jcs-auto-
[Link]"></script>
[Link] auto-validation in AngularJS: javascript
var app = [Link]("myApp", ['jcs-
autoValidate']);
[Link] a simple form with auto-validation:
<form name="myForm">
<label>Email:</label>
<input type="email" name="email" ng-
model="[Link]" required>
<br><br>
<button type="submit">Submit</button>
</form>
4. User Feedback with Ladda Buttons
• Ladda buttons provide loading indicators for actions
like form submission.
Steps to Use Ladda Buttons in AngularJS
[Link] Ladda CSS & JS files:
<link rel="stylesheet"
href="[Link]
.0.6/[Link]">
<script
src="[Link]
0.6/[Link]"></script>
<script
src="[Link]
0.6/[Link]"></script>
2. Modify the AngularJS Controller:
var app = [Link]("myApp", []);
[Link]("myController", function($scope,
$timeout) {
$[Link] = function() {
var l =
[Link]([Link]('.ladda-button'));
[Link]();
$timeout(function() {
[Link]();
alert("Form submitted!");
}, 2000);
};
});
[Link] Ladda Button in HTML Form:
<form name="myForm" ng-
controller="myController">
<label>Name:</label>
<input type="text" name="name" ng-
model="[Link]" required>
<br><br>
<button class="ladda-button" data-
style="expand-left" ng-click="submitForm()">
<span class="ladda-label">Submit</span>
</button>
</form>

You might also like