How to validate select elements using AngularJS

Issue

I have the following HTML on my page, where I have 2 select elements. I want them both to be required. I want the second element currentModel to remain disabled until the first one is selected with a value other than Year, which is my default value.

<select class="form-control  input-xsmall select-inline" data-ng-model="currentYear" >
    <option>Year</option>
    <option ng-repeat="year in years" value="{{year}}">{{year}}</option>
</select>
<select  class="form-control  input-xsmall select-inline" data-ng-model="currentModel">
    <option>Model</option>
    <option ng-repeat="model in models" value="{{model.niceName}}">{{model.name}}</option>
</select>

Could somebody help me with how to validate the select elements like this?

Solution

All you need to use is ng-model and ng-options instead of manually creating options via ng-repeat. Let angular create options for you.

<select class="form-control  input-xsmall select-inline" data-ng-model="currentYear"
          ng-options="year for year in years track by year">
    <option value="">Year</option>
</select>

<select  class="form-control  input-xsmall select-inline" data-ng-model="currentModel" 
   ng-disabled="!currentYear" 
   ng-options ="model.niceName as model.name for model in models track by model.niceName">
    <option value="">Model</option>
</select>

Plnkr

  • ng-options="year for year in years track by year" follows the syntax label for value in array

  • ng-options ="model.niceName as model.name for model in models track by model.niceName" follows the syntax select as label for value in array

  • Just set the ng-model for both the selects. In case of models since i used select as syntax (model.niceName as model.name) the currentModel will have niceName property of the selected item. if you remove select as part from the model it will have the respective model object.

  • set an ng-disabled on the 2nd select based on value of currentModel

since there is a track by bug with ng-select when dealing with objects we need to go with as syntax

Answered By – PSL

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.