简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM