I thought I understood the difference between Factories and Services fairly clearly. I made the assumption that factories, by their name, were useful for pumping out new instances of objects every time you asked for them. I also held the belief that services were simply a nomenclature for defining a set of utility functions for tracking state or some sort of data.
Well, forget what I just said, because I had it wrong. Factories and services are actually pretty similar in functionality (assuming I'm not getting it wrong yet again). They both serve the purpose of instantiating a singleton object; something that you're going to use as a single instance throughout your page lifecycle.
The main difference between factories and services is how you define them. Services should build off of the this
object. Factories should return a custom object with functionality attached to it.
Service:
angular.module('app', [])
.service('panicButton', function () {
this.isPressed = false;
this.panic = function () {
this.isPressed = true;
console.log('panicking');
};
})
.controller('controlPanel', function (panicButton) {
panicButton.panic(); // logs -> 'panicking'
});
Factory:
angular.module('app', [])
.factory('panicButton', function () {
var isPressed = false;
return {
panic: function () {
isPressed = true;
console.log('panicking');
}
};
})
.controller('controlPanel', function ($scope, panicButton) {
panicButton.panic(); // logs -> 'panicking'
});
I think the biggest reason I had trouble understanding all of this is that the naming scheme isn't the clearest. As I said, I made the assumption that 'Factory' meant 'pumping out objects'. And while this is true, it's not true in the way I thought it was.