简体   繁体   English

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

[英]AngularJS/ JS How do I access variables outside my function?

I'm trying to access the variable np defined from within a function block; 我正在尝试访问功能块中定义的变量np; however, I am running into some issues when I call this.items.push(plumbers) . 但是,当我调用this.items.push(plumbers)时,我this.items.push(plumbers)了一些问题。 I get TypeError: Cannot call method push of undefined 我收到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;
});
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);
        });
    });
};

I'm really curious why you're using this , since it's going to be a different this depending on what scope accessing the singleton from. 我真的很好奇,为什么你用this ,因为这将是一个不同的this取决于什么范围访问来自单身。 That would explain the error that you're getting. 那将解释您得到的错误。

I would strongly suggest reading up on factories in Angular and then taking another look at the code. 我强烈建议阅读Angular中的工厂,然后再看一下代码。 The services docs are a good place to start and this question is good as well. 服务文档是一个很好的起点这个问题也很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM