”;
AngularJS supports the concept of Separation of Concerns using services architecture. Services are JavaScript functions, which are responsible to perform only specific tasks. This makes them individual entities which are maintainable and testable. The controllers and filters can call them on requirement basis. 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 −
- Factory
- Service
Using Factory Method
In this method, we first define a factory and then assign method to it.
var mainApp = angular.module("mainApp", []); mainApp.factory(''MathService'', function() { var factory = {}; factory.multiply = function(a, b) { return a * b } return factory; });
Using Service Method
In this method, we define a service and then assign method to it. We also inject an already available service to it.
mainApp.service(''CalcService'', function(MathService) { this.square = function(a) { return MathService.multiply(a,a); } });
Example
The following example shows use of all the above mentioned directives −
testAngularJS.htm
<html> <head> <title>Angular JS Services</title> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "CalcController"> <p>Enter a number: <input type = "number" ng-model = "number" /></p> <button ng-click = "square()">X<sup>2</sup></button> <p>Result: {{result}}</p> </div> <script> var mainApp = angular.module("mainApp", []); mainApp.factory(''MathService'', function() { var factory = {}; factory.multiply = function(a, b) { return a * b } return factory; }); mainApp.service(''CalcService'', function(MathService) { this.square = function(a) { return MathService.multiply(a,a); } }); mainApp.controller(''CalcController'', function($scope, CalcService) { $scope.square = function() { $scope.result = CalcService.square($scope.number); } }); </script> </body> </html>
Output
Open the file testAngularJS.htm in a web browser and see the result.
”;