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

时间:2013-10-01 11:00:20

标签: javascript html angularjs

防止在AngularJS中验证隐藏表单字段的最佳方法是什么?

3 个答案:

答案 0 :(得分:76)

我最初错过了内置的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>

答案 1 :(得分:45)

您也可以使用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>

答案 2 :(得分: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');
      }
  }
});

参见 Fidlle here

在:

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

后:

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