Skip to content

Instantly share code, notes, and snippets.

@klamping
Last active August 29, 2015 14:07
Show Gist options
  • Save klamping/310c5d8a2aa57af33d19 to your computer and use it in GitHub Desktop.
Save klamping/310c5d8a2aa57af33d19 to your computer and use it in GitHub Desktop.
How I've Messed up in Angular

Part 1 - Factories vs. Services

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.

http://www.airpair.com/angularjs/posts/top-10-mistakes-angularjs-developers-make#5-service-vs-factory

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment