AngularJS Services

1. What is a service?

Services are javascript functions and responsible for doing a specific task only.

The Angular Js has 30 inbuilt services some of them $http,$route,$location,etc....

 

2. What is $timeout Service?

The $timeout service can be used to call another javascript function after a given time delay.

<!DOCTYPE  html>
<html>
<head>
<script src="http://ajax.googleapis.com/
ajax/libs/angularjs/1.4.5/angular.min.js"></script>
</head>
<body>
<div ng-app="myFirstApp" ng-controller="myControl"> 
<p>This header will change after three seconds:</p>
<h1>{{Header}}</h1>
</div>
<script>
var myFirstApp= angular.module('myFirstApp', []);
myFirstApp.controller('myControl', 
function($scope, $timeout) {
  $scope.Header = "Hi!";
  $timeout(function () {
      $scope.Header = "How are you ?";
  }, 3000);
});
</script>
</body>
</html>

 

3. What is $interval Service?

The $interval service function is similar to $timeout function. but we can schedule a function for repeated executions in between time intervals.

<!DOCTYPE  html>
<html>
<head>
<script src="http://ajax.googleapis.com
/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-controller="myController">
        counter: <input type="text" ng-model="counter"> 
    </div>
    <script>
    function myController($scope, $interval) {
        $scope.counter = 0;
       $scope.incrementcounter = function() {
          $scope.counter  += 1;  
        }
      $interval($scope.incrementcounter, 750, 5);
	
    }
   </script>
</body>
</html>

 

4. What is $location service?

The $location service is used to return the information about the location of current web page .

<!DOCTYPE  html>
<html>
<head>
<script src="http://ajax.googleapis.com/
ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script>
var app = angular.module('myFirstApp', []);
app.controller('myController', function($scope, $location) {
    $scope.myUrl = $location.absUrl();
});
</script>
</head>
<body>
<div ng-app="myFirstApp" ng-controller="myController">
<p>The url of this page is:</p>
<h3>{{myUrl}}</h3>
</div>

<p>This example uses the inbuilt $location 
service to get the absolute url of the page.</p>

</body>
</html>