0% found this document useful (0 votes)
4 views26 pages

Module 5 Advance AngularJs

The document provides an overview of AngularJS services, including built-in services such as $http, $location, and $timeout, as well as how to create custom services using Factory, Service, and Provider methods. It also covers displaying data in tables, using select boxes, form creation with data binding and validation, and the importance of client-side validation in AngularJS applications. Examples of code snippets illustrate the practical implementation of these concepts in AngularJS.

Uploaded by

tune7549
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)
4 views26 pages

Module 5 Advance AngularJs

The document provides an overview of AngularJS services, including built-in services such as $http, $location, and $timeout, as well as how to create custom services using Factory, Service, and Provider methods. It also covers displaying data in tables, using select boxes, form creation with data binding and validation, and the importance of client-side validation in AngularJS applications. Examples of code snippets illustrate the practical implementation of these concepts in AngularJS.

Uploaded by

tune7549
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

Events

Services
Angular Service Service is a function or an object, which is used to provide with a specified action. In
AngularJS, there are about 30 builtin services, such as $http, $location, $interval and $timeout.

Types of Services in AngularJS

AngularJS provides several built-in services and also allows you to create custom services. Here are
some commonly used built-in services:

1. $http: For making AJAX requests.


2. $location: For handling URL manipulation.
3. $timeout: For delaying code execution.
4. $interval: For repeated execution at specified intervals.
5. $q: For promise-based asynchronous operations.
6. $rootScope: For sharing data across the entire app.

Creating a Custom Service

Custom services can be created using:

1. Factory
2. Service
3. Provider

1. Using Factory

A factory function returns an object or a function that is injected where needed.


Example:

javascript
Copy code
[Link]('mathService', function() {
return {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};
});

Usage in a Controller:

javascript
Copy code
[Link]('mathController', function($scope, mathService) {
$[Link] = [Link](10, 5); // 15
$[Link] = [Link](10, 5); // 5
});

2. Using Service

A service in AngularJS is a constructor function. AngularJS instantiates this function with the new
keyword.

Example:

javascript
Copy code
[Link]('greetService', function() {
[Link] = function(name) {
return "Hello, " + name + "!";
};
});

Usage in a Controller:

javascript
Copy code
[Link]('greetController', function($scope, greetService) {
$[Link] = [Link]("John");
});
3. Using Provider

A provider gives you the most control over service creation. It is used when you need to configure a
service before making it available.

Example:

javascript
Copy code
[Link]('messageService', function() {
var prefix = '';

[Link] = function(value) {
prefix = value;
};

this.$get = function() {
return {
getMessage: function(message) {
return prefix + " " + message;
}
};
};
});

// Configure the provider


[Link](function(messageServiceProvider) {
[Link]('Hello');
});

[Link]('messageController', function($scope, messageService) {


$[Link] = [Link]('AngularJS');
});

Built-in AngularJS Services

1. $http (For AJAX requests)

Used to communicate with a server.

Example:

javascript
Copy code
[Link]('httpController', function($scope, $http) {
$[Link]('[Link]
.then(function(response) {
$[Link] = [Link];
});
});

2. $timeout (For Delayed Execution)

Executes a function after a delay.

Example:

javascript
Copy code
[Link]('timeoutController', function($scope, $timeout) {
$[Link] = "Waiting...";
$timeout(function() {
$[Link] = "Hello, after 3 seconds!";
}, 3000);
});

3. $interval (For Repeated Execution)

Executes a function repeatedly at a specified time interval.

Example:

javascript
Copy code
[Link]('intervalController', function($scope, $interval) {
$[Link] = 0;
$interval(function() {
$[Link]++;
}, 1000);
});

4. $q (For Promises)

Handles asynchronous operations.

Example:

javascript
Copy code
[Link]('promiseController', function($scope, $q) {
function asyncTask(success) {
var deferred = $[Link]();
setTimeout(function() {
if (success) {
[Link]('Task succeeded!');
} else {
[Link]('Task failed!');
}
}, 2000);
return [Link];
}

var promise = asyncTask(true);


[Link](function(successMessage) {
$[Link] = successMessage;
}).catch(function(errorMessage) {
$[Link] = errorMessage;
});
});

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

Displaying Data in a Table

Displaying tables with angular is very simple:

<!DOCTYPE html>

<html>

<script src="[Link]

<body>

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

<table>

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


<td>{{ [Link] }}</td>

<td>{{ [Link] }}</td>

</tr>

</table>

</div>

<script>

var app = [Link]('myApp', []);

[Link]('customersCtrl', function($scope, $http) {

$[Link]("[Link]")

.then(function (response) {$[Link] = [Link];});

});

</script>

</body>

</html>

Display with orderBy Filter

To sort the table, add an orderBy filter:

AngularJS Example
<table>
<tr ng-repeat="xinnames|orderBy:'Country'">
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
</tr>
</table>
Display with uppercase Filter

To display uppercase, add an uppercase filter:


AngularJS Example
<table>
<tr ng-repeat="xinnames">
<td>{{[Link]}}</td>
<td>{{[Link]|uppercase}}</td>
</tr>
</table>

Display the Table Index ($index)

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

AngularJS Example
<table>
<tr ng-repeat="xinnames">
<td>{{$index+1}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
</tr>
</table>

Using $even and $odd


<table>
<tr ng-repeat="xinnames">
<td ng-if="$odd" style="background-color:#f1f1f1">{{[Link]}}</td>
<td ng-if="$even">{{[Link]}}</td>
<td ng-if="$odd" style="background-color:#f1f1f1">{{[Link]}}</td>
<td ng-if="$even">{{[Link]}}</td>
</tr>
</table>

Select box:-
AngularJS Select
In AngularJS, you can create a dropdown list (select box) based on items in an array, or an object.
Using ng-options
You should use the ng-option directive to create a dropdown list, based on an object or an array in
AngularJS.

See this example:

<!DOCTYPE html>
<html>
<script src="[Link]
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names">
</select>
</div>
<script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope) {
$[Link] = ["Java", "PHP", ".Net", "AngularJS", "C/C++"];
});
</script>
</body>
</html>

You can also use the ng-repeat directive to make the same dropdown list as ng-options.

<!DOCTYPE html>
<html>
<script src="[Link]
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select>
<option ng-repeat="x in names">{{x}}</option>
</select>
</div>
<script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope) {
$[Link] = ["Java", "PHP", ".Net", "AngularJS", "C/C++"];
});
</script>
<p>The same example of dropdown list using the ng-repeat directive.</p>
</body>
</html>

ng-options vs. ng-repeat


Although, both can be used for dropdown list, but 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, while the ng-options
directive was made especially for filling a dropdown list with options, and has at least one important
advantage:

Limitation of ng-repeat
The ng-repeat directive has a limitation that the selected value must be a string:

While using the ng-options directive, you can select an object value:

Form:-
AngularJS facilitates you to create a form enriches 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 controls together.

Following are the input controls used in AngularJS forms:

o input elements
o select elements
o button elements
o textarea elements
AngularJS provides multiple events that can be associated with the HTML controls. These events are
associated with the different HTML input elements.

Data-Binding

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

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

The application does now have a property named firstname.

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

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


Example
<script>
var app=[Link]('myApp',[]);
[Link]('formCtrl', function($scope){
$[Link] = "John";
});
</script>

It can also be referred to elsewhere in the application:

Example
<form>
FirstName: <input type="text" ng-model="firstname">
</form>

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

Checkbox

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

Example

Show the header if the checkbox is checked:

<form>
Check_to_show_a_header:
<input type="checkbox" ng-model="myVar">
</form>

<h1 ng-show="myVar">My Header</h1>

Radiobuttons

Bind radio buttons to your application with the ng-model directive.


Radio buttons with the same ng-model can have different values, but only the selected one will be used.

Example

Display some text, based on the value of the selected radio button:

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

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

Selectbox

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

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

Example

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

<form>
Select_a_topic:
<select ng-model="myVar">
<option value="">
<option value="dogs">Dogs
<option value="tuts">Tutorials
<option value="cars">Cars
</select>
</form>

Example:-

<!DOCTYPE html>
<html lang="en">
<script src="[Link]
<body>

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


<form novalidate>
First Name:<br>
<input type="text" ng-model="[Link]"><br>
Last Name:<br>
<input type="text" ng-model="[Link]">
<br><br>
<button ng-click="reset()">RESET</button>
</form>
<p>form = {{user}}</p>
<p>master = {{master}}</p>
</div>

<script>
var app = [Link]('myApp', []);
[Link]('formCtrl', function($scope) {
$[Link] = {firstName:"John", lastName:"Doe"};
$[Link] = function() {
$[Link] = [Link]($[Link]);
};
$[Link]();
});
</script>

</body>
</html>
Output:-

FirstName:

LastName:
RESET

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

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

Validations:-
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>{{[Link].$valid}}</h1>
E-mail

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

Example

The input field has to be an e-mail:

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

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


<h1>{{[Link].$valid}}</h1>
Custom Validation

To create your own validation function is a bit more tricky; You have to add a new directive to your
application, and deal with the validation inside a function with certain specified arguments.

Example

Create your own directive, containing a custom validation function, and refer to it by
using my-directive.

The field will only be valid if the value contains the character "e":

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

<script>
var app = [Link]('myApp', []);
[Link]('myDirective', function() {
return {
require: 'ngModel',
link: function(scope, element, attr, mCtrl) {
function myValidation(value) {
if ([Link]("e") > -1) {
mCtrl.$setValidity('charE', true);
} else {
mCtrl.$setValidity('charE', false);
}
return value;
}
mCtrl.$[Link](myValidation);
}
};
});

</script>
Example Explained:

In HTML, the new directive will be referred to by using the attribute my-directive.

In the JavaScript we start by adding a new directive named myDirective.

Remember, when naming a directive, you must use a camel case name, myDirective, but when
invoking it, you must use - separated name, my-directive.

Then, return an object where you specify that we require ngModel, which is the ngModelController.

Make a linking function which takes some arguments, where the fourth argument, mCtrl, is
the ngModelController,

Then specify a function, in this case named myValidation, which takes one argument, this argument is
the value of the input element.

Test if the value contains the letter "e", and set the validity of the model controller to either true or false.

At last, mCtrl.$[Link](myValidation); will add the myValidation function to an array of other


functions, which will be executed every time the input value changes.

You might also like