AngularJS / JS如何访问函数外的变量?

时间:2013-09-01 05:38:57

标签: javascript angularjs angular-resource

我正在尝试访问从功能块中定义的变量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;
});

2 个答案:

答案 0 :(得分: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);
        });
    });
};

答案 1 :(得分:0)

我真的很好奇为什么你使用this,因为根据访问单例的范围,它将是一个不同的this。这可以解释你得到的错误。

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