0

我正在尝试访问从功能块中定义的变量 np;但是,当我调用this.items.push(plumbers). 我明白了TypeError: Cannot call method push of undefined

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;
});
4

2 回答 2

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);
        });
    });
};
于 2013-09-01T05:49:07.277 回答
0

我真的很好奇你为什么使用this,因为它会this根据访问单例的范围而有所不同。这将解释你得到的错误。

我强烈建议阅读 Angular 中的工厂,然后再看一下代码。服务文档是一个很好的起点这个问题也很好。

于 2013-09-01T05:50:16.297 回答