简体   繁体   中英

Accessing controller variable from anonymous function

I am coding an AngularJS application. I need to load data from a SQLite3 database. The architecture I'm using for this is: I have a Node.js server using express which communicates with the angular.js application through socket.io. So, I make a petition from the client to get info from the database, the server gathers that info and sends it back to the client.

Here I'm trying to initialize an array of objects: main.meds (using angular.js routeProvider, I have referenced 'MainCtrl' as 'main'):

angular.module('medsOrmApp').controller('MainCtrl', function() {
  this.socket = io();
  this.meds = [];

  this.socket.emit('loadMeds', 'gimme the list !');
  this.socket.on('medsResponse', function(data) {
    console.log(data);

    for (var i = 0; i < data.length; i++) {
      var tmp = {};
      tmp.id = data[i].ID_MEDICAMENTO;
      tmp.nombre = data[i].NOMBRE_MEDICAMENTO;
      tmp.cantidad = data[i].CANTIDAD_DISPONIBLE;
      tmp.lab = data[i].LABORATORIO;
      meds.push(tmp); // ERROR: 'meds' is not defined
    }
  });
});

The problem is that I can't access 'meds' from inside the anonymous function. I've tried with meds and this.meds without success.

Would this not work if you used $scope ?

angular.module('medsOrmApp').controller('MainCtrl', function($scope, $timeout) {
  this.socket = io();
  this.meds = [];

  this.socket.emit('loadMeds', 'gimme the list !');
  this.socket.on('medsResponse', function(data) {
    console.log(data);

    for (var i = 0; i < data.length; i++) {
      var tmp = {};
      tmp.id = data[i].ID_MEDICAMENTO;
      tmp.nombre = data[i].NOMBRE_MEDICAMENTO;
      tmp.cantidad = data[i].CANTIDAD_DISPONIBLE;
      tmp.lab = data[i].LABORATORIO;
      this.meds.push(tmp); // ERROR: 'meds' is not defined
    }
  });
});

edit: what about adding this.meds.push ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM