As stated in the Angular documentation,
Note: In Angular, all services are treated as singletons. This means that each service is only created once by the injector, and then a reference to that object is cached for future use.
When you define a factory in Angular, you are essentially declaring an object that will be returned and injected using dependency injection.
This concept is also explained in the documentation for services
here :
Angular services are:
- Lazily instantiated – Angular only creates a service when it is needed by a component in the application.
- Singletons – Each component that depends on a service receives a reference to the same instance created by the service factory.
Edit:
From a JavaScript
perspective, this is similar to copying an Object
by reference, for example:
var obj1 = {name: 'Alex', id: 2};
var obj2 = obj1;
console.log(obj1.name) // 'Alex'
console.log(obj2.name) // 'Alex'
obj2.name = 'Max';
console.log(obj2.name) // 'Max'
console.log(obj1.name) // 'Max'
In Angular, you can observe the same behavior by:
.factory('myfactory', ['$q', function ($q) {
return {
someArray: [1, 2]
}
}])
and then in controllers:
.controller('ctrl1', ['$scope', 'myfactory', function ($scope, myfactory) {
myfactory.someArray[0] = 100500;
})
.controller('ctrl2', ['$scope', 'myfactory', function ($scope, myfactory) {
console.log(myfactory.someArray[0]); /* if this controller is initialized after 'ctrl1' - you will see in console '100500' instead of '1' */
})
Additionally, .factory()
is a function that returns an Object
. In Angular, when you inject a service, the .factory()
callback is executed only once to create an instance of the returned object. Angular then provides only a single instance of this Object
throughout the application, not multiple copies.
I hope this clears things up for you.