0

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;
});
Jon7
  • 7,165
  • 2
  • 33
  • 39
Ryan W Kan
  • 380
  • 3
  • 16

2 Answers2

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);
        });
    });
};
zs2020
  • 53,766
  • 29
  • 154
  • 219
0

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.

Community
  • 1
  • 1
Jon7
  • 7,165
  • 2
  • 33
  • 39
  • 1
    I'm kinda hacking it atm, from this demo code http://binarymuse.github.io/ngInfiniteScroll/demo_async.html so yea, might be bad practice. Was hoping to get it to work then refactor. – Ryan W Kan Sep 01 '13 at 06:48
  • @ryanwkan Good call. Sza's solution will definitely get it to a working state. Then you can refactor to make it more "angular-y". I can't put my finger on the "angular way" to do what you want to do, but I feel like there is a way. – Jon7 Sep 01 '13 at 16:31