|
6 | 6 | function tcFileInput() {
|
7 | 7 | return {
|
8 | 8 | restrict: 'E',
|
9 |
| - require: ['^form', '^ngModel'], |
| 9 | + require: '^form', |
10 | 10 | templateUrl: 'directives/tc-file-input/tc-file-input.html',
|
11 | 11 | scope: {
|
12 | 12 | labelText: '@',
|
|
19 | 19 | setFileReference: '&',
|
20 | 20 | ngModel: '='
|
21 | 21 | },
|
22 |
| - link: function(scope, element, attrs, controllers) { |
23 |
| - var formController = controllers[0]; |
24 |
| - var ngModel = controllers[1]; |
25 |
| - |
| 22 | + link: function(scope, element, attrs, formController) { |
26 | 23 | scope.selectFile = selectFile;
|
27 | 24 | var fileTypes = scope.fileType.split(',');
|
28 | 25 |
|
|
34 | 31 | fileInput.bind('change', function() {
|
35 | 32 | var file = fileInput[0].files[0];
|
36 | 33 |
|
| 34 | + // About 1 in 20 times, the file is undefined (must be race condition) |
| 35 | + // Return early in this case so no errors are thrown |
| 36 | + if (!file) { |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + var fileSize = file.size; |
| 41 | + var isAllowedFileSize = fileSize < '500000000'; |
| 42 | + |
37 | 43 | var selectedFileType = file.type.slice(file.type.lastIndexOf('/') + 1);
|
38 | 44 | var isAllowedFileFormat = _.some(fileTypes, _.matches(selectedFileType));
|
39 | 45 |
|
40 | 46 | scope.$apply(function(){
|
| 47 | + // Set the file name as the value of the disabled input |
| 48 | + fileNameInput[0].value = file.name; |
| 49 | + var clickedFileInput = formController[attrs.fieldId]; |
| 50 | + |
41 | 51 | if (!isAllowedFileFormat) {
|
42 |
| - fileNameInput[0].value = file.name; |
| 52 | + // Manually setting is required since Angular doesn't support file inputs |
| 53 | + clickedFileInput.$setTouched(); |
| 54 | + clickedFileInput.$setValidity('required', false); |
| 55 | + |
| 56 | + } else { |
| 57 | + clickedFileInput.$setValidity('required', true); |
| 58 | + } |
43 | 59 |
|
| 60 | + if (!isAllowedFileSize) { |
44 | 61 | // Manually setting is required since Angular doesn't support file inputs
|
45 |
| - formController[attrs.fieldId].$setTouched(); |
46 |
| - formController[attrs.fieldId].$setValidity('required', false); |
| 62 | + clickedFileInput.$setTouched(); |
| 63 | + clickedFileInput.$setValidity('filesize', false); |
47 | 64 |
|
48 | 65 | } else {
|
| 66 | + clickedFileInput.$setValidity('filesize', true); |
| 67 | + } |
| 68 | + |
| 69 | + if (isAllowedFileFormat && isAllowedFileSize) { |
49 | 70 | // Pass file object up through callback into controller
|
50 | 71 | scope.setFileReference({file: file, fieldId: scope.fieldId});
|
51 |
| - |
52 |
| - // Set the file name as the value of the disabled input |
53 |
| - fileNameInput[0].value = file.name; |
54 |
| - |
55 |
| - // Manually set validity of specific input field |
56 |
| - formController[attrs.fieldId].$setValidity('required', true); |
57 | 72 | }
|
58 | 73 | });
|
59 | 74 | });
|
|
0 commit comments