簡體   English   中英

觸發所需的驗證angularjs

[英]Trigger required validation angularjs

我有一個選擇與另一個選擇連接,當第一個選擇出現時,第二個選擇成為必需,我通過控制器上的jquery進行選擇

<select id="month-selector" name="month" ng-change="controller.setRequired()">
</select>
<select id="year-selector" name="year">
</select>

//controller
$("#year-selector").prop('required', true);

在我的表單上,我有一個添加按鈕,根據表單的有效性可以啟用/禁用

<button ng-disabled="!controller.myForm.$valid">
    Add
</button>

因此,當我在第一個選擇上選擇一個選項時,我希望按鈕一直處於禁用狀態,直到我在第二個選擇上選擇一個選項時,我才嘗試將第二個選擇設置為臟狀態,以觸發表單無效,但並沒有工作。

//controller
$("#year-selector").prop('required', true);
myForm.customerSinceYear.$setDirty();

您可以在第二個選擇元素上使用ng-required僅在第一個選擇元素具有值時才需要

<select id="month-selector" name="month" ng-model="contorller.month">
</select>
<select id="year-selector" name="year" ng-required="controller.month">
</select>

嘗試這個

 function TestController($scope) { $scope.required = false; $scope.setRequired = function(){ $scope.required = true; } } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="" ng-controller="TestController" > <form name="myForm"> <select id="month-selector" name="month" ng-model="month" ng-change="setRequired()" required> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <select id="year-selector" ng-model="year" ng-required="required"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <button ng-disabled="myForm.$invalid"> Add </button> </form> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM