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

2 Answers 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);
        });
    });
};
Sign up to request clarification or add additional context in comments.

1 Comment

AWESEOME! Works great!
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.

2 Comments

I'm kinda hacking it atm, from this demo code binarymuse.github.io/ngInfiniteScroll/demo_async.html so yea, might be bad practice. Was hoping to get it to work then refactor.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.