I have an AngularJS function defined as follows.
angular.module('myService').service('myService', function() { this.publicFunction(param) { ... }; this.anotherPublicFunction(param) {
and I would like to name the first function both from outside the service (which works fine using myService.publicFunction(xxx) ), and from another function in the same service, i.e. anotherPublicFunction . None of this.publicFunction(param) or myService.publicFunction(param) will work from the second function, and I can understand it.
EDIT:
Actually the whole problem was caused by the fact that you cannot reproduce with my example. I passed the second function as a callback parameter to another function in a separate controller, and when it is called, the reference to this does not work.
eg.
anotherService.someCall('a', 123, myService.anotherPublicFunction);
crashes inside anotherPublicFunction because this cannot be resolved.
I wrote Plunker to show the problem: http://plnkr.co/edit/rrRs9xnZTNInDVdapiqF?p=info
(I will still leave the question here if this helps someone else.)
I know that I can work around the problem using a service link or a first function like this
var ms = this; this.anotherPublicFunction(param) { ms.publicFunction(param); ... };
or
var pf = this.publicFunction; this.anotherPublicFunction(param) { pf(param); ... };
but both look like dirty hacks.
Is there a good way to call the first function from the second in this case? Or am I doing something completely wrong, in the first place, to have such a service?
I found these questions with good answers:
- Angularjs Access Functions Inside a Service
- AngularJs calls an internal service function from itself
but they are different from my problem, because one of them has a separate internal function that should have been called, and the other used a factory instead of a service.
EDIT:
After publishing this, I immediately realized that I could do this:
var actualWork = function(param) { ... } this.publicFunction(param) { actualWork(param); }; this.anotherPublicFunction(param) { actualWork(param); ... };
that so far is not as bad as other options so far ... Are there any better approaches?