Angular service or factory

What is an AngularJS service or factory?


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.

That object or function is passed as a parameter to any other factory function which specifies a dependency on this service.


Notice the name Calculator declared in module CalculatorService, and used here as a parameter to inject dependency from the controller to the service.

On the view we are using the controller to do the data binding as shown below,