我想扩展概述的指令 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();
(取消注释)阻止打开文件对话框,但我不知道如何恢复“更改”事件。
是否可以手动触发更改事件?
最佳答案
您想单击不同的按钮,而不是文件输入标签。用户不会看到文件输入或其标签。
然后确认模式...触发文件输入的点击。
以下使用从模态 Controller 到指令的 Angular 事件广播
在指令中将 element.bind('click...
替换为:
scope.$on('init-file-select', function(){
element[0].click();
});
在模态 Controller 中修改开始看起来像:
app.controller("AbandonChangesModalCtrl", function($scope, $modalInstance, $rootScope){
$scope.yes = function(){
// this could also be done from main controller in `result` promise callback
$rootScope.$broadcast('init-file-select')
$modalInstance.close('yes');
}
关于javascript - 在 Angular 中的文件对话框之前允许模态对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38297489/