How to validate select elements using AngularJS


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 ng-repeat="year in years" value="{{year}}">{{year}}</option>
<select  class="form-control  input-xsmall select-inline" data-ng-model="currentModel">
    <option ng-repeat="model in models" value="{{model.niceName}}">{{}}</option>

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


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  class="form-control  input-xsmall select-inline" data-ng-model="currentModel" 
   ng-options ="model.niceName as for model in models track by model.niceName">
    <option value="">Model</option>


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

  • ng-options ="model.niceName as 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 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.