2013-10-01 36 views
52

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

+1

等都可能只是删除了'required'属性,当你隐藏了它? – Cherniv

+0

如果你有代码,请发布它来帮助我们,有足够的选项来实现你的逻辑,但是不要从头开始,而只是改变你的代码。小提琴/ PLUNKER会很棒 –

+0

有没有人回答你的问题?许多人只是给你选择禁用所需的验证,但没有任何其他......像,数字......或者我错过了什么? – genuinefafa

回答

72

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

很简单,谢谢。我有一个子表单,它阻止了主表单的有效性,因为子表单(不可见)的文本字段具有ng-required =“true”指令。现在一切都按预期工作! – Sebastian

+0

这将完全奏效;只要注意ng-if创建一个隔离范围...如果你没有考虑到这一点,可能会导致一些不良影响。 – djdmbrwsk

+0

这里有一种情况 - 首先我选择已婚并且进入了no。的儿童和后来选择未婚。现在,当我提交表单时,孩子的价值也被提交。我如何防止提交儿童的价值? – Puni

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"> 
+0

Fidlle什么也没做!? – IamStalker

+0

它从'input'中删除'required'。你可以调试它,并检查在开始时你有“必需”。 –

+0

ahhh好的抱歉没有注意到它。 – IamStalker

38

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

如果您想要避免验证多个元素,或者验证比仅检查元素是否为空时更复杂,ng-if可以很好地工作。这假设你也想隐藏元素。 –

+0

所以基本上你是删除一切,甚至用户输入? – Vignesh

+0

整个div和这个地方的内容,但你也可以在输入中使用ng-if,并跳过div。 – SoEzPz