>当用户单击提交按钮时,我正在验证表单,使用ng-click我正在调用函数,在此函数中我正在传递form1.$invalid,基于此变量,我正在放置条件,如果条件为真,则验证函数将调用,这里的问题是移动是隐藏字段,此隐藏字段还检查验证.如何跳过或不验证移动字段隐藏状态, 我尝试了下面的代码。
.html ----
<form name="form1" novalidate>
<input ng-show="user" type="text" name="user" ng-model="frm1.user" />
<p ng-show="form1.user.$error.required"><span ng-show="errorMsgShow" ng-required="true">{{requiredMsg}}</span></p>
<input ng-show="mobile" type="text" name="mobile" ng-model="frm1.mobile" />
<p ng-show="form1.mobile.$error.required"><span ng-show="errorMsgShow" ng-required="true">{{requiredMsg}}</span></p>
<button ng-click="SubmitForm(regForm.$invalid);">submit</button>
</form>
脚本----
$scope.SubmitForm = function(val){
$scope.user= true;
$scope.mobile = false;
if (if(val ===true){
$scope.validation();
}
}
$scope.validation = function(){
$scope.requiredMsg="input fieldis required";
}
我建议更好的方法是在不需要使用ng-if时将移动输入从表单中删除,而不仅仅是使用ng-show隐藏它。
当条件为假时,Ng-if将确保输入不会呈现在 DOM 树中,因此不会触发验证。
你可以对ng-if和ng-show之间的差异进行一些研究,以更好地了解这两个指令。
尝试 ng-if 以避免验证。如果您希望移动设备跳过验证,请使用表达式将ng-if设置为假。
语法:ng-if="表达式">
转到此链接以获取更多信息
https://docs.angularjs.org/api/ng/directive/ngIf
有关NG-IF和ng-hide/ng-show之间的区别,请参阅以下链接
NG-IF和NG-SHOW/NG-hide有什么区别
一些观察:
- 与其使用
ng-show
来隐藏和显示输入<input type="hidden"... >
只需对mobile
字段使用元素即可。 - 无需使用变量
$scope.user
和$scope.mobile
来隐藏和显示输入。
将 required
属性添加到user
输入字段中,而不是mobile
输入字段中,因为您不想验证移动field
。- 使用
SubmitForm(form1.$invalid)
而不是SubmitForm(regForm.$invalid)
,因为您的表单名称form1
不是regForm
。
演示
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.SubmitForm = function(val) {
console.log(val);
if(val === true) {
$scope.validation();
}
}
$scope.validation = function() {
$scope.requiredMsg="input fieldis required";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<form name="form1" novalidate>
<input type="text" name="user" ng-model="frm1.user" required/>
<p ng-show="form1.user.$error.required">{{requiredMsg}}</p>
<input type="hidden" name="mobile" ng-model="frm1.mobile" />
<button ng-click="SubmitForm(form1.$invalid);">submit</button>
</form>
</div>