我有功能,我有一个上传框,我将浏览我的json文件并将上传并提交它,当我提交它时我的控制器将被调用来处理它,我需要迭代上传的json文件逐行和键值对。为此尝试使用angular.forEach(data)
,如下所示,但它不起作用。我们可以做到这一点的可能方式是什么。而不是使用$ http我们可以用工厂吗?
{
"outer"
[
"A" : "aaaa",
"B" : "bbbb"
],
"C" : "c"
"D" : "d"
},
{
"C" : "c"
"D" : "d"
"E" : "e"
}
mapApp.factory('formDataObject',function($resource){
return $resource("",{},{
upload: {
method: 'POST',
transformResponse: function(data){
var fd = new FormData();
angular.forEach(data, function(value, key)
{
fd.append(key, value);
return fd;
});
}
}
}
)});
在下面这个例子中,我可以看到上传的文件内容,这里我要做的是,我想动态迭代每一行。
答案 0 :(得分:1)
我得出了答案。找到代码的DEMO。
var myapp = angular.module('myapp', []);
myapp.controller('MainCtrl', function ($scope) {
$scope.showContent = function($fileContent){
$scope.content = $fileContent;
$scope.aa = JSON.parse($scope.content);
alert('length->' + $scope.aa.length +'--->'+angular.toJson($scope.aa));
//alert($scope.content.value.data); // not working
angular.forEach($scope.aa, function (key, value) {
// alert('key->'+key+'ZValue->'+value); // disaply each letter
});
};
});
myapp.directive('onReadFile', function ($parse) {
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
var fn = $parse(attrs.onReadFile);
element.on('change', function(onChangeEvent) {
var reader = new FileReader();
reader.onload = function(onLoadEvent) {
scope.$apply(function() {
fn(scope, {$fileContent:onLoadEvent.target.result});
});
};
reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});
}
};
});