Awa Melvine Awa Melvine - 25 days ago 8
AngularJS Question

Angularjs: dynamically populated option select returns object instead of value

I am trying to dynamically populate the

options
of a
<select>
HTML element in AngularJS with values gotten from the database. According to the documentation, I tried this:

<select
name="student_id"
ng-model="studentData.student_id"
ng-options="student as student.name for student in students track by student.id"
class="form-control">
<option value="">-- choose Agency --</option>
</select>


This worked fine. It populated the
option
select
HTML element and I could see the dropdown values filled with the names of the students and the corresponding value of
option
element was the
student_id
.

The problem now is that when I fill out all the form and attempt to submit, it submits a student object instead of the student_id as the value of the
option select
element.




How do I submit
student_id
instead of the student object?

Answer

In your code, you select your whole student object. Change this line

ng-options="student as student.name for student in students track by student.id"  

To:

ng-options="student.id as student.name for student in students track by student.id"  

Note: I think you should also remove the track by, I guess it does not bring anything here.