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

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

问题描述

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

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?

推荐答案

自定义事件被视为超出 angular 上下文的事件.触发此类事件后,角度摘要循环系统不会被告知更新其绑定.您必须手动启动摘要循环以同步绑定.您可以在此处使用 $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]);
});

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

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