Vahid Kharazi
Vahid Kharazi

Reputation: 6033

Use parent scope variable in angular and javascript

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?

Upvotes: 0

Views: 104

Answers (1)

km6zla
km6zla

Reputation: 4877

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.

Upvotes: 1

Related Questions