如何在文本区域中显示文本文件的内容? [英] How can I display a text files contents in a textarea?

查看:127
本文介绍了如何在文本区域中显示文本文件的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建文件上传组件,并在浏览器的文本区域中显示文本文件内容,以便在处理之前进行编辑.

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.

我的输入看起来像这样

<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?

推荐答案

自定义事件被视为事件用尽了角上下文.触发此类事件后,不会消化角度摘要循环系统以更新其绑定.您必须手动启动摘要循环以同步绑定.您可以在此处使用$timeout运行摘要周期.

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.

代码

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]);
});

这篇关于如何在文本区域中显示文本文件的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆