条件“多重” < input type =" file">中的属性与AngularJS

问题描述:

我需要一个上传表单字段,可能允许或不允许用户选择多个文件。

I need an upload form field that may or may not allow the user to select more than one file.

我知道我可以这样做:

<input type="file" multiple ng-if="allow_multiple">
<input type="file" ng-if="!allow_multiple">

但是,我们知道这并不理想。

But, we know that is not ideal.

我试过

<input type="file" ng-multiple="allow_multiple">

但这不起作用。

似乎AngularJS 没有这样的ngMultiple指令,但无论如何,每个人都在使用它(或者我错过了什么?)

It seems that AngularJS has no such ngMultiple directive, but everyone is using it anyway (or am I missing something?)

无论如何,实现这一目标的最佳方法是什么?

Anyway, what is the best way to accomplish that?

编辑:从目前为止的答案来看,似乎没有办法做到这一点。
我在他们的跟踪器上打开了这个问题,让我们看看我们得到了什么:-)
https: //github.com/angular/angular.js/issues/7714

From thw answers so far it really seems like there's no pretty way to do this. I opened this issue on their tracker, let's see what we get :-) https://github.com/angular/angular.js/issues/7714

最简单的方法是写你自己的 ngMultiple 指令。

The easiest way is to write your own ngMultiple directive.

HTML(相关):

<label><input type="checkbox" ng-model="allowMultiple"> Allow multiple</label>
<hr>
<input
  type="file"
  class="hide"
  accept="image/*"
  ng-multiple="allowMultiple">

JS:

angular
    .module('app', [])
    .controller('appCtrl', function($scope) {
        $scope.allowMultiple = false;
    })
    .directive('ngMultiple', function () {
        return {
            restrict: 'A',
            scope: {
                ngMultiple: '='
            },
            link: function (scope, element) {
                var unwatch = scope.$watch('ngMultiple', function (newValue) {
                    if(newValue) {
                        element.attr('multiple', 'multiple');
                    } else {
                        element.removeAttr('multiple');
                    }
                });
            }
        };
    });

Plunker