AngularJS factory, service and providers

As per our previous article on AngularJS Services, AngularJS provides us with three ways to create and register our own service –

  1. Factory
  2. Service
  3. Provider

Basically its more about our own preferences but we will be checking out each of the approaches in more detail and how their implementations differ.

1. Factory approach

In this approach, we first create an object, add properties to it, and then return that same object. When we pass this factory into the controller, those properties on the object will now be available in that controller through factory.

2. Service approach

In this approach, AngularJS instantiates the service behind the scenes with the ‘new’ keyword. Because of that, we add properties to ‘this’ reference and the service will return ‘this’. When we pass the service into the controller, the properties on ‘this’ will now be available on that controller through service.

3. Provider approach

It is the most configurable approach through which we can create configurable services. In this case, the ‘service’ object can be passed into the config section of the application as ‘serviceProvider’, so the service object can be better initialized before being used elsewhere in the application.

I hope the below snippet further clarifies out everything.

For any queries, please share them as comments.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.