Search code examples
angularjsng-options

How to use ng-options with a dictionary style object?


I have a data source that looks like this:

var options = {
    "A": { name: "Bob", SSN: "111-22-3333" },
    "B": { name: "Sue", SSN: "444-55-6666" }
};

I want to use ng-options to let the user select a person from options above.

I've written HTML that looks like this:

<select ng-model="ctrl.selectedPerson" ng-options="label for (value, label) in ctrl.options"></select>

This results in my being able to select an option, but it shows [object Object] as the select text for each option.

I believe that the problem is that I need to specify that I want to display the name field for the options, but I'm totally confused about the syntax for the ng-options attribute.

How do I use ng-options with this dictionary-style data source?


Solution

  • Close on the syntax - it's value as text for (key, val) in obj - so yours would be:

    ng-options="label as label.name for (value, label) in ctrl.options"
    

    The name property of each object would be the text in the above example - while the value is the entire object.