Monday , February 27 2017
Home / angularjs / Angularjs Services Example Tutorials

Angularjs Services Example Tutorials

AngularJs Services are the reusable components, which can be used across the multiple controllers. AngularJs given a set of built-in services to perform require operations.

What is AngularJs Services :

  • A service is a reusable component, which can be use across the multiple controllers.
  • AngularJs service is a function or an object, it can be used by the AngularJs application.
  • A service is defined for a specific task. It should be an independent component, so that it can be maintainable and easily testable.
  • An Angular Service can have variables and functions in it.
  • AngularJs services can define the instance members by using the this keyword.
  • Controllers and filters can use services based on their requirement and the service can inject using the dependency injection in AngularJs.

Popular Services in AngularJS :

AngularJs provides about 30 different services, in which here we have discussed most used and suggested services;

$timeout Service :

The $timeout service can be used to call the another javascript function after a specific time. Here is the example to sessiontime out example;


<!DOCTYPE html>
<html>
<script
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

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

        <p>Welcome to AngularJs Services</p>

        <h1>Hello World</h1>

    </div>

    <p>Your Session will be expired, after 60 Sec of inactive.</p>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope, $timeout) {
            $timeout(function() {
                alert("Your Session is going to expire in 57 Sec..")
            }, 3000);
        });
    </script>

</body>
</html>

$interval Service :

The $interval is something similar to $timeout service except it schedule for an interval.


<!DOCTYPE html>
<html>
<style>
#time {
    color: green;
}

#message {
    width: 750px;
    height: 250px;
    border: 2px solid green;
    padding: 5px;
}

h1 {
    color: red;
}
</style>

<script
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

    <div ng-app="myApp" ng-controller="intervalService">
        <p>
        <h2 id="time">Read this message with in the time period :
            {{secs}}</h2>
        </p>
        <div id="message">
            <i> Intervals created by this service must be explicitly
                destroyed when you are finished with them. In particular they are
                not automatically destroyed when a controller's scope or a
                directive's element are destroyed. You should take this into
                consideration and make sure to always cancel the interval at the
                appropriate moment. See the example below for more details on how
                and when to do this </i>
            <div></div>
            <script>
                var app = angular.module('myApp', []);
                app.controller('intervalService', function($scope, $interval) {
                    $scope.secs = 12;
                    $scope.theTime = new Date().toLocaleTimeString();
                    var inter = $interval(function() {
                        if ($scope.secs > 0 && $scope.secs > 0) {
                            $scope.secs = $scope.secs - 1;

                        } else {
                            $scope.stop();
                        }
                    }, 1000);

                    $scope.stop = function() {

                        if (angular.isDefined(inter)) {
                            $interval.cancel(inter);
                            inter = undefined;
                            alert("Your Time is up !");
                        }
                    };
                });
            </script>
</body>
</html>

$location service :

The $location service is used to get the current location of the browser window. This will expose the window URL like window.location.

The AngularJs API given set of getter and setter methods to manipulate the $location services. If we change the location by using the setter, the window navigates the location accordingly. Here is the example for $location service.


<!DOCTYPE html>
<html>
<script
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
    <div ng-app="myApp" ng-controller="locationController">
        <p>This example uses the built in $location services to get the
            resource informaton like url, protocal, host and port</p>
        <h3>Present Url : {{myUrl}}</h3>
        <h3>Present protocol : {{protocol}}</h3>
        <h3>Present host : {{host}}</h3>
        <h3>Present port : {{port}}</h3>
        <h3>Present path : {{path}}</h3>
    </div>
    <script>
        var app = angular.module('myApp', []);
        app.controller('locationController', function($scope, $location) {
            $scope.myUrl = $location.absUrl();
            $scope.protocol = $location.protocol();
            $scope.host = $location.host();
            $scope.port = $location.port();
            $scope.path = $location.path();

        });
    </script>
</body>
</html>

Points to Note :

host(): Returns the host name, such as localhost
port(): Returns the port where the server is listening on, such as 8080
protocol(): Returns the protocol used, such as http or https
url(): Returns the part of the URL after hostname and protocol  e.g. /demo?Qtn1=value1#div4
absUrl(): Returns the whole URL, such as http://localhost:8080/demo?Qtn1=value1#div4

$http service :

$http service is used to make AJAX calls from AngularJs application.

Create user define Services :

If you want to create your own services like above, AngularJs given a service() method to define a service.

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

AngularJs Data Binding Example

One of the important feature of AngularJs is Data Binding. Data binding makes the AngularJs …

Leave a Reply

Your email address will not be published. Required fields are marked *