[英]How to validate files with required in angularjs?
嗨,我正在开发angularjs应用程序。 我有文件上传模块。 下面是我的html代码。
<input type="file" file-modelsr="myFileID" name="fileupld" valid-files required />
在提交表单时,我正在尝试获取以下内容。
console.log(form2.fileupld.$valid);
这总是让我不确定。 如何在提交表单时检查文件是否已上传?
我用下面的指令。
myapp.directive('validFiles', function () {
return {
require: 'ngModel',
link: function (scope, el, attrs, ngModel) {
//change event is fired when file is selected
el.bind('change', function () {
debugger;
scope.$apply(function () {
ngModel.$setViewValue(el.val());
ngModel.$render();
})
})
}
}
})
我使用以下指令上传文件。
myapp.directive('fileModelsr', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModelsr);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
如何在AngularJS中应用所需的文件验证?
您可以将fileModel
指令更改为以下内容,并摆脱validFiles
指令。 检查您的fileModelsr
是否具有任何值,然后根据此值进行验证。
JS :
.directive('fileModel', ['$parse', '$rootScope', function($parse, $rootScope) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModelsr);
var modelSetter = model.assign;
element.bind('change', function() {
scope.$apply(function() {
modelSetter(scope, element[0].files[0]);
if (element[0].files[0]) {
$rootScope.fileUploaded = true;
}
});
});
}
};
}])
HTML :
<input type="file" file-modelsr="myFileID" name="fileupld" required />
<button type="submit" name="submit" class="btn btn-primary" ng-disabled="!fileUploaded" ng-click="uploadFile()">Submit</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.