13

I have been trying to figure out how to use an array if objects as the key values for an ng-select directive

this is the data I want to use

$scope.selectValues [
    {name: "Options 1", value: "11"}, 
    {name: "Options 2", value: "22"}
    {name: "Options 3", value: "33"}
];

and I want the output to be

<select>
    <option value="11">Options 1</option>
    <option value="22">Options 2</option>
    <option value="33">Options 3</option>
</select>

Can anyone explain how to do this ? and show a an example of the directive set up? I have looked at the docs but they don't have an example that fits for the this model.

||||||
28

ng-options supports both array and object based data source. For example:

Array based data source:

$scope.options = ["Blue", "Red", "Yellow"]

<select ng-model="selected"
        ng-options="for o in options">

Object based data source:

$scope.options = {
  "Blue": "color_1",
  "Red": "color_2",
  "Green": "color_3"
}

<select ng-model="selected"
        ng-options="name for (name, value) in options">

However, you are using an incompatible data structure for the array based option. You can use like this:

<select ng-model="selected"
        ng-options="o.name for o in options">

and use the selected value as selected.value. (selected is bound to one of the objects in the array). This won't work if you want to submit the form via HTTP, so in this case you should convert the options to one of the data structure mentioned above.

I've included these three usage here: http://plnkr.co/IEBQkqJNifY5MZWloDP6


Edit: So I looked at the docs again today and found the way to work with your original data structure.

<select ng-model="selected"
        ng-options="o.value as o.name for o in options">

The plnkr is updated also.

||||||
  • Thanks this worked. The docs on this are very limited but now I changed my data structure and all works fine. Thanks again – Edgar Martinez Dec 19 '13 at 3:40
  • Sorry I overlooked the docs. There's a way to work with the original data structure, please see my edit. – tungd Dec 20 '13 at 13:32
  • @tungd your third example actually does not work. It sets the values to the indices and not to o.value I just realized you need to add "track by o.value" in order for the values to work properly – trattles Mar 16 '15 at 16:36
  • I'm not sure what example you're talking about, could you please add more detail? I checked the Plnkr and all the examples work as expected. Thanks. – tungd Mar 17 '15 at 0:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.