Why should I choose to use the service via Factory in AngularJS?

I know this has been asked so many times (in fact, a lot!), But I still cannot fully understand what the main difference is between the two.

I am aware that the service returns a singleton instance of the provided function and that the factory will simply call that function and return its value.

But...

As I see it, you can do and achieve the same effect using one or the other, so how should I choose which one to use? Why should I choose services over factories or vice versa?

Is there a situation where you can do something else that cannot?

+3


source to share


1 answer


Shorter

If you want your function to be called like a normal function, use a factory. If you want your function to be created with a new operator, use a service. If you don't know the difference, use a factory

Source:

URL: http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html

Detailed explanation



When you use a service, the variables and functions you declare will be prototyped into a new object and the object will be returned to you. Where in a factory, it will return the function just the way it is.

Suppose you created a service with 10 functions, when you include it as a dependency, a new object will be created and all functions will be prototyped, see below example

function Gandalf() {
    this.color = 'grey';
}

Gandalf.prototype.comeBack = function() {
    this.color = 'white';
}

      

"this" will be returned. The performance issues are minor here.

+3


source







All Articles