[英]Accessing controller variable from anonymous function
我正在编写AngularJS应用程序。 我需要从SQLite3数据库加载数据。 为此,我使用的体系结构是:我有一个使用express的Node.js服务器,该服务器通过socket.io与angular.js应用程序进行通信。 因此,我请求客户端从数据库中获取信息,服务器会收集该信息并将其发送回客户端。
在这里,我试图初始化一个对象数组: 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
}
});
});
问题是我无法从匿名函数内部访问“ meds”。 我已经尝试过meds
和this.meds
但没有成功。
如果使用$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
}
});
});
编辑:如何添加this.meds.push
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.