57

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

4

3 回答 3

77

我最初错过了内置ngRequired指令。还有一个required标签,这让我很困惑。

现在,我们可以使用相同的逻辑(用于隐藏元素)来设置ngRequiredfalse。

这是一个实际用例示例:我想问已婚人士他们有多少孩子,但是,如果他们没有结婚,只需隐藏关于孩子的字段。

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

Fidlle here

前:

<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 回答