Commit 5ff1941678a4407216b10a46f97b5c5a2331b33f
1 parent
d57f67fc66
Exists in
master
directiva ng-file-model
Showing
1 changed file
with
43 additions
and
0 deletions
Show diff stats
src/js/ngFileModel-directive.js
... | ... | @@ -0,0 +1,43 @@ |
1 | +angular.module('focaDirectivas') | |
2 | + .directive('ngFileModel', ['$parse', function ($parse) { | |
3 | + return { | |
4 | + restrict: 'A', | |
5 | + link: function (scope, element, attrs) { | |
6 | + var model = $parse(attrs.ngFileModel); | |
7 | + var isMultiple = attrs.multiple; | |
8 | + var modelSetter = model.assign; | |
9 | + element.bind('change', function () { | |
10 | + var promesas = []; | |
11 | + angular.forEach(element[0].files, function (item) { | |
12 | + promesas.push(new Promise(function(resolve, reject) { | |
13 | + var reader = new FileReader(); | |
14 | + reader.readAsDataURL(item); | |
15 | + reader.onload = function(){ | |
16 | + var value = { | |
17 | + name: item.name, | |
18 | + url: URL.createObjectURL(item), | |
19 | + size: item.size, | |
20 | + base64: reader.result, | |
21 | + _file: item | |
22 | + }; | |
23 | + resolve(value); | |
24 | + }; | |
25 | + reader.onerror = function (error) { | |
26 | + reject(error); | |
27 | + }; | |
28 | + })); | |
29 | + }); | |
30 | + | |
31 | + Promise.all(promesas).then(function(values){ | |
32 | + scope.$apply(function () { | |
33 | + if (isMultiple) { | |
34 | + modelSetter(scope, values); | |
35 | + } else { | |
36 | + modelSetter(scope, values[0]); | |
37 | + } | |
38 | + }); | |
39 | + }); | |
40 | + }); | |
41 | + } | |
42 | + }; | |
43 | + }]); | |
0 | 44 | \ No newline at end of file |