AngularJS:防止验证隐藏的表单字段

AngularJS: Prevent hidden form fields being validated

本文关键字:表单 字段 隐藏 验证 AngularJS      更新时间:2023-09-26

防止隐藏表单字段在 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">