Home » Angularjs » Passing value instead of whole object with ng-options

Passing value instead of whole object with ng-options

Posted by: admin January 30, 2018 Leave a comment

Questions:

I’m parsing a .json file and am showing all available options in a select:

<div bo-switch-when="dropdown">
  <fieldset>
      <select ng-options="options.text for option in question.body.options" ng-model="question.answer" ></select>
  </fieldset>
</div>

It is working, but not as I want it to. Instead of getting the whole object to my model, I just want to have the value of this object. Via Chrome Dev Tools:

This object (as in the picture) is in my model. I just want to have the text.

But when i change my ng-options to this:

ng-options="options.text for option.text in question.body.options"

it isn’t working at all…

enter image description here

Answers:

This is actually a pretty common question among Angular developers.

You can use ng-repeat, like so:

<select ng-model="question.answer" >
  <option ng-repeat="option in question.body.options" value="{{option.text}}">{{option.text}}</option>
</select>

Questions:
Answers:

According to ngOptions documentation you can specify the property of the object to be used as options value select as label for (key , value) in object
where select is the property binded to the model and label is the property used as options label.
No need to ngRepeat here.

In your case just use .text property in both select and label :

 <select ng-options="option.text as option.text for option in question.body.options" ng-model="question.answer" >