I need an upload form field that may or may not allow the user to select more than one file.
I know I can do something like:
You can use ngSwitch directive for this. Take a look in AngularJs documentation for more details.
https://docs.angularjs.org/api/ng/directive/ngSwitch
In this demo example the directive switch between input file with and without multiple based in a scope param passed for directive using ngSwitch directive.
Demo using ngSwitch
Another idea is to use ngShow/ngHide for this. In this demo example input file is show/hide based in param and have a directive for get input value(s) and set in a $scope param.
Demo using ngShow + directive
I am on mobile, sorry for the short answer.
I would hide two different file inputs, one with the multiple attribute and one without. You can use the ng-if directive to achieve that.
Edit: I'm so sorry, seems like you don't want to do it that way, even though it's completely valid. You could write your own directive for it however, it's really simple.
I come to this page for same issue with Angular 2
And finally fixed like this:
<input type="file"
[accept]="extAccepts"
[multiple]="(maxFiles > 1)" />
Note: both file type (extAccepts) and maxFiles are reading from component as @input() from the user.
Hope it will help for someone!
Try using ng-attr-
ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"
If you prefix any attribute with ng-attr-, then the compiler will strip the prefix, and add the attribute with its value bound to the result of the angular expression from the original attribute value.
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');
}
});
}
};
});
Plunker