Reputation: 12653
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?
Upvotes: 1
Views: 1702
Reputation: 123739
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>
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
Upvotes: 1
Reputation: 9780
ng-disabled="currentYear == -1"
select your default value by doing $scope.currentYear = -1
This will make the second select box disabled if the currentYear model value is '-1'
<select class="form-control input-xsmall select-inline" data-ng-model="currentYear" >
<option value="-1">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"
ng-disabled="currentYear == 'Year'">
<option>Model</option>
<option ng-repeat="model in models" value="{{model.niceName}}">{{model.name}}</option>
</select>
Here is Plunkr example: http://plnkr.co/edit/LIAqMq4TEz9xOCUGPAUs?p=preview
Upvotes: 1