AngularJS:防止验证隐藏的表单字段
AngularJS: Prevent hidden form fields being validated
防止隐藏表单字段在 AngularJS 中被验证的最佳方法是什么?
我最初错过了内置的ngRequired
指令。还有一个required
标签,这让我感到困惑。
现在,我们可以使用相同的逻辑(我们用来隐藏元素)将ngRequired
设置为 false。
这里有一个实际用例的例子:我想问一下已婚人士他们有多少孩子,但是,如果他们没有结婚,只需隐藏有关孩子的字段。
<form ng-app name="form">
Marital status:
<select ng-model="maritalStatus" required>
<option value="">Select...</option>
<option value="M">Married</option>
<option value="UM">Unmarried</option>
</select>
<div ng-show="maritalStatus == 'M'">
Number of children: <input type="number" ng-model="children" ng-required="maritalStatus == 'M'">
</div>
(for testing) Is this form correctly filled? {{form.$valid}}
</form>
您也可以使用 ng-if 而不是 ng-show 在 DOM/form 中完全添加或删除它。
<div ng-show="maritalStatus === 'M'">
Number of children: <input type="number" ng-model="children" ng-required="maritalStatus == 'M'">
</div>
对此
<div ng-if="maritalStatus === 'M'">
Number of children: <input type="number" ng-model="children" ng-required="true">
</div>
您可以使用指令删除required
属性:
<div ng-app="myApp">
<input type="backbutton" id="firstName" name="firstName" type="text" required/>
var app = angular.module('myApp',[]);
app.directive('input',function($compile){
return {
restrict:'E',
compile:function($tElement,$tAttrs){
console.log("hi there");
var el = $tElement[0];
if(el.getAttribute('type')){
el.removeAttribute('type');
el.setAttribute($tAttrs.type,'');
return function(scope){
$compile(el)(scope);
}
}
}
}
});
app.directive('remove',function($compile){
return {
restrict: 'A',
replace:true,
template:'',
link: function (scope, element, attrs) {
element.removeAttr('required');
}
}
});
在这里看到菲德勒
以前:
<input id="firstName" name="firstName" required="" remove="" class="ng-scope">
后:
<input id="firstName" name="firstName" remove="" class="ng-scope">
相关文章:
- 通过单击动态加载的表中同一行的另一个字段来更新一行的字段
- 添加和删除隐藏字段数组中的值,而不提交表单
- 单击鼠标,用MySQL数据填充html表单输入字段
- 带有条件字段的PHP表单
- 验证PDF表单中的字段
- HTML提交表单,同时包含空字段检查和按钮隐藏
- 在表单中的输入字段上提交事件
- 当所有输入文本字段都为空时,禁止表单提交,但当jquery中的任何字段不为空时允许提交
- 表单输入字段随着溢出的文本而增长
- 如何将onChange方法添加到ExtJS 4表单中的所有字段(textField)中
- 尝试使用名称访问表中字段的日期选取器时出现问题
- Javascript 表单 - 字段不是必需的
- 单击按钮时更改数据库表的字段值
- 数据表将字段值关联到按钮,而 ajax 填充表
- 返回数据表输入字段
- 更改附加表行字段jQuery的名称
- Angularjs表单/字段验证使用JavaScript函数,无需指令
- 仅在Firefox中,表脱离字段集边界
- 如何在表单提交后使用JQuery从附加到HTML表的字段中获取$_POST数组中的值
- 什么's提交表单后,从post数组中动态附加的表行字段中获取值的问题