Here are some more examples of services vs factories which may be useful in seeing the difference between them. Basically, a service has "new ..." called on it, it is already instantiated. A factory is not instantiated automatically.
Here is a service that has a single method:
angular.service('Hello', function () {
this.sayHello = function () { /* ... */ };
});
Here is a factory that returns an object with a method:
angular.factory('ClassFactory', function () {
return {
sayHello: function () { /* ... */ }
};
});
A factory that returns a list of numbers:
angular.factory('NumberListFactory', function () {
return [1, 2, 3, 4, 5];
});
console.log(NumberListFactory);
A service that returns a list of numbers:
angular.service('NumberLister', function () {
this.numbers = [1, 2, 3, 4, 5];
});
console.log(NumberLister.numbers);
The output in both cases is the same, the list of numbers.
In this example we define a CounterFactory, it increments or decrements a counter and you can get the current count or get how many CounterFactory objects have been created:
angular.factory('CounterFactory', function () {
var number_of_counter_factories = 0; // class variable
return function () {
var count = 0; // instance variable
number_of_counter_factories += 1; // increment the class variable
// this method accesses the class variable
this.getNumberOfCounterFactories = function () {
return number_of_counter_factories;
};
this.inc = function () {
count += 1;
};
this.dec = function () {
count -= 1;
};
this.getCount = function () {
return count;
};
}
})
We use the CounterFactory
to create multiple counters. We can access the class variable to see how many counters were created:
var people_counter;
var places_counter;
people_counter = new CounterFactory();
console.log('people', people_counter.getCount());
people_counter.inc();
console.log('people', people_counter.getCount());
console.log('counters', people_counter.getNumberOfCounterFactories());
places_counter = new CounterFactory();
console.log('places', places_counter.getCount());
console.log('counters', people_counter.getNumberOfCounterFactories());
console.log('counters', places_counter.getNumberOfCounterFactories());
The output of this code is:
people 0
people 1
counters 1
places 0
counters 2
counters 2