AngularJS : When to use service instead of factory

Please bear with me here. I know there are other answers such as:
AngularJS: Service vs provider vs factory

However I still can’t figure out when you’d use service over factory.

From what I can tell factory is commonly used to create “common” functions that can be called by multiple Controllers: Creating common controller functions

The Angular docs seem to prefer factory over service. They even refer to “service” when they use factory which is even more confusing! http://docs.angularjs.org/guide/dev_guide.services.creating_services

So when would one use service?

Is there something that is only possible or much easier done with service?

Is there anything different that goes on behind the scenes? Performance/memory differences?

Here’s an example. Other than the method of declaration, they seem identical and I can’t figure out why I’d do one vs the other. http://jsfiddle.net/uEpkE/

Update: From Thomas’ answer it seems to imply that service is for simpler logic and factory for more complex logic with private methods, so I updated the fiddle code below and it seems that both are able to support private functions?

myApp.factory('fooFactory', function() {
    var fooVar;
    var addHi = function(foo){ fooVar="Hi "+foo; }

    return {
        setFoobar: function(foo){
            addHi(foo);
        },
        getFoobar:function(){
            return fooVar;
        }
    };
});
myApp.service('fooService', function() {
    var fooVar;
    var addHi = function(foo){ fooVar="Hi "+foo;}

    this.setFoobar = function(foo){
        addHi(foo);
    }
    this.getFoobar = function(){
        return fooVar;
    }
});

function MyCtrl($scope, fooService, fooFactory) {
    fooFactory.setFoobar("fooFactory");
    fooService.setFoobar("fooService");
    //foobars = "Hi fooFactory, Hi fooService"
    $scope.foobars = [
        fooFactory.getFoobar(),
        fooService.getFoobar()
    ];
}

9 Answers
9

Leave a Comment