Rolando
Rolando

Reputation: 62664

How to access instance of service?

In an angular service, how can I set correct this:

var fruit = $http.get("url", {cache:false});

$q.all([fruit]).then(function(val) {
    this.fruits.push(val); // this.fruits is undefined. Need "this" to refer to the angular service as opposed to whatever its referring to.
});

Is there a better way to do this or alternative?

Upvotes: 0

Views: 69

Answers (2)

trey-jones
trey-jones

Reputation: 3437

I favor another technique, also pretty common in javascript:

var fruit = $http.get('url', {cache: false}),
   self = this;  // cache the correct this in the self variable

$q.all([fruit]).then(function(val) {
    // self is still equal to the value outside of this closure
    // ie. the service
    self.fruits.push(val);  
});

Edit: The only reason that I would recommend this over the Function.bind is that this is going to be universally supported. Function.bind is not supported in IE8 or older, though it can be easily polyfilled. Another trivial detail that I know of is that the "Function" object used by Appcelerator Titanium Mobile also does not have a bind method. Again, it is easily polyfilled.

Upvotes: 0

Jeff Hubbard
Jeff Hubbard

Reputation: 9902

This is merely a JavaScript thing, rather than an angular-specific thing, but what you want is Function.bind(). See the corrected code below:

var fruit = $http.get("url", {cache:false});

$q.all([fruit]).then(function(val) {
    this.fruits.push(val); // this.fruits is undefined. Need "this" to refer to the angular service as opposed to whatever its referring to.
}.bind(this));

Upvotes: 1

Related Questions