Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function in AngularJS service from the same service?

Tags:

angularjs

I have an AngularJS service defined in the following way

angular.module('myService').service('myService', function() {   this.publicFunction(param) {     ...   };    this.anotherPublicFunction(param) {     // how to call publicFunction(param)?     ...   }; });     

and I would like to call the first function both from outside the service (which works fine by myService.publicFunction(xxx)) and from another function in the same service, i.e. anotherPublicFunction. Neither one of this.publicFunction(param) or myService.publicFunction(param) won't work from within the second function, and I can understand that.


EDIT:
Actually the whole problem was caused by something you can't reproduce with my example alone. 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 doesn't work.

E.g.

anotherService.someCall('a', 123, myService.anotherPublicFunction); 

fails inside anotherPublicFunction because this can't be resolved.

I've written a Plunker to show the problem: http://plnkr.co/edit/rrRs9xnZTNInDVdapiqF?p=info

(I'll still leave the question here in case it will help someone else.)


I know I could get around the problem by using a reference to the service or the first function like this

var ms = this; this.anotherPublicFunction(param) {   ms.publicFunction(param);   ... }; 

or this

var pf = this.publicFunction; this.anotherPublicFunction(param) {   pf(param);   ... }; 

but both seem like dirty hacks.

Is there a good way to call the first function from the second one in this case? Or am I doing something totally wrong in the first place to have a service like this?

I found these questions with good answers:

  • Angularjs share functions inside service
  • AngularJs call an internal service function from self

but they differ from my problem since one of them has a separate, internal function that was to be called, and the other one was using a factory instead of a service.

EDIT:

After posting this I immediately realized I could also do this:

var actualWork = function(param) {   ... }  this.publicFunction(param) {   actualWork(param); };  this.anotherPublicFunction(param) {   actualWork(param);   ... }; 

which doesn't seem quite as bad as the other options so far... Are there better approaches?

like image 723
MJV Avatar asked Nov 07 '13 17:11

MJV


1 Answers

I think the best way is to go like this:

var myFunctions =  {      myFunc1: function(param) {      },      myFunc2: function(param) {        return foo + myFunctions.myFunc1(param)// do some stuff with the first function             }  } return myFunctions; 

because I think if you use this, it may get conflict with the scope where you use the service.

like image 59
Aladdin Mhemed Avatar answered Sep 22 '22 02:09

Aladdin Mhemed