AngularJS Service and Factory

Updated on September 17, 2015 Kisan Patel

Services provide a method for us to keep data around for the lifetime of the app and communicate across controllers in a consistent manner.

Services are singleton objects that are instantiated only once per app and lazy-loaded (created only when necessary). They provide an interface to keep together those methods that relate to a specific function.

For example, the built-in $timeout service executes a function after a specified interval. The $http service encapsulates the logic required to interact with REST api. We ask AngularJS to inject these services into our controllers so that we can utilize them.

In above code, angular.module() provides a function service() that’s used to register a service. The first argument to this function is the service name. The second argument is a constructor function.

A factory is another injectable type. Effectively it’s the same as a service. The difference between service and factory are, with the factory you actually create an object inside of the factory and return it but with the service you just have a standard function that uses the this keyword to define function.

The most common and flexible way to create a service uses the angular.module API factory:

The factory method creates a singleton UserService, that returns two functions for retrieving all users and the first user only. The controllers get the UserService injected by adding it to the controller function as params.