【问题标题】:angularjs upload and iterate over json file recordsangularjs上传并遍历json文件记录
【发布时间】:2018-05-13 01:43:13
【问题描述】:

我有功能,我有一个上传框,我将在其中浏览我的 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;
                                 });
                            }
                }
}
)});

添加示例:

在下面这个例子中,我可以看到上传的文件内容,这里我想做的是,我想动态地迭代每一行。

http://jsfiddle.net/6aG4x/1242/

【问题讨论】:

  • 定义“不工作”。你做了什么调试?出了什么问题?

标签: angularjs json file-upload


【解决方案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]);
            });
        }
    };
});

【讨论】:

    猜你喜欢
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2016-02-04
    • 1970-01-01
    相关资源
    最近更新 更多