I am trying to ensure a user selects a value from a select box before submitting the form. This works correctly with static options; it however fails when populating the options via a model using ng-options
Example
http://plnkr.co/edit/wRqSCNskLo5c48jy4nQf
I am using AngularJS 1.2.9
Thank you in advance.
In my opinion the correct way to set a default value is to simply pre-fill your ng-model property with the value selected from your ng-options , angular does the rest. Essentially when you define the $scope property your select will bind to assign it the default value from your data array.
In AngularJS when you are using ng-options, you can filter out the options by calling a custom function you have in the controller. Let's say you have following set of employees and when you display all these employees inside HTML select using ng-options, you can see all the employees in a dropdown.
AngularJS ng-options Directive The ng-options directive fills a <select> element with <options>. The ng-options directive uses an array to fill the dropdown list. In many cases it would be easier to use the ng-repeat directive, but you have more flexibility when using the ng-options directive.
Overview. HTML select element with AngularJS data-binding. The select directive is used together with ngModel to provide data-binding between the scope and the <select> control (including setting default values). It also handles dynamic <option> elements, which can be added using the ngRepeat or ngOptions directives.
In your example changing the data bound select to the following fixes the required directive. I'm not sure why exactly.
<select ng-model="selectedValue1" ng-options="opt for opt in ['Mazda2','Maxda3']" required> <option></option> </select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With