What is an AngularJS service or factory?
Singleton.
Yes! That one word is enough to define AngularJS services. The purpose of AngularJS service / factory function is to generate a single object or function that represents the service to rest of the application.
An AngularJS service can be created or registered or created in four different ways,
Using the service() method
Using the factory() method
Using the provider() method
Using the value() method
Using the constant() method
For example, here we are saying, we want to create a module called CalculatorService, which uses no other modules, hence the empty array parameter. This module has a service called Calculator, which has a function to square a number a. The result square will be a property for this singleton.
1 2 3 4 5 |
var CalculatorService = angular.module('CalculatorService', []) .service('Calculator', function () { this.square = function (a) { return a*a}; }); |
That object or function is passed as a parameter to any other factory function which specifies a dependency on this service.
mainCtrl.js
Notice the name Calculator declared in module CalculatorService, and used here as a parameter to inject dependency from the controller to the service.
1 2 3 4 5 6 7 |
var myApp = angular.module('myApp', ['CalculatorService']); myApp.controller('CalculatorController', function ($scope, Calculator) { $scope.findSquare = function () { $scope.answer = Calculator.square($scope.number); } }); |
On the view we are using the controller to do the data binding as shown below,
Enter a number:
{{answer}}Let us understand difference between creating a service using the service() method and the factory() method.
Using the service() method uses the function constructor and it returns the object or instance of the function to work with
Using the factory() method uses the returned value of the function. It returns the value of the function returned after the execution