在角度服务中,我该如何设置正确的:
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.
});
有更好的方法可以做到这一点或替代方案吗?
答案 0 :(得分:1)
这只是一个JavaScript的东西,而不是角度特定的东西,但你想要的是Function.bind()
。请参阅下面的更正代码:
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));
答案 1 :(得分:0)
我赞成另一种技巧,在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);
});
编辑:我通过Function.bind推荐这个的唯一原因是这将得到普遍支持。 IE8或更早版本不支持Function.bind,但可以轻松填充。我知道的另一个微不足道的细节是Appcelerator Titanium Mobile使用的“Function”对象也没有bind方法。同样,它很容易被填充。