aluknot
aluknot

Reputation: 504

Link two select in AngularJS with JSON

So, i tried with this Link two select boxes using angular js, but don't know how to use this formula in my case with this JSON:

{
    "option1": [{
        "countries": [
            {
                "currency": "ARS"   
            },
            {
                "currency": "USD"  
            }
        ]
    }],
    "option2": [{
        "countries": [
            {
                "currency": "EUR"   
            },
            {
                "currency": "GBP"  
            }
        ]
    }],
    "option3": [{
        "countries": [
            {
                "currency": "RU"   
            },
            {
                "currency": "TR"  
            }
        ]
    }]
}

The first select should have option1, option2, option3. And if option1 is selected, the second select should have ARS and USD.

What is the proper way to do this?

UPDATE1: i did something similar like @Joaozito Polo answered, but tried to set the default values with ngModel in both selects and when i change the first select, the second get blank.

UPDATE2: now i get it and is working, buuuuuuut.... only in the jsbin, i don't understand why isn't working in my real code. When i do:

<select ng-options="value as name for (name, value) in options" ng-model="currentOption" ng-change="showSomething()"></select>

and in ngChange do a console log like this:

$scope.showSomething = function() {
    console.log($scope.currentOption);
};

I get the same option all the time, but in jsbin the option change :/ i am working with ionic and cordova, maybe is a bug?

UPDATE3: found this, working perfect right know. Is this a good solution? why with ionic doesn't work? i wan't to understand this behavior.

Thanks in advance

Upvotes: 0

Views: 109

Answers (1)

Joao Polo
Joao Polo

Reputation: 2163

Considering your data model, as is, as a variable "options"...

You need to use (key, value) on ng-options:

Option
<select ng-options="value as name for (name, value) in options" ng-model="currentOption"></select>

Currency
<select ng-options="item as item.currency for item in currentOption[0].countries" ng-model="currency"></select>

look at this jsbin: jsbin

Upvotes: 1

Related Questions