Snæbjørn
Snæbjørn

Reputation: 10792

Set selected value of ng-options on $scope

I want to get/set the selected index + offset of a dropdown on the scope.

So when I select the option called "Third " the $scope.selectedIndex value should be 3. But it's obj3.

Here's what I've come up with so far. I was hoping that track by would fix it, but it didnt :(

Controller

$scope.foos = [obj1, obj2, obj3]

View

<select data-ng-model="selectedIndex"
        data-ng-options="foo.name for foo in foos track by foos.indexOf(foo) + 1">
    <option value=""></option>
</select>

Generated view (the generated value is as expected)

<select data-ng-model="selectedIndex" data-ng-options="foo.name for foo in foos track by foos.indexOf(foo) + 1">
    <option value="" class=""></option>
    <option value="1" label="First">First</option>
    <option value="2" label="Second">Second</option>
    <option value="3" label="Third">Third</option>
</select>

I can't use the array trick

ng-options="idx as choice for (idx, choice) in choices"

Because idx needs to be offset by +1

Plnkr

Upvotes: 1

Views: 895

Answers (1)

James Brierley
James Brierley

Reputation: 4670

Use the value as name syntax:

data-ng-options="foos.indexOf(foo) + 1 as foo.name for foo in foos"

https://plnkr.co/edit/juFXFzlpXmWuS1ukde5R?p=preview

Upvotes: 5

Related Questions