nemo_87 nemo_87 - 14 days ago 7
Javascript Question

Make drop down required only if it has values in AngularJs

I have two drop downs in form. First drop down has 4 values, but second drop down has value only if value with index 3 is selected in first drop down, otherwise is empty.

Code I have always preform validation and checks if both drop downs has values.
Is there an easy way in angular to preform validation for second drop down only if it has values inside of it?
In other words, if drop down is not empty that user has to select value.

This is my code for drop downs:

<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>


As you can see 'subevent' drop down is always required. How can I change it to be required only if it has values inside?

Answer

You can give a condition to ng-required.

You didn't give your controller code, but I will assume that newTestSessionCtrl.formData.event.subevents is equal to [] when empty.

Your condition is then

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