FileReader()onload函数没有触发

时间:2017-11-08 14:30:03

标签: angularjs angularjs-directive filereader

我知道这是重复的,但到目前为止,答案都没有帮助。

我有这个指令:

app.directive('fileReader', function () {
    return {
        scope: {
            fileReader: "="
        },
        link: function (scope, element) {
            $(element).on('change', function (changeEvent) {
                var files = changeEvent.target.files;
                if (files.length) {
                    var reader = new FileReader();
                    console.log('reader created');
                    reader.onload = function (e) {
                        console.log('onload hit');                           
                    };
                }
            });
        }
    };
}) 

这个DOM元素链接到指令:

<input type="file" id="file" file-reader="fileContent"/>  

当我为输入选择文件时,我的控制台打印出reader created,但从不打印onload hit。我无法弄清楚如何正确启动我的onload功能。我在这做错了什么?

1 个答案:

答案 0 :(得分:1)

### Directive ###
    app.directive('fileReader', ['$rootScope', function($rootScope) {
     return {
        scope: {
            fileReader:"="
        },
        link: function(scope, element) {
            $(element).on('change', function(changeEvent) {
                var files = changeEvent.target.files;
                if (files.length) {
                    $rootScope.uploadedFileName = files[0].name;
                    var r = new FileReader();
                    r.onload = function(e) {
                        var contents = e.target.result;
                        scope.$apply(function () {
                            scope.fileReader = contents;    
                            $rootScope.uploadedFileName = files[0].name;                        
                        });
                    };
                    r.readAsText(files[0]);
                }
            });
        }
     };
    }]);

### HTML ###

    <input type="file" accept=".csv" id="myFile" file-reader="fileContent"/>