In angular services are singletons, which means there is only ONE instance of that service. There are cases where you would want unique instances of objects. This is where the Factory Pattern comes in handy.
https://en.wikipedia.org/wiki/Factory_method_pattern
Within angular this pattern can most easily be seen with the $resource factory. With the $resource factory you request a unique instance of a resource.
In Angular services are classes. They are constructor functions. But only one instance is ever newed up. So a factory allows you to new instances as needed.
// my service
function Foo(fooId) {
this.id = fooId;
}
function fooFactory() {
return function(id) {
return new Foo(id);
}
}
angular.module('app').factory('foo', fooFactory);
So in the above if we delete the factory and just bind Foo to the DI container with angular.module('app').service('foo', Foo) -- what will happen? Every instance of Foo will have the same id. But with this factory, we can set the id when we create the instance.
So why use the factory and not just new up the instance by myself? Testability. Your code is not testable if you new up your classes (yes a constructor is just a class, in a sense) in your services or controllers.
Do you need this? Probably not for much.
You should just use services.
function Bar($http, $timeout) {
this.$http = $http;
this.$timeout = $timeout;
}
Bar.prototype.doSomething = function(value) {
return this.$http.get('/api/dosomthing', {value: value});
}
angular.module('app').service('bar', Bar);