0

I have seen a number of similar questions but none really gave a simple example. Here's one example of how to do something which is similar to a few other very similar examples:

//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
    this.sayHello = function() {
        return "Hello, World!"
    };
});

//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
    return {
        sayHello: function() {
            return "Hello, World!"
        }
    };
});

But both do the same thing. Can someone show me why I would use one or other of the above by making this example show some additional functionality that I could get by using one method instead of the other.

1 Answers1

0

Services and factories are subtly different. Services are constructors that you call with "new" where factories return singleton objects.

Brian Genisio
  • 47,787
  • 16
  • 124
  • 167
  • Further reading: http://stackoverflow.com/questions/15666048/angular-js-service-vs-provide-vs-factory/15666049#15666049 – Brian Genisio Apr 17 '13 at 19:32
  • 1
    I'm sorry but I still don't really understand what advantage one has over the other. I keep seeing examples that do just the same thing. I have yet to see a short few line example that shows why I would need to use one over the other. You mention "services are constructors that you call with "new". But I am not sure. Why would that be needed or not needed compared with a factory? –  Apr 19 '13 at 04:38
  • For the most part, the difference is really just semantics. For example, I can return a constructor using a Factory which will act like a service. But, here is an explanation with examples: https://groups.google.com/forum/#!msg/angular/56sdORWEoqg/b8hdPskxZXsJ – Brian Genisio Apr 20 '13 at 19:00
  • 1
    While it's nice that Misko takes the time to answer, the examples he gives are unfortunatly pretty bad. They really don't explain WHY one would use a one or the other (at least not in a way anyone new to Angular will understand). It would be nice with an example in the same style as the this question that shows a factory doing something a service can't and vice versa. If such an example can't be made then the difference is pointless and both should not exist. :P – Erik Honn Jul 13 '13 at 00:00