[英]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.