Nick
Nick

Reputation: 19684

AngularJS Select and ng-options: Can I bind and object to ng-model while only displaying a property?

I'm binding a select element to data that looks like this:

  var gearConditions = [
    { id: 1, value: 'New' },
    { id: 2, value: 'Like New' },
    { id: 3, value: 'Excellent' },
    { id: 4, value: 'Good' },
    { id: 5, value: 'Fair' },
    { id: 6, value: 'Very Used' },
    { id: 7, value: 'Other' }
];

My select looks like this:

  <select name="condition"
          class="form-control"
          ng-model="postModel.condition"
          ng-options="condition.id as condition.value for condition in gearConditions">
  </select>

This binds condition.id to the ng-model and displays condition.value as the select option. My question is: can I keep the current behavior but bind the whole object to the ng-model?

For example if the first option is selected the model value would then be {id:1, value: 'New'} rather than just 1.

Is this possible or do I need to use ng-changed to accomplish this?

Thanks!

Upvotes: 1

Views: 1631

Answers (2)

developer10
developer10

Reputation: 1500

I think you you try similar:

// I took this from my code
ng-options="key as value for (key, value) in ...

Now you could try to combine key+value and see if it appears like you wish.

Upvotes: 0

tymeJV
tymeJV

Reputation: 104785

Yes, change condition.id to condition:

ng-options="condition as condition.value for condition in gearConditions"

Upvotes: 2

Related Questions