In angular JS the service is an singleton object, where we can inject the service reference name to the controller function. As it is singleton object it can be instantiated once per the application and can be accessed throughout the application.
Look of custom service creation :
var app = angular.module('apptest', [])
app.service('servicename', function () {
//return some data through function.
}
})
In the above example we can observe the service with it’s name ‘servicename’ in the first parameter and to the next parameter as an anonymous constructor function which can contain the function that returns the data to the called one.
Example on service :
var myapp = angular.module('myapp', []);
myapp.service('actions', function () {
this.add = function (val1) {
return parseInt(val1) + parseInt(val1);
}
this.sub = function (val1) {
return parseInt(val1) - parseInt(val1);;
}
});
In the above code I had just created the module named as "myapp" and then created a service to that app by using the service().'actions' is the anme of the service that which we created and within the constructor function of anaother parameter I created two functions as "add" and "sub"
In the above code if we observe, I used "this" keyword. The purpose of that keyword use is to refer that particular object. In javascript every function will internally treated as an object itsef.
Now, following is the code of controller with the dependency containing the 'actions' service :
myapp.controller('myctrl', function ($scope, actions) {
$scope.GetResult = function () {
$scope.addres = 'Addition to itself is : ' + actions.add($scope.val1);
$scope.subres = 'Substraction to itself is : ' + actions.sub($scope.val1);
}
});
In the above code we can find the controller injecting with the service 'actions' within the constructor function.
Now lets have look over the HTML code:
<body ng-app="myapp">
<div ng-controller="myctrl">
<input type="text" id="txtval" ng-model="val1" />
<input type="button" value="Get Result" ng-click="GetResult()"/> <br />
<span ng-bind="addres"></span><br />
<span ng-bind="subres"></span>
</div>
</body>
From the above code, the "GetResult()" function will be called whehever user clicks on the button.
within the GetResult() function we assigned the values of ng-bind="addres" and ng-bind="subres" by calling the services of add as "actions.add($scope.val1)" and services of sub as actions.sub($scope.val1).
Here, $scope.val1 is the vaalue that which comes from the input textbox where we used the ng-model.
Image refernce of above code :
Output :
In angular JS we are having some built-in services, where we can use based on the requirement. Some of the built-in services are as like, $filter , $location , $cookie ,.. etc.