简体   繁体   English

使用angularjs,如何触发文件上传指令的更改事件?

[英]With angularjs, how do I fire a change event for a file upload directive?

I have a fileUpload directive that displays the currently selected filename: 我有一个fileUpload指令,显示当前选定的文件名:

app.directive('fileUpload', function () {
return {
    scope: true,
    link: function (scope, el, attrs) {
        el.bind('change', function (event) {
            var files = event.target.files;
            for (var i = 0;i<files.length;i++) {
                scope.$emit("fileSelected", { file: files[i] });
            }
        });
    }
};

}); });

Here is the html: 这是html:

<input id="pdDocument" type="file" file-upload>

I have a cancel button on the form that does this: 我在执行此操作的表单上有一个取消按钮:

$scope.files = [];

The files object gets cleared but the filename still displays on the page next to the Choose File button. 文件对象被清除,但文件名仍显示在“选择文件”按钮旁边的页面上。 How can I get the filename to clear out so it doesn't display when $scope.files is cleared? 我如何清除文件名,以便在清除$ scope.files时不显示文件名? I feel like I need to trigger the change event for the file input directive but not sure how to do that. 我觉得我需要触发文件输入指令的change事件,但不确定如何执行。

Inside the link function, you can add the following watcher to set the file name to empty when the model files changes: 在链接功能内,您可以添加以下watcher以在模型files更改时将文件名设置为空:

scope.$watch('files', function(){
    el.val('');
})

Working Demo 工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM