AngularJS Services

In AngularJS has a user can make an own Service or use a Built-in Services.

In AngularJS a service is a function,or an object ,that is available in an AngularJS Application.

Angular Js has Many Built in services as such $location.

This service has methods which returns a information about a location of a current web source page.

Example :

var app = angular.module('app',[ ])
app.controller("peoplesctrl") , function($scope,$location) {
$scope.myUrl = $location.absUrl(); });

An $http Service.

$http is a commonly used services in any AngularJS applications.

This service provides a request to a server then the application it self handles the response from the Server.

Example:

var app = angular.module('app',[ ])
app.controller("abcctrl") , function($scope,$http) {
$http.get("page1.htm").then(function (response) {
$scope.abcpage1 = response.data;
});
});

$timeout Service

$timeout is a service in AngularJS of an window.setTimeout function..


Here is an Example which display a message after 5 sec:

Example:

var app = angular.module('app',[ ])
app.controller("lenctrl") , function($scope,$timeout) {
$scope.myHeader ="Welcome To AngularJS Learning Sessions";
$timeout(function ()) { $scope.myHeader = "How is your practice Going on?"; },5000); });

$internal Service

$internal service AngularJS version of an window.setInterval .

Here is an Example which display a message after 2 sec:

Example:

var app = angular.module('app',[ ])
app.controller("lenctrl") , function($scope,$interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function ()) { $scope.theTime = new Date().toLocaleTimeString();; },2000); });

Creating a Service

In AngularJS in order to create a service one have to connect to a module.

Here is an example created a service with name myservice.

Example:

app.service('myservice', function() {
this.myFunc = function(A) {
return A.tostring(10);
} });

AngularJS Custom Service

If a Service is created it can be connected into your application. This service can be used in any controller, directive, other filters and even in other service also.

Example:

app.filter('myfiltername',['names1' function(names1) {
return function(A) { return Anames1.myFunc(A);
}; }]);