2013-09-01 55 views
0

我试图访问从功能块内定义的变量np;然而,当我拨打this.items.push(plumbers)时,我遇到了一些问题。我得到TypeError: Cannot call method push of undefinedAngularJS/JS如何访问我的函数之外的变量?

myApp.factory('np', function($resource, nearbyPlumbers){ 
    var np = function(){ 
    this.items = []; 
    this.busy = false; 
    this.limit = 5; 
    this.offset = 0; 
    }; 

    np.prototype.nextPage = function(){ 
    if (this.busy) return; 
    this.busy = true; 

    var temp; 

    nearbyPlumbers.nearby({lat: -37.746129599999996, lng: 144.9119861}, function(data){ 
     angular.forEach(data, function(plumber){ 
     alert('yay'); 
     //this.items.push(plumber); 
     console.log(plumber); 
     console.log(this.items); // <--- This wont work. How do I access this.items 
     }); 
    }); 
    }; 
    return np; 
}); 

回答

1
np.prototype.nextPage = function() { 
    if (this.busy) return; 
    this.busy = true; 

    var temp; 
    var that = this; // add this line 

    nearbyPlumbers.nearby({ 
     lat: -37.746129599999996, 
     lng: 144.9119861 
    }, function (data) { 
     angular.forEach(data, function (plumber) { 
      that.items.push(plumber); //access using "that" 
      console.log(plumber); 
      console.log(that.items); 
     }); 
    }); 
}; 
+0

AWESEOME!很棒! –

0

我真的很好奇,为什么你正在使用this,因为这将是根据什么范围不同this访问来自单身。这将解释你得到的错误。

我强烈建议您阅读Angular的工厂,然后再看看代码。 services docs are a good place to startthis question也不错。

+1

我有点骇客它atm,从这个演示代码http://binarymuse.github.io/ngInfiniteScroll/demo_async.html所以是的,可能是不好的做法。希望能让它工作,然后重构。 –

+0

@ryanwkan好的电话。 Sza的解决方案一定会使其达到工作状态。然后你可以重构,使其更“角-y”。我不能把手指放在你想做的事情上,但我觉得有一种方法。 – Jon7