如果您想要更优雅/更集成的东西,您可以使用decorator 来扩展input 指令并支持type=file。需要牢记的主要警告是,此方法在 IE9 中不起作用,因为 IE9 没有实现 File API。在 IE9 或更早版本中,使用 JavaScript 上传二进制数据(无论类型如何)在 IE9 或更早版本中根本不可能(使用 ActiveXObject 访问本地文件系统不算作使用 ActiveX 只是为了安全问题)。
这个确切的方法还需要 AngularJS 1.4.x 或更高版本,但您可以调整它以使用 $provide.decorator 而不是 angular.Module.decorator - 我写了 this gist 来演示如何在遵守 @987654323 的同时做到这一点@:
(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', myInputFileDecorator);
myInputFileDecorator.$inject = ['$delegate', '$browser', '$sniffer', '$filter', '$parse'];
function myInputFileDecorator($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;
};
}
})();
为什么一开始没有这样做? AngularJS support is intended to reach only as far back as IE9. If you disagree with this decision and think they should have just put this in anyway, then jump the wagon to Angular 2+ because better modern support is literally why Angular 2 exists.
问题是(如前所述)没有文件 api
鉴于我们的核心,支持正确执行此操作是不可行的
基线是 IE9 并且填充这些东西是不可能的
核心。
另外尝试以不
跨浏览器兼容只会让第 3 方解决方案更难,
现在必须对抗/禁用/解决核心解决方案。
...
我将在关闭 #1236 时关闭它。 Angular 2 正在
构建以支持现代浏览器并使用该文件支持将
很容易获得。