xerotolerant xerotolerant - 3 months ago 8
AngularJS Question

using call and bind in an angular service

I'm currently learning angularjs and I am wondering something.
How would one user call or apply to connect the value of a call back function to a value in a service. Let me explain.

app.service("AppService"), function(){
//value to be bound
this.value;

//function that references a promise or something
this.doThing = function(){
//refer to a promise

externalPromise("string").then(function(response){
//The scope has changed so "this" is no longer refering to the service
this.value = response;
});
}

})

app.controller("AppCtrl", function(AppService){

alert(AppService.value);

})


I know that this could (and probably should be) can be done:

app.service("AppService"), function(){
//value to be bound
var value;

//function that references a promise or something
var doThing = function(){
//refer to a promise

externalPromise("string").then(changeValue(response));
}

function changeValue(response){
value = response;
}
var getValue = function(){return value}

return {
value: getValue,
doThing: doThing
}
})



app.controller("AppCtrl", function(AppService){

alert(AppService.value);

})


But if the point of services is that they return the "this" then I think it would make the most sense to exploit that. I think it might be possible to use call bind or apply to set the
this
inside the changeValue function to the same as
this
in the controller. I can't figure out exactly how. Does anybody know? Even if it is unnecessary, think of it as an academic exercise.

Edit: The solution presented in the other question is valid and would work. However I wanted to know if there was a specific way to do it in angular. The answer That I marked as correct recommended using
angular.bind()
on the function that I wanted to bind.

Answer

You should be able to use angular.bind to give your handler function the correct "this":

 this.doThing = function(){
   externalPromise("string").then(angular.bind(this, function(response){ 
        //this is now the "this" you expect
        this.value = response;
    }));
 }

An alternative that is commonly used is to store "this" in a variable and then use that variable in your handler:

this.doThing = function(){
   var self = this;
   externalPromise("string").then(function(response){ 
        //self is now the "this" you wanted.
        self.value = response;
    });
 }