Hi rani,
AngularJS Services are JavaScript functions which are responsible to perform only specific tasks. The controllers and filters can call them when requirement. Services are normally injected using the dependency injection mechanism of AngularJS.
AngularJS provides many inbuilt services. For example, $http, $route, $window, $location, etc. Each service is responsible for a specific task such as the $http is used to make ajax call to get the server data, the $route is used to define the routing information and so on.
The inbuilt services are always prefixed with $ symbol.
There are two ways to create a service.
1. Factory
2. Service
HTML
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("MyApp", []);
app.controller("MyController", ['$scope', 'CustomerService', 'CustomerFactory', function ($scope, customerService, customerFactory) {
$scope.Customers = customerService.Customers();
$scope.Name = customerFactory.Name;
$scope.Country = customerFactory.Country;
} ]);
app.service("CustomerService", function ($http) {
this.Customers = function () {
return [{ CustomerId: 1, Name: "John Hammond", Country: "United States" },
{ CustomerId: 2, Name: "Mudassar Khan", Country: "India" },
{ CustomerId: 3, Name: "Suzanne Mathews", Country: "France" },
{ CustomerId: 4, Name: "Robert Schidner", Country: "Russia"}];
}
});
app.factory('CustomerFactory', function () {
var customer = { CustomerId: 1, Name: "John Hammond", Country: "United States" };
return customer;
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<table border="1" cellpadding="1" cellspacing="1">
<tr>
<th>Customer Id</th>
<th>Name</th>
<th>Country</th>
</tr>
<tbody ng-repeat="m in Customers">
<tr>
<td>{{m.CustomerId}}</td>
<td>{{m.Name}}</td>
<td>{{m.Country}}</td>
</tr>
</tbody>
</table>
<br />
Name : <b>{{Name}}</b>
<br />
Country : <b>{{Country}}</b>
</div>
Demo
For more details refer below links.
https://www.tutorialspoint.com/angularjs/angularjs_services.htm
https://docs.angularjs.org/guide/services