简体   繁体   中英

Setting Selected value of Select List

I've got this code for the select

<select class="form-control input-sm" id="drpState"
 data-ng-model="vm.complainant.mState"
 data-ng-options="state.abbreviation for state in vm.states track by vm.complainant.mState">

I've tried a couple different ways that I've seen through SO, but none seem to be setting the option in the drop down. there are 50 options, it should select the one that is currently in vm.complainant.mState.

I'm grabbing an array of State's from a RESTful API. The state abbreviations show up just fine. But one should be selected by my vm.complainant model. Which is another object that was gotten from the API, which is populated correctly. the complainant has a pState property, lets say it comes back as MN, but for whatever reason I cannot set the selected value of that dropdown either through Jquery or through the model.

when I change the value, it updates the complainant.mState property like it is supposed to when bound to the model. but why is it I cannot select a value?

Add state.abbreviation as at the beginning of your options.

<select class="form-control input-sm" id="drpState"
 data-ng-model="vm.complainant.mState"
 data-ng-options="state.abbreviation as state.abbreviation for state in vm.states">

Without the "as" statement you are binding the full object as the value.

This is common for times like item.id as item.description for item in vm.items which would bind the id to your model, but show the description in the dropdown.

Update: After seeing Dylan's comment I tried out a plunker and removing the Track By fixed the issue. See plunkr

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