Home > Article > Web Front-end > Introduction to the methods of using factory and service in AngularJS_AngularJS
AngularJS supports the concept of "separation of concerns" in an architecture using services. Services are JavaScript functions and are responsible for doing only one specific task. This also makes them separate entities for maintenance and testing. Controllers, filters can call them as a basis for requirements. Services are injected normally using AngularJS's dependency injection mechanism.
AngularJS provides many intrinsic services, such as: $http, $route, $window, $location, etc. Each service is responsible for a specific task, for example $http is used to create AJAX calls to get data from the server. $route is used to define routing information, etc. Built-in services are always prefixed with a $ sign.
There are two ways to create a service.
Use factory method
Using factory methods, we first define a factory and then assign methods to it.
var mainApp = angular.module("mainApp", []); mainApp.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b } return factory; });
Use service method
Using service methods, we define a service and then assign methods. Also inject already available services.
mainApp.service('CalcService', function(MathService){ this.square = function(a) { return MathService.multiply(a,a); } });
Example
The following example will demonstrate all the above commands.
testAngularJS.html
Angular JS Forms AngularJS Sample Application
<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>Enter a number:
Result: {{result}}
Results
Open textAngularJS.html in your web browser. See the results below.