2016-11-23 74 views
0

我在表單中有兩個下拉菜單。第一個下拉菜單有4個值,但是第二個下拉菜單隻有在第一個下拉菜單中選擇了具有索引3的值時纔有值,否則爲空。只有在AngularJs中具有值時才需要下拉菜單

代碼我總是進行驗證並檢查兩個下拉列表是否都有值。 有沒有一種簡單的方法來進行預成型的第二次下拉驗證,只要它的內部有值? 換句話說,如果下拉不爲空,那麼用戶必須選擇值。

這是我的下拉菜單代碼:

<form name="addNewTestSession" class="form-horizontal" novalidate> 
    <div class="row"> 
     <div class="col-md-2" ng-class="{ 'has-error has-feedback': addNewTestSession.event.$touched && addNewTestSession.event.$invalid }"> 
      <label for="event">Event<span class="mandatory">*</span></label> 
      <select id="event" name="event" class="form-control" ng-model="newTestSessionCtrl.formData.event" 
       ng-options="event.name for event in newTestSessionCtrl.viewData.events" 
       ng-required="true"> 
       <option value="" disabled selected>Select</option> 
      </select> 
      <span ng-show="addNewTestSession.event.$touched && addNewTestSession.event.$invalid" 
       class="form-control-feedback fa fa-warning" 
       uib-popover="This field is required." 
       popover-trigger="'mouseenter'" 
       popover-placement="auto right" 
       popover-class="additional-info"></span> 
     </div> 
     <div class="col-md-2" ng-class="{ 'has-error has-feedback': addNewTestSession.subevent.$touched && addNewTestSession.subevent.$invalid }"> 
      <label for="subevent">Sub-Event<span class="mandatory">*</span></label> 
      <select id="subevent" name="subevent" class="form-control" ng-model="newTestSessionCtrl.formData.subevent" 
       ng-options="subevent.name for subevent in newTestSessionCtrl.formData.event.subevents" 
       ng-required="true"> 
       <option value="" disabled selected>Select</option> 
      </select> 
      <span ng-show="addNewTestSession.subevent.$touched && addNewTestSession.subevent.$invalid" 
       class="fa fa-warning form-control-feedback" 
       uib-popover="This field is required." 
       popover-trigger="'mouseenter'" 
       popover-placement="auto right" 
       popover-class="additional-info"></span> 
     </div> 
    </div> 
</form> 

正如你可以看到「子事件」下拉始終是必需的。我如何才能將其更改爲僅在內部具有值時才需要?

回答

1

您可以給ng-required一個條件。

你沒有給你的控制器代碼,但我會假設newTestSessionCtrl.formData.event.subevents等於[]時爲空。

你的條件那麼

<select id="subevent" name="subevent" class="form-control" 
    ng-model="newTestSessionCtrl.formData.subevent" 
    ng-options="subevent.name for subevent in newTestSessionCtrl.formData.event.subevents" 
    ng-required="newTestSessionCtrl.formData.event.subevents.length > 0" 
> 
1

試着這麼做:

ng-required="newTestSessionCtrl.formData.event.subevents.length > 0" 
相關問題