简体   繁体   English

从匿名函数访问控制器变量

[英]Accessing controller variable from anonymous function

I am coding an AngularJS application. 我正在编写AngularJS应用程序。 I need to load data from a SQLite3 database. 我需要从SQLite3数据库加载数据。 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. 为此,我使用的体系结构是:我有一个使用express的Node.js服务器,该服务器通过socket.io与angular.js应用程序进行通信。 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'): 在这里,我试图初始化一个对象数组: main.meds (使用angular.js routeProvider,我已将'MainCtrl'引用为'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. 问题是我无法从匿名函数内部访问“ meds”。 I've tried with meds and this.meds without success. 我已经尝试过medsthis.meds但没有成功。

Would this not work if you used $scope ? 如果使用$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 ? 编辑:如何添加this.meds.push

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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