Say I have this:
$scope.items = ["foo", "bar", "baz"];
$scope.index = 1;
How do I bind that to a <select>
?
I tried: <select ng-model="index" ng-options="i for i in items">
but then a blank option is selected at load time.
This: <select ng-model="items[index]" ng-options="i for i in items">
seems to work initially but when changing the selection, the value at items[index] is changed, which is obviously not what we want.
My workaround is to map the array to {num, title} pairs but that logic clutters up the controller.
Try the following:
<select ng-model="index" ng-options="i as name for (i, name) in items">
If you check the ng-options documentation, you'll see one of the supported forms is
select as label for value in array
We've combined that with the (key, value)
grouping, which you can use to get access to the key in the object (or in this case, index in the array).
Edit: I'm seeing the same issue you're seeing. A comment on the angular docs recommends this approach instead:
<select ng-model="index" ng-options="items.indexOf(item) as item for item in items">
Which IMO is not quite as clean, but seems to work.
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