Conditional "multiple" attribute in <input type = "file"> with AngularJS
I need a upload form field that may or may not allow the user to select more than one file.
I know I can do something like:
<input type="file" multiple ng-if="allow_multiple"> <input type="file" ng-if="!allow_multiple"> But we know that this is not ideal.
I tried
<input type="file" ng-multiple="allow_multiple"> But that does not work.
It seems that AngularJS does not have such a ngMultiple directive , but they use it all the same (or am I missing something?)
Anyway, what is the best way to do this?
EDIT: from thw answers it still really seems that there is no nice way to do this. I discovered this problem on my tracker, see what we get :-) https://github.com/angular/angular.js/issues/7714
The easiest way is to write your own ngMultiple directive.
HTML (relevant):
<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'); } }); } }; }); Besides the difficulty with this, there is also the problem that some browser will not evaluate multiple="false" (Safari 8 at the file input for ex). Thus, the attribute of plurality should be conditionally written.
I would wrap your html in a directive and conditionally apply an attribute inside the directive, for example:
var input = elem.find('input'); if(condition) input.attr('multiple', 'true'); If the condition can be any attribute of the directive.
I'm on mobile, sorry for the short answer.
I would hide two different file entries: one with several attributes and one without it. To achieve this, you can use the ng-if directive.
Edit: I'm sorry, it looks like you don't want to do this, even if it is fully operational. You could write your own directive for this, but it is really simple.
You can use the ngSwitch directive for this. See the AngularJs documentation for more details.
https://docs.angularjs.org/api/ng/directive/ngSwitch
In this demo, a directory switch between the input file with and without several parameter-based areas passed for the directive using the ngSwitch directive.
Try using ng-attr -
ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}" If you prefix any attribute using ng-attr-, the compiler will strip the prefix and add the attribute with its value associated with the result of the angular expression from the original cost attribute.