Created
December 14, 2018 17:50
-
-
Save p0lar-bear/ec933b8756e03e48df69236b8c6b7149 to your computer and use it in GitHub Desktop.
AngularJS 1.4+ Styleguide-friendly support of ngModel in input[type=file] elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
'use strict'; | |
/** | |
* @ngdoc input | |
* @name input[file] | |
* | |
* @description | |
* Adds very basic support for ngModel to `input[type=file]` fields. | |
* | |
* Requires AngularJS 1.4.x or later. Does not support Internet Explorer 9 - the browser's | |
* implementation of `HTMLInputElement` must have a `files` property for file inputs. | |
* | |
* @param {string} ngModel | |
* Assignable AngularJS expression to data-bind to. The data-bound object will be an instance | |
* of {@link https://developer.mozilla.org/en-US/docs/Web/API/FileList `FileList`}. | |
* @param {string=} name Property name of the form under which the control is published. | |
* @param {string=} ngChange | |
* AngularJS expression to be executed when input changes due to user interaction with the | |
* input element. | |
*/ | |
angular | |
.module('yourModuleNameHere') | |
.decorator('inputDirective', scpInputFileDecorator); | |
scpInputFileDecorator.$inject = ['$delegate', '$browser', '$sniffer', '$filter', '$parse']; | |
function scpInputFileDecorator($delegate, $browser, $sniffer, $filter, $parse) { | |
var inputDirective = $delegate[0], | |
preLink = inputDirective.link.pre; | |
inputDirective.link.pre = function (scope, element, attr, ctrl) { | |
if (ctrl[0]) { | |
if (angular.lowercase(attr.type) === 'file') { | |
fileInputType( | |
scope, element, attr, ctrl[0], $sniffer, $browser, $filter, $parse); | |
} else { | |
preLink.apply(this, arguments); | |
} | |
} | |
}; | |
return $delegate; | |
} | |
function fileInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) { | |
element.on('change', function (ev) { | |
if (angular.isDefined(element[0].files)) { | |
ctrl.$setViewValue(element[0].files, ev && ev.type); | |
} | |
}) | |
ctrl.$isEmpty = function (value) { | |
return !value || value.length === 0; | |
}; | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment