仅对可见控件应用`$ invalid`

时间:2016-09-14 20:27:26

标签: javascript angularjs

我有一个简单的表单,根据属性data-ng-hide="objective.editMode"显示控件:

<form class="form-horizontal" role="form" name="adduserform">                        
    <div class="form-group">                           
       <label for="title6" class="col-sm-5 control-label">Progress</label>
       <div class="col-sm-6">

          <input data-ng-hide="objective.editMode" type="number" min="0" max="100" 
               data-ng-model="newTask.Progress" class="form-control" required  />
          <input data-ng-show="objective.editMode" type="number" min="0" max="100" 
               data-ng-model="objective.Progress" class="form-control" required  />

       </div>
    </div>    

    <div class="form-group">
       <div class="col-sm-offset-2 col-sm-10">
          <span data-ng-hide="editMode">
             <input data-ng-hide="objective.editMode" type="submit" value="Add" 
                    ng-disabled="adduserform.$invalid" data-ng-click="add()"/>
             <input data-ng-show="objective.editMode" type="submit" value="Save" 
                    ng-disabled="adduserform.$invalid" data-ng-click="Save()" />    
          </span>                 
       </div>
    </div>
</form>

我的问题是adduserform.$invalid可以检查表单上显示的控件吗?由于adduserform.$invalid需要填写所有控件,但并非所有控件都显示在表单上控制的出现取决于objective.editMode

2 个答案:

答案 0 :(得分:1)

您可以使用ng-if代替ng-hide

<input data-ng-if="!objective.editMode" type="number" min="0" max="100" 
           data-ng-model="newTask.Progress" class="form-control" required  />

答案 1 :(得分:1)

隐藏data-ng-hide / data-ng-show的元素仍然在DOM树上,因此被验证。请改用data-ng-if,这将删除DOM中的元素:

<form class="form-horizontal" role="form" name="adduserform">                        
<div class="form-group">                           
   <label for="title6" class="col-sm-5 control-label">Progress</label>
   <div class="col-sm-6">

      <input data-ng-if="!objective.editMode" type="number" min="0" max="100" 
           data-ng-model="newTask.Progress" class="form-control" required  />
      <input data-ng-if="objective.editMode" type="number" min="0" max="100" 
           data-ng-model="objective.Progress" class="form-control" required  />

   </div>
</div>    

<div class="form-group">
   <div class="col-sm-offset-2 col-sm-10">
      <span data-ng-if="!editMode">
         <input data-ng-if="!objective.editMode" type="submit" value="Add" 
                ng-disabled="adduserform.$invalid" data-ng-click="add()"/>
         <input data-ng-if="objective.editMode" type="submit" value="Save" 
                ng-disabled="adduserform.$invalid" data-ng-click="Save()" />    
      </span>                 
   </div>
</div>