简体   繁体   中英

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

I'm trying to access the variable np defined from within a function block; however, I am running into some issues when I call this.items.push(plumbers) . I get 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. 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. The services docs are a good place to start and this question is good as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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