Mike Rouse
Mike Rouse

Reputation: 1298

Angular Select List Binding an Object when I was expecting a Value

I wonder if I am going about this all wrong, but here's the issue.

I have a Select List configured like so:

<select name="{{ measure.Name }}_MeasureId"
    ng-model="CompleteDataSetViewModel.AnnualRecord.TargetHazardousWaste_Original_MeasureId"
    ng-options="obj.Text for obj in measure.AnnualTarget_Measure_SelectList track by obj.Value"
    ng-init="CompleteDataSetViewModel.AnnualRecord.TargetHazardousWaste_Original_MeasureId = measure.AnnualTarget_Measure_SelectList[measure.InitialFigure_Measure - 1]"
    class="" required></select>

This outputs what I want:

<option selected="selected" value="?"></option>
<option value="13">Metric Tonnes  </option>
<option value="14">Imperial Tonnes</option>
<option value="15">Short Tonnes   </option>

What I then want in my JSON is the value of CompleteDataSetViewModel.AnnualRecord.TargetHazardousWaste_Original_MeasureId to be set to a numeric value of let's say 13. However, what I actually get is an object like this:

"TargetHazardousWaste_Original_MeasureId": {
  "Text": "Metric Tonnes  ",
  "Value": "13",
  "Selected": false
},

This is somewhat correct - the right item is picked, but what I am after is simply the 13 as that is the value I want to write to my database.

I have considered doing some kind of mapping exercise to effectively extract the value and assign it, but that feels counter to what Angular appears to be about (I've only been at it 2 days).

I've tried the Angular documentation, but that's left me feeling more confused. Is there something I am missing?

Upvotes: 0

Views: 39

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

Change your ng-options to this:

obj.Value as obj.Text for obj in measure.AnnualTarget_Measure_SelectList track by obj.Value

Without that, you're making it so the one they select is the entire object.

Upvotes: 1

Related Questions