Todd Davis Todd Davis - 1 year ago 63
AngularJS Question

Angular ng-options how to bind to one property, not entire object?

I am using ng-options to create a Select from an array of objects. This is working just fine, and for the purposes of this question, the content of the objects is somewhat unimportant, just suffice to say they have a name property, a value property, and a few other properties.

Below is the code that I'm using to create the Select, and so far it is working just fine.

Here's my question - when an option is selected, what gets bound to the ng-model is the "entire object" (fl). What I'd like to be bound to ng-model is just the "name" (i.itemName) part of the object.

I suppose I can fix this by going back after the fact, and when the submit button is pressed, I can loop through all data, find the bound object, extract the name from it and then change it so it's not bound to the name, but... that's rather sloppy and not really how it should be handled.

Is there a way to change this code so that when I select an item, ng-model is bound to i.itemName and not fl?

<select chosen
ng-options="i.itemName for i in fl.combo_ItemList.itemList track by i.itemValue"
style="width: 100%;">

Answer Source

You may use the following code if you want to bound the ng-model to itemName. Do note that you need to remove track by here for it to work as it will evaluates to undefined and the model value will not match to any options.

i.itemName as i.itemName for i in fl.combo_ItemList.itemList.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download