Search code examples
javascriptjsonangularjsng-options

Select only the property names of a JSON object with ng-options


I have a JSON object in my scope as follows:

$scope.props =
{
    'prop1': { 'att': 10 },
    'prop2': { 'att': 20 },
    ...
    'propN': { 'att': 42 }
};

I bind this object to a select using ng-options:

<select ng-options="propName for (propName,propVal) in props"
        ng-model="selectedProp"></select>

The options prop1, prop2, etc. show up in the drop-down box. When I select one of these options, the propVal is stored in selectedProp.

However, I need to store the actual property name, not its value. I can completely ignore the value - all I need is the selected property name string, such as "prop2".

Is this possible in AngularJS?


Solution

  • Does this work for you?

    <select ng-options="key as key for (key , value) in props"
            ng-model="selectedProp"></select>
    

    You can find more info in angular docs, but basically key as key refers at value_to_store as value_to_display. So you want to store in the model the property name (key) of the selected object and display it as that same property name.