简体   繁体   中英

AngularJS select element value is an object, why?

I have a JSON object like:

{
    "9000A": {
        "LOCname":"A Location"
        "LOCid":"9000A"
    },
    "2700C": {
        "LOCname":"C Location"
        "LOCid":"2700C"
    },
    "7600B": {
        "LOCname":"B Location"
        "LOCid":"7600B"
    }
}

I need to sort it by LOCname to display in a select list, I do this using a custom filter that turns the JSON object into an array:

<select name="location" ng-model="formData.location" ng-options="loc.LOCname for loc in (locations | json2array | orderBy:'LOCname') track by loc.LOCid">
    <option style="display:none" value="" disabled selected>Choose a location.</option>
</select>

This works great my options look like:

<option value="9000A" label="A Location">A Location</option>
<option value="7600B" label="B Location">B Location</option>
<option value="2700C" label="C Location">C Location</option>

My problem is that formData.location is now equal to an object:

{"LOCname":"A Location","LOCid":"9000A"}

Expected result is that formData.location would be equal to "9000A"

Anyone able to explain why this is happening and how to fix it?

because of the way u use ng-options

if you use ng-options as

ng-options="color.LOCid as loc.LOCname for loc in (locations |..."

you can select the ID

explanation

color.LOCid as loc.LOCname for loc in (locations |...

location is the array we need to iterate

loc is a single object loc.LOCname for 'loc.LOCname' is the value we need to show

color.LOCid in is the value of selected option

(if you do not set "color.LOCid in") by default is select the whole object in your case its loc

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