Iterate with ng-options in a dictionary(object) [closed]
Asked Answered
S

1

19

I need to iterate over the following object with ng-options:

var a = {
'optionName1': 'optionValue1',
'optionName2': 'optionValue2',
'optionName3': 'optionValue3',
'optionName4': 'optionValue4',
};

I get this object in this format from a 3rd party resource, and I'd rather no to re-arrange it manually.

I already did a Google search, and looked into the documentation, it deals with lists, and lists of objects only from what I could tell.

Sibella answered 18/9, 2013 at 10:9 Comment(0)
T
32

For a model like this:

$scope.options = {
    'optionName1': 'optionValue1',
    'optionName2': 'optionValue2',
    'optionName3': 'optionValue3',
    'optionName4': 'optionValue4',
};

You can create options like this:

<select ng-change="change()" ng-model="votes.status" 
ng-options="v for (k,v) in options">
</select>
Tanked answered 18/9, 2013 at 10:14 Comment(6)
My bad, didn't had ng-model set up. Probably was too hungry before launch timeSibella
And the parentheses (k,v) matter.Aindrea
Huh. Thats almost pythonesque. Neat.Lithiasis
Good! Only one thing to point out is that you can rename as you like, maybe k and v doesn't make any sense to you. You can do something like this: ng-options="value for (id,value) in optionsChantellechanter
This is working, however, the ng-model get's Value ('optionValue1') what if we need to show Value in dropdown, but upon selection, model should get key. For example, upon selection of 'optionValue1' the model should hold 'optionName1'Sporades
i think it should be k for (k,v) in optionsAmaranthaceous

© 2022 - 2024 — McMap. All rights reserved.