AngularJS:防止隐藏的表单字段被validation

什么是最好的方式来防止在AngularJSvalidation隐藏的表单字段?

我最初错过了内置的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 /表单中删除它。

 <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'); } } }); 

这里的Fidlle

之前:

 <input id="firstName" name="firstName" required="" remove="" class="ng-scope"> 

后:

 <input id="firstName" name="firstName" remove="" class="ng-scope">