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?
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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With