【发布时间】:2018-11-20 01:06:40
【问题描述】:
鉴于 AngularJS 不支持此功能,我正在尝试制作一个能够在 <form> 内处理 <input type="file"> 验证的指令......它可以检查是否选择了文件,但是我在表单中也有一个<textarea>,所以当我选择一个文件时,表单的状态为 $valid=true,但只需输入<textarea>,即使我没有设置验证<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>
我刚才所说的有一个有效的 plnkr: http://plnkr.co/edit/k3KZpdX5q3pelWN21NVp?p=preview
【问题讨论】:
标签: javascript angularjs html