Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a <select> be bound to an array by index in Angular.js?

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.

like image 631
Sijmen Mulder Avatar asked Jul 22 '13 14:07

Sijmen Mulder


1 Answers

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

  • select is what the value of the model should be when that item is selected
  • label is the text to display

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.

like image 117
John Ledbetter Avatar answered Nov 08 '22 14:11

John Ledbetter