The factory
method provides the capability to implement functionality into a service. It can also be dependent on other service providers, enabling you to build up compartmentalized code. The factory
method uses the following syntax, where name
is the service name and factoryProvider
is a provider function that builds the factory service:
factory(name, factoryProvider)
You can inject the factory
method with other services, and it returns the service object with the appropriate functionality. The functionality can be a complex JavaScript service, a value, or a simple function. For example, the following code implements a factory
service that returns a function that adds two numbers:
var app = angular.module('myApp', []);
app.constant('myConst', 10);
app.factory('multiplier', ['myConst', function (myConst) {
return function(value) { return value + myConst; };
}]);