0

I am trying to change this.data to the results returned by an API but it seems that I am not managing to achieve this. I am pretty sure it has to do with the scopes (API data is returned successfully) however I am not sure how to go round this properly. Below I have posted a skeleton method of what I am trying to do, I would appreciate any guidelines as to how to properly access this.data within closures. Thank you.

app.controller("Ctrl", function(//param) {

  this.data = {};

  this.method = function() {

    var apiURL = "blablabla";

    // OAuth Procedure
    $angularService.getData(Client_ID, [//fields]).then(function(result) {
      // do stuff
      $http.get(apiURL, {
        params: {
          access_token: $localStorage.accessToken,
          fields: "params",
          format: "json"
        }
      }).then(function(result) {
          this.data = result.data;   // here it is not recognising this.data
      }, function(error) {
        alert("error");
        console.log(error);
      });
    }, function(error) {
      alert("error");
      console.log(error);
    })
  }
}
mesllo
  • 545
  • 7
  • 29
  • 3
    after this.data = {}; add a var self = this; then access to self.data – Sladix Jun 28 '16 at 12:48
  • that worked thanks! But I don't understand why initializing this as a variable would help.. – mesllo Jun 28 '16 at 13:03
  • 1
    When you use this inside a function (callback or not) it refers to the local scope. So by declaring a self variable you store all the scope into it so you can access it later – Sladix Jun 28 '16 at 13:12

0 Answers0