Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Get current factory/service name

Ola!

I was just playing around with angular's factories and services and I just noticed that I can't get the current name of the factory/service. At least I couldn't get any resources about that.
For example so its a bit more clear I have a factory, like this;

.factory('GuessImAFactory', [function() {

    var factoryName = this.yadayada.name; //<- This actually doesn't work,
                                             //if you haven't guessed

    //<--Some other code goes here-->

    return something;
}])

So the question does anyone know the trick how to get the name of it?

like image 487
TheCodeDestroyer Avatar asked Jul 16 '14 11:07

TheCodeDestroyer


People also ask

What is factory service in AngularJS?

What is Factory in AngularJS? Factory is an angular function which is used to return the values. A value on demand is created by the factory, whenever a service or controller needs it. Once the value is created, it is reused for all services and controllers. We can use the factory to create a service.

Which uses this is it service or factory?

service() is just a Constructor, it's called with new , whereas . factory() is just a function that returns a value. Using . factory() gives us much more power and flexibility, whereas a .

What is factory service?

The term service factory, coined in 1989 by Richard B. Chase and Warren J. Erikson, represents the idea that the factory can be a source of customer service in addition to a place where products are manufactured.

What is difference between factory and service in angular?

The major difference between an AngularJS service and an AngularJS factory is that a service is a constructor function and a factory is not. That is why, in the case of a factory, we return an object literal instead of using this.


1 Answers

I don't think this is possible. In callback function you can't get actual instance of factory since you are defining it right in that place. In other works, it's not yet created.

However, simple workaround for this would be to hard code it.. Since you probably won't have dynamic factories, you could just simply say

var factoryName = 'GuessImAFactory';

and use it if needed.

like image 179
domakas Avatar answered Sep 17 '22 13:09

domakas