-
Notifications
You must be signed in to change notification settings - Fork 1
/
ng-fileDialog.js
115 lines (98 loc) · 2.91 KB
/
ng-fileDialog.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/**
* Created by yang on 2015/9/22.
*/
angular.module('ng-fileDialog', []).factory('FileDialog', function() {
var dialogs = {};
dialogs.selectFile = function(callback, acceptTypes) {
_open({
accept: acceptTypes
}, callback);
};
dialogs.selectFiles = function(callback, acceptTypes) {
_open({
multiple: true,
accept: acceptTypes
}, callback);
};
dialogs.selectDir = function(callback) {
_open({
webkitdirectory: true
}, callback);
};
dialogs.saveAs = function(callback, defaultFilename, acceptTypes) {
_open({
nwsaveas: defaultFilename || true,
accept: acceptTypes
}, callback);
};
dialogs.open = _open;
function _open(options, callback) {
var dialog = document.createElement('input');
dialog.type = 'file';
options = options || {};
if (options.multiple) {
dialog.multiple = true
}
if (options.accept) {
if (angular.isArray(options.accept) && options.accept.length > 0) {
dialog.accept = options.accept.join(',');
} else if (angular.isString(options.accept)) {
dialog.accept = options.accept;
}
}
if (options.webkitdirectory) {
dialog.webkitdirectory = true;
}
if (options.nwdirectory) {
dialog.nwdirectory = true;
}
if (options.nwworkingdir) {
dialog.nwworkingdir = options.nwworkingdir;
}
if (options.nwsaveas) {
dialog.nwsaveas = options.nwsaveas;
}
dialog.addEventListener('change', function() {
if (!callback) {
return;
}
// string join with ';'
// callback(dialog.value);
// files array
if (options.multiple) {
var files = [];
for (var i = 0; i < dialog.files.length; i++) {
files.push(dialog.files[i]);
}
callback(files);
} else {
callback(dialog.files[0]);
}
}, false);
dialog.click();
}
return dialogs;
}).directive('ngFileDialog', function(FileDialog) {
return {
restrict: 'EA',
replace: false,
transclude: false,
require: ['?options'],
scope: {
select: '&',
options: '='
},
link: function ($scope, $element, attrs) {
$element.on('click', function(event) {
event.preventDefault();
FileDialog.open($scope.options, function(file) {
if ($scope.select) {
$scope.select({
file: file
});
}
});
});
}
};
});