简体   繁体   中英

Angular Select initial value not selected

I have a strange problem with data-binding on select.

Here are the definitions of my objects :

brands =
[
    {
        $$hashKey: "object:18"
        firm: Object
        id: 242
        name: " CONTAGEL "
        regex: null
    },
    ...
]

products = 
[
    {
        $$hashKey: "object:7"
        brand: 
        {
            $$hashKey: "object:613"
            firm: Object
            id: 32
            name: "Level Junior Solaire"
            regex: null
        }
        label: "Level Junior Solaire - LL LEJUS1501"
        productCode: "01646554"
    },
    ...
]

I have a list of brand and a list of products. Each product have a brand (pulled from the brand array).

I want to display the list of product with a select for changing the brand.

<div ng-repeat="p in products">
    Product : {{p.productCode}} 
    <select ng-model="p.brand" ng-options="b as b.name for b in brands">
</div>

The option list is filled with the brand list but not any value is selected. And when i change the value of the select, it changes the brand of the product.

So I don't understand what I have missed.

The issue is with your ng-options . ng-model on select boxes uses references, so unless the object is the same reference, it's not going to be selected by default. In your case, it's a new object and therefore not the same reference, so in ng-model 's eyes, it's not a match. Use track by to match on the id.

ng-options="b.name for b in brands track by b.id"

您可以在示例中看到,Brands变量中的brand对象与product变量中的brand对象不同。

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