How can I display a text files contents in a textarea?

梦想与她 提交于 2019-12-11 03:33:47

问题


I am trying to create a file upload component, and display the text file contents in a textarea in the browser for editing before processing.

My inputs looks like this

<input type="file" process-file/>
<textarea id="file-text"
     ng-model="fileContent">
</textarea>

I have a directive that correctly reads the file contents

app.directive('processFile', [function () {
    return {
        link: function (scope, element, attrs) {
            element.on('change', function  (evt) {
                var files = evt.target.files;

                var reader = new FileReader();
                reader.onload = function(e) {
                    var text = e.target.result
                    console.log(text); // contents are correctly displayed
                    scope.fileContent = text;  // this does not work
                    $scope.fileContent = text; // nor does this
                    $("#file-text").text(text) // or this
                };

                reader.readAsText(files[0]);
            });
        }
    }
}]);

I need to inject the file content into that textarea but all attempts seem to fail. How can I do that?


回答1:


Custom event considered as event runs out of angular context. After firing such event angular digest cycle system doesn't get intimated to update its bindings. You have to kick off digest cycle manually to sync up binding. You could use $timeout here to run digest cycle.

Code

element.on('change', function  (evt) {
    var files = evt.target.files;
    var reader = new FileReader();
    reader.onload = function(e) {
        var text = e.target.result
        console.log(text); // contents are correctly displayed
        $timeout(function(){
            scope.fileContent = text;
        },0);
    };

    reader.readAsText(files[0]);
});



回答2:


This is how you change value of a textarea:

document.getElementById('myTextarea').value = '';

or like this in jQuery:

$('#myTextarea').val('');

Where you have

<textarea id="myTextarea" name="something">This text gets removed</textarea>

How to change the Content of a <textarea> with Javascript

So should have this in your onload function:

$("#file-text").val(text);

Or this in your html file:

<textarea id="file-text">
    {{fileContent}}
</textarea>


来源:https://stackoverflow.com/questions/41250349/how-can-i-display-a-text-files-contents-in-a-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!