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-show の代わりに ng-if を使用して、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 に答える