Ravindhar Konka
Ravindhar Konka

Reputation: 153

<select> with selection to equal the index of the source array

I want to select the index of the selected item in the array data source. Or, put it in other words, I want the value attribute of an <option> to equal the index value, e.g. 0, 1, 2, ...:

<select name="networkname" class="form-control" id="networkname" ng-model="selectedNetwork" ng-options="network.id as network.name for network in networksList" ng-change="get($index)"</select>

Then my output HTML is:

<option value="object:57" label="A5 (2 cores, 14336 MB)" selected="selected">A5 (2 cores, 14336 MB)</option>
<option value="object:58" label="A6 (4 cores, 28672 MB)">A6 (4 cores, 28672 MB)</option>

But I want the value to be:

<option value="0" label="A5 (2 cores, 14336 MB)" selected="selected">A5 (2 cores, 14336 MB)</option>
<option value="1" label="A6 (4 cores, 28672 MB)">A6 (4 cores, 28672 MB)</option>

This is the source array:

$scope.networkList = [
 {id: "A5", name: "A5 (2 cores, 14336 MB)", cpus: 2, disk: null, memory: "14.0 GB"},
 {id: "A6", name: "A6 (4 cores, 28672 MB)", cpus: 4, disk: null, memory: "28.0 GB"}
];

Upvotes: 1

Views: 216

Answers (1)

New Dev
New Dev

Reputation: 49590

There are 2 ways to do this with Angular (1.2.x and 1.3.x) that I know of - neither one is perfect:

  1. treat the source array as an object source
  2. generate options with ng-repeat

So, assuming the following VM:

$scope.items = [{id: "a", n: "b"}, ...]

Alternative #1

<select ng-model="selectedIndexStr" 
        ng-options="idx as item.n for (idx, item) in items">

Drawbacks:

  1. selectedIndexStr will be a string, not an integer, because idx is treated as a property key of an object, not an index of an array. This may or may not work for you, but, to illustrate, if you wanted to set the ng-model to a default value, it would have to be $scope.selectedIndexStr = "0" (notice the "")
  2. The order will be based on string comparison of index values. So, if you had more than 10 items, the order would be: "0", "1", "10", "11", "2", "3", ...

Alternative #2

<select ng-model="selectedIndex">
  <option ng-repeat="item in items" value="{{$index}}" 
          ng-selected="selectedIndex === $index">{{item.n}}</option>
</select>

Drawback here is that it is more verbose as it doesn't use ng-options

Here's a plunker showing the alternatives

Off-topic:

In a typical case, though, one would want the actual selected object, or sometimes - a property of that object. If you rely on an index of the array where the object is stored, then perhaps you should re-evaluate your ViewModel design.

So, the following would make the most sense to me:

<select ng-model="selectedItem" ng-options="item as item.n for item in items">

or,

<select ng-model="selectedItemId" ng-options="item.id as item.n for item in items">

Upvotes: 1

Related Questions