I want to add an html select with options AM,PM with angularjs, what i need is having the key and the value of the option be the same :
<option value="AM">AM</option>
<option value="PM">PM</option>
My html looks like this
<select ng-model="ampm" ng-options="k as v for (k , v) in ampms"></select>
and my controller looks like
$scope.ampm = (new Date().getHours()) >= 12 ? 'PM' : 'AM';
$scope.ampms ={"AM":"AM","PM":"PM"};
and every thing working fine.
My question is why i cant have the same thing when i used an array (i tried all the options in the ng-options) as this
$scope.ampms =["AM","PM"];
what ever i do i always get this
<option value="0">AM</option>
<option value="1">PM</option>
What i want is using an array like above with the option has the key and the value the same.
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.
ng-repeat creates a new scope for each iteration so will not perform as well as ng-options. For small lists, it will not matter, but larger lists should use ng-options. Apart from that, It provides lot of flexibility in specifying iterator and offers performance benefits over ng-repeat.
Use ng-init to set default value for ng-options .
This is is a default behavior of ng-options in Angular. If you do not specify a key name, angular will automatically choose to use the index rather than a key. The code that does that can be seen on line 405 in /src/ng/directives/select.js on Angular's Github repository.
It can't even be forced by "value as value for (index, value) in values".
But as dnc253 just beat me to the punch with his answer (it showed up while I was typing)... you don't have to worry about it, Angular does it all for you automatically.
With AngularJS, you don't need to worry about what the value of the option is. All the selects I've seen with ng-options
have values of 0 through whatever. If you're just looking for a dropdown with the two options, it can be as simple as
<select ng-model="ampm" ng-options="currOption for currOption in ['AM', 'PM']"></select>
See http://jsfiddle.net/EyBVN/1/
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