【发布时间】:2016-07-10 23:58:55
【问题描述】:
我想扩展in this popular question 概述的指令。
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
scope.$apply(function () {
scope.fileread = changeEvent.target.files[0];
// or all selected files:
// scope.fileread = changeEvent.target.files;
});
});
}
}
}]);
基本上 - 我想要做的是当用户按下“打开文件”文件输入时,它将显示一个“这将放弃更改”模式对话框。
如果用户按下“取消”,则不应显示文件对话框,但如果按下“继续而不保存”或“保存更改并继续”,则仅应显示选择文件对话框。
我希望能够将模态创建函数作为指令参数传递 - 这样我就可以在打开文件对话框之前使用不同的模态。
示例用法:
<label class="btn btn-default" for="fileOpen">
Open File
</label>
<input
style="display: none"
type="file"
fileread="onFileRead"
id="fileOpen"
name='file'
prefn="openModal"
/>
这是一个 jsfiddle,它演示了我正在尝试做的事情,以及示例问题:http://jsfiddle.net/hcyj3q6q/55/
这是我写的完整指令:
app.directive("fileread", [function() {
return {
scope: {
fileread: "=",
prefn: "="},
link: function(scope, element, attributes) {
element.bind("click", function(event){
if (scope.prefn){ // prefn is optional
//event.preventDefault();
scope.$apply(function(){
scope.prefn().then(
function() {
$timeout(function(){
//Resume file dialog
});
},
function() {
//Don't open file dialog
}
);
});
}
});
element.bind("change", function(changeEvent) {
scope.$apply(function() {
var file = changeEvent.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(e) {
scope.$apply(function() {
var contents = e.target.result;
scope.fileread(contents);
});
};
});
});
}
}
}]);
按原样 - 问题将是模式与打开文件对话框同时出现。
我们可以使用event.preventDefault();(取消注释)阻止文件对话框打开,但是我不知道如何恢复“更改”事件。
是否可以手动触发更改事件?
【问题讨论】:
标签: javascript angularjs file-io event-bubbling