我有一个AngularJS表单,其内容被发送到nodemailer后端。这很好用,使用以下指令将文件上传组件添加到表单:
.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}])
但是,我需要为此添加验证,以便在选择文件之前禁用“提交”按钮。我假设表单看起来像这样:
<div class='form-group'>
<!-- FILE UPLOAD -->
<input type="file" file-model="email.attachment" name="attachment"
class="form-control" accept="application/pdf, application/msword, text/plain" />
<!-- SUBMIT BUTTON -->
<button type='submit' name='submit' class='btn btn-primary'
ng-disabled = 'userForm.$invalid' value = 'Send'
ng-click = 'uploadFile()'>Submit</button>
</div>
我理解标准所要求的&#39;不适用于文件模型,我找不到正确程序的示例。 我该如何修改指令以实现验证?
答案 0 :(得分:0)
使用$ rootScope:
在您的主控制器中:
$ rootScope.fileUploaded = false;
.directive('fileModel', ['$parse','$rootScope', function ($parse,$rootScope) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
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;
}
});
});
}
};
}])
在您看来:
<div class='form-group'>
<!-- FILE UPLOAD -->
<input type="file" file-model="email.attachment" name="attachment"
class="form-control" accept="application/pdf, application/msword, text/plain" />
<!-- SUBMIT BUTTON -->
<button type='submit' name='submit' class='btn btn-primary'
ng-disabled = '!fileUploaded' value = 'Send'
ng-click = 'uploadFile()'>Submit</button>
</div>