Service vs. Factory in AngularJS could become very confusing for users. In general, both are singleton objects for persist/share data between different parts in our application.

[test2Service] and [test2Factory] are doing exactly the same thing, and the part which uses them, refers them exactly the same (as you can see below).

The only difference between service and factory is how AngularJS treats them when requested to inject each to AngularJS part (like controller or other services, factories).

As you can see below, the factory has to return something and service is not, that means there is more flexibility when working with factories.

Factory’s return type could be a simple object or a function, and that means we can implement the factory pattern to create a new instance every time with the new keyword.

A real life showcase using this pattern could be as implemented in the [personsService] and [Person], where [personsService] hold a list of persons and we can create a new person using the [Person] factory with the keyword new.

Here’s the full code snippet we walked through:

Looking to learn more about AngularJS for your team? Check out our custom group training options today.