我试图让一个指令能够处理<input type="file">在<form>中的验证,因为AngularJS不支持this...It类型的工作来检查文件是否被选中,但是我在表单中也有一个<textarea>,所以当我选择一个文件时,表单获得状态$valid=true,但是只要键入<textarea>,表单就变成了$valid=false,尽管我还没有为<textarea>设置一个验证。这一切为什么要发生?我怎样才能修好它呢?下面是一个简单的例子来说明这个问题:
我的app.js文件:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
app.directive('validFile', function () {
return {
restrict: "A",
require: '^form',
link: function (scope,elem,attrs, ctrl) {
elem.bind("change", function(e) {
console.log("change");
scope.$apply(function(){
ctrl.$valid=true;
ctrl.$invalid=false;
});
});
}
};
});我的index.html文件:
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-form="myForm" >
<input ng-model="filename" valid-file required type="file"/>
<button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary"><i class="icon-white icon-ok"></i> Ok</button>
<div >
<textarea name="observations" rows="3" cols="50" ng-model="observations"></textarea>
</div>
<p>
Input is valid: {{myForm.$valid}} Input is invalid: {{myForm.$invalid}}
<br>Selected file: {{filename}}
<br>Area is valid: {{myForm.observations.$valid}} Area is invalid: {{myForm.observations.$invalid}}
</p>
</div>
</body>
</html>我刚才说的话中有一个有用的观点:http://plnkr.co/edit/k3KZpdX5q3pelWN21NVp?p=preview
发布于 2018-11-20 02:08:39
一个快速的黑客就是像这样把文本区域从ng表格中取出来-
<div ng-form="myForm">
<input id="userUpload" ng-model="filename" archivo-valido
name="userUpload" required type="file"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
</div>
<button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary">
<i class="icon-white icon-ok"></i> Ok
</button>问题是,Form在开始时是invalid,但是您只是将值强制到change上的true。一旦您在textarea中编写了一些东西,Form就会返回到它原来的false值。我不明白你指令中的密码-
错误 范围。$apply(函数()){ if( true ){ //将始终计算为true。那为什么还有其他的部分?ctrl.$valid=true;ctrl.$invalid=false;}{ ctrl.$valid=false;});
更好的方法是在你的每个自定义验证器上写这样的ngModels -
app.directive('archivoValido', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.archivoValido = function(modelValue, viewValue) {
if (ctrl.$isEmpty(modelValue)) {
// consider empty models to be valid
return true;
}
// your custom validation here
...
// it is invalid
return false;
};
}
};
});https://stackoverflow.com/questions/53384807
复制相似问题