Search code examples
javascriptangularjsionic-frameworkangularjs-ng-optionsangularjs-ng-init

Ng-init from an ng-repeat


I have a list of products, you can see the JSON :

var panier =
    {
        "Client": "Ben",
        "Date":"",
        "Produits": [
            {
                "Id": "188", 
                "Name":"Name1",
                "Qte": "5", 
                "Variante": 
                "20 Pcs",
                "Prix" :"149.00"
            },
            {
                "Id": "231",
                "Name":"Name2",
                "Qte": "2", 
                "Variante": "7 encas de 35g",
                "Prix" :"109.00"
            },
            {
                "Id": "232", 
                "Name":"Name3",
                "Qte": "7", 
                "Variante": "10 pieces",
                "Prix" :"99.00"
            }
        ]
    };

I do a list with ionic to retrieve the products and it all works.

Inside of the list Item when I do (for example the firsr item) Qte = {{product.Qte}} it gives me Qte = 5

But when I want to put the quantity on a select it doesn't work with the ng-init :

<select 
    ng-model="selectedQte"
    ng-init="selectedQte = {{product.Qte}}"
    ng-options="selectedQte for selectedQte in range('10')"
    ng-change="product.Qte = selectedQte">
</select>

I have tried :

ng-init="selectedQte = product.Qte"

and :

ng-init="selectedQte = {{product.Qte}}"

But nothing happens. When I have tried :

ng-init="selectedQte = 3"

I have a 3on my 3 selects.

But I want 5 on the first one, 2on the second and 7on the third.

Any help is needed, thanks !


Solution

  • Looks like the problem is with the dataType of the Qte in the JSON is string & the array created for range is sequence of number. You need to convert the JSON coming from response to number instead of string will do the trick. You could directly bind the Product.Qte to your ng-model.

    Markup

    <select ng-model="product.Qte"
        ng-options="selectedQte for selectedQte in range('10')">
    </select>