防止在 AngularJS 中验证隐藏表单字段的最佳方法是什么?
问问题
38800 次
3 回答
77
我最初错过了内置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>
于 2013-10-02T09:00:18.450 回答
46
您也可以使用 ng-if 代替 ng-show 将其从 DOM/表单中完全添加或删除。
<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>
于 2014-11-24T22:49:19.437 回答
1
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">
于 2013-10-01T11:33:02.083 回答