Objectives and outcomes

In this tutorial we are going to learn about angular-js services. Services in angular-js are javascript functions which performs the specific task. These can be called by controllers and filters on requirement basis. There are many inbuilt services in angular-js for eg- $http, $route, $location, $interval, $timeout etc. Service object is passed as a second argument to controller function.



Javascript for $location service

<script>
var app = angular.module("myapp",[]);
app.controller("location_control",function($scope, $location)
{
$scope.curr_url = $location.absUrl();
});
</script>


Javascript for $interval service

<script>
var app = angular.module("myapp",[]);
app.controller('interval_control', function($scope, $interval) 
{
$scope.time_date = new Date().toLocaleTimeString();
$interval(function () 
{
$scope.time_date = new Date().toLocaleTimeString();
}, 1000);
});
</script>


Javascript for $timeout service

<script>
var app = angular.module("myapp",[]);
app.controller('timeout_control', function($scope, $timeout) 
{
$scope.content = "Welcome to codeshot.in!!";
$timeout(function () 
{
$scope.content = "Also learn jquery-ui, android and other technologies with us!!";
}, 5000);
});
</script>


Javascript for custom service

<script>
var app = angular.module("myapp",[]);
app.service("half",function()
{
this.func = function(a)
{
return (a/2);
}
});

app.controller("custom_service_control", function($scope, half)
{
$scope.func1 = function()
{
$scope.result = half.func($scope.num);
}
});
</script>


HTML code:

<html>
<head>
<meta charset="utf-8">
<title>AngularJS Services</title>
<script src="angular-1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="myapp">
    
<div ng-controller="location_control">
<p>Location service : <b>{{curr_url}}</b></p>
</div><br/>
    
<div ng-controller="interval_control">
<p>Interval service : <b>{{time_date}}</b></p>
</div><br/>
    
<div ng-controller="timeout_control">
<p>Timeout service : <b>{{content}}</b></p>
</div><br/>
    
<div ng-controller="custom_service_control">
<label>Enter a number</label>
<input type="number" ng-model="num" required><br/>
<button type="submit" ng-click="func1()">find half</button>
<p>Half of the number is : <b>{{result}}</b></p>
</div>

</div>
</body>
</html>


Location service : {{curr_url}}


Interval service : {{time_date}}


Timeout service : {{content}}




Half of the number is : {{result}}