我的表单中有一个文件上传控件。我正在使用Angular JS。 当我输入required属性来验证文件是否被选中时,它无效。
<input id="userUpload" name="userUpload" required type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
<button type="submit" class="btn btn-primary"><i class="icon-white icon-ok"></i> Ok</button>
你能否说明为什么要求不起作用?
答案 0 :(得分:40)
ngModelController基于require
等属性在Angular中进行验证。但是,目前使用ng-model服务不支持input type="file"
。为了使它工作,你可以创建一个这样的指令:
app.directive('validFile',function(){
return {
require:'ngModel',
link:function(scope,el,attrs,ngModel){
//change event is fired when file is selected
el.bind('change',function(){
scope.$apply(function(){
ngModel.$setViewValue(el.val());
ngModel.$render();
});
});
}
}
});
示例标记:
<div ng-form="myForm">
<input id="userUpload" ng-model="filename" valid-file name="userUpload" required type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
<button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary"><i class="icon-white icon-ok"></i> Ok</button>
<p>
Input is valid: {{myForm.userUpload.$valid}}
<br>Selected file: {{filename}}
</p>
</div>
答案 1 :(得分:11)
扩展@joakimbl代码我会建议像这样直接
.directive('validFile',function(){
return {
require:'ngModel',
link:function(scope,el,attrs,ctrl){
ctrl.$setValidity('validFile', el.val() != '');
//change event is fired when file is selected
el.bind('change',function(){
ctrl.$setValidity('validFile', el.val() != '');
scope.$apply(function(){
ctrl.$setViewValue(el.val());
ctrl.$render();
});
});
}
}
})
在html中你可以像这样使用
<input type="file" name="myFile" ng-model="myFile" valid-file />
<label ng-show="myForm.myFile.$error.validFile">File is required</label>