Knockout linked DropDownList ko.observableArray()

2019-06-08 16:37发布

问题:

The main question is that I need to link two select. When I choose one country in the first select the second must display the states of the selected country.

What I got, The custom Binding:

 ko.bindingHandlers.chosen = {
        init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
            $(element).chosen();            
        },
        update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
            $(element).trigger("liszt:updated");         
        }
};

var viewModel = {
Comunidades : ko.observableArray([
    {"name": "Comunidad Valenciana" ,
     "id" : 0, "provincias": 
        [{"name" : "Alicante", "id": 0},
         {"name": "Valencia", "id" : 1},
         {"name": "Castellon", "id" : 2}
        ] } ,
    {"name": "Madrid" , "id" : 1 },
    {"name": "Murcia" , "id" : 2 }]
),
    ]),
selectedOne : ko.observableArray(),

ko.applyBindings(viewModel);

With this I display the first array in a HTML select, but I don't know how to display the 'Provincias' inside the first option for example.

I'll try to make a demo.

<link rel="stylesheet" href="http://harvesthq.github.com/chosen/chosen/chosen.css" />  
<select data-bind="options: Comunidades , value: selectedOne, chosen : true, optionsText: 'name', optionsValue: 'id'   "  class="chzn-select" style="width:300px;" ></select>

<select data-bind="options: Comunidades , value: selectedTwo, chosen : true, optionsText: 'name', optionsValue: 'id'   "  class="chzn-select" style="width:300px;" ></select>

<p data-bind="text: selectedOne"></bind>
<p data-bind="text: selectedTwo"></bind>

http://i.imgur.com/shqlFVp.png?1

回答1:

http://jsfiddle.net/benfosterdev/wHtRZ/

])

There is the example I inspired in. Using a cascade DropDown List with Knockout, also helped the Papa example.