Reputation: 153
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
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:
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:
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 ""
)"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