我正在使用来自csv文件的数据填充$scope.master
。在我填充$scope.master
的函数中,所有数据都在那里。查看日志输出;我把它放在了线上。
但是,在函数之外,$scope.master
仍然按预期填充数据,但console.log(Object.getOwnPropertyNames($scope.master))
返回一个空数组,console.log(Object.getOwnPropertyNames($scope.master).length)
返回0.
为什么明显非空的$scope.master
对象会为其属性返回一个空数组?
angular.module('app', []);
angular.module('app').controller('mainCntrl', ['$scope',
function ($scope) {
$scope.master = {};
$scope.selected_interface = "";
$scope.selected_DBCfile = "";
$scope.DBCfiles = [];
var CSV_filepath = '../data/interfaces.csv';
d3.csv(CSV_filepath, function (err, data) {
data.forEach(function (d) {
d.interfaceName = d.interfaceName;
d.DBCfile = d.DBCfile;
d.AtoB = +d.AtoB;
d.BtoA = +d.BtoA;
if (!$scope.master[d.interfaceName]) {
var DBCfilesForInterface = {};
DBCfilesForInterface[d.DBCfile] = new Array();
DBCfilesForInterface[d.DBCfile].push(d);
$scope.master[d.interfaceName] = DBCfilesForInterface;
}
else if (!$scope.master[d.interfaceName][d.DBCfile]) {
$scope.master[d.interfaceName][d.DBCfile] = new Array();
$scope.master[d.interfaceName][d.DBCfile].push(d);
}
else{
$scope.master[d.interfaceName][d.DBCfile].push(d);
}
})
//master is all made
$scope.interfaces = Object.keys($scope.master);
$scope.selected_interface = $scope.interfaces[0];
$scope.DBCfiles = Object.keys($scope.master[$scope.selected_interface]);
$scope.selected_DBCfile = $scope.DBCfiles[0];
//LOOK AT THESE LOGS
console.log($scope.master);
//Object { 1 - ModelS ESP 1.0 Interface: Object, 2 - ModelS ESP 2.0 Interface: Object, 3 - ModelS ESP 2.0 Interface with Tesla Body Controls: Object, 4 - ModelS ESP 2.0 Interface with Tesla Body Controls and TH bus: Object }
console.log($scope.selected_interface);
//"1 - ModelS ESP 1.0 Interface"
console.log($scope.selected_DBCfile);
//"ModelS_BDY.dbc"
console.log($scope.DBCfiles);
//Array [ "ModelS_BDY.dbc", "ModelS_BFT.dbc", "ModelS_CH.dbc", "ModelS_ETH.dbc", "ModelS_OBDII.dbc", "ModelS_PT.dbc", "ModelX_TH_common.dbc" ]
});
//OUTSIDE OF THE FUNCTION
console.log($scope.master);
//Object { 1 - ModelS ESP 1.0 Interface: Object, 2 - ModelS ESP 2.0 Interface: Object, 3 - ModelS ESP 2.0 Interface with Tesla Body Controls: Object, 4 - ModelS ESP 2.0 Interface with Tesla Body Controls and TH bus: Object }
//$scope.master has data, as expected
console.log(Object.getOwnPropertyNames($scope.master));
//Array [ ]
//however, it has no properties? but we just saw them in the above log...
console.log(Object.getOwnPropertyNames($scope.master).length);
//0
console.log($scope.selected_interface);
//""
//this has suddenly turned empty as well
console.log($scope.selected_DBCfile);
//""
//this has suddenly turned empty as well
console.log($scope.DBCfiles);
//Array [ ]
//this has suddenly turned empty as well
}]);
答案 0 :(得分:2)
这是因为d3.csv是一种异步方法。
在数据完成配对并存储到变量之前,函数外的所有控制台都会运行。将所有方法处理文件数据放入d3.csv方法的回调中,一旦数据被解析并可用,它们应该将所有值填充到它们中。
希望这有帮助。