0

i have this javascript code:

myApp.factory('Reddit', function($http) {
  var Reddit = function() {
    this.items = [];
    this.busy = false;
    this.after = '';
  };

  Reddit.prototype.nextPage = function() {
    console.log(this.items);// []
    $http({method: 'GET', url: url}).
    success(function(data, status, headers, config) {
      console.log(this.items); // undefined ?? how to access to items list
    })

How can access to items list in success function?

1
  • this in success callback refers to the callback function, not Reddit object, therefore this.items is undefined. See @ogc-nick's answer on how to avoid this. Commented Feb 12, 2014 at 18:14

1 Answer 1

1

Try assigning it to a local variable while it is defined. That local variable should be defined in your success function.

Reddit.prototype.nextPage = function() {
    console.log(this.items);// []
    var localItems = this.items; // if it is defined here, then alias it to a local var ( you can rename it to whatever)
    $http({method: 'GET', url: url}).
    success(function(data, status, headers, config) {
      console.log(this.items); // undefined ?? how to access to items list
      console.log(localItems); // should work
    })

I assume though that you are going to want access to the whole object in which case you can just alias this

Reddit.prototype.nextPage = function() {
    var obj = this;
    $http({method: 'GET', url: url}).
    success(function(data, status, headers, config) {
      obj.items.push('xxx');
    });

Here is a plunkr that shows multiple instances of a Reddit object building distinct items lists: example. Make sure to check the console.

Sign up to request clarification or add additional context in comments.

Comments

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.