我为演示这个问题创造了一个小提琴 - https://jsfiddle.net/fomigo/9rug9b7c/
视图模型:
ko.bindingHandlers.selected = {
update: function(element, valueAccessor, allBindingsAccessor) {
allBindingsAccessor().options();
$(element).val(valueAccessor()).trigger('change');
}
};
var VM = function(countries, states, cities) {
var self = this;
self.countries = ko.observableArray(countries);
self.states = ko.observableArray(states);
self.cities = ko.observableArray(cities);
self.selectedCountry = ko.observable(undefined);
self.selectedState = ko.observable(undefined);
self.selectedCity = ko.observable(undefined);
self.stateOptions = ko.pureComputed(function() {
return ko.utils.arrayFilter(self.states(), function(state) {
return state.countryId == self.selectedCountry();
});
});
self.cityOptions = ko.pureComputed(function() {
return ko.utils.arrayFilter(self.cities(), function(city) {
return city.stateId == self.selectedState();
});
});
};
模特 - 可以在小提琴中看到。
查看:
<select data-bind="
options: countries,
optionsValue: 'id',
optionsText: 'name',
value: selectedCountry,
selected: 2,
optionsCaption: 'Choose country...'
"></select>
<select data-bind="
options: stateOptions,
optionsValue: 'id',
optionsText: 'name',
value: selectedState,
selected: 7,
optionsCaption: 'Choose state...'
"></select>
<select data-bind="
options: cityOptions,
optionsValue: 'id',
optionsText: 'name',
value: selectedCity,
selected: 14,
optionsCaption: 'Choose city...'
"></select>
在用户实际选择某些内容之前,需要在选项绑定中选择值。 它在网站的仪表板中进行 - 有两种形式,a)用于添加项目; b)用于编辑项目。 当然,我希望它只是一种形式。因此需要在保存项目后预选值。 我不想将我的ViewModel移动到PHP代码来设置默认值。
如果你改变国家,国家&amp;城市下拉列表添加了奇怪的空选项和隐藏的标题。
那么,我做错了什么?
感谢。
P.S。抱歉我的英文,plz =)
答案 0 :(得分:0)
可以使用几个计算器来实现,实现默认选择逻辑(updated fiddle):
ko.computed(function() {
var firstState = self.stateOptions()[0];
if(!self.selectedState() && firstState) {
self.selectedState(firstState.id);
}
});
ko.computed(function() {
var firstCity = self.cityOptions()[0];
if(!self.selectedCity() && firstCity) {
self.selectedCity(firstCity.id);
}
});
如果您只需要重置为&#34;选择某个...&#34;值,您可以将选择重置为未定义(jsfiddle):
self.stateOptions = ko.pureComputed(function() {
self.selectedState(undefined);
return ko.utils.arrayFilter(self.states(), function(state) {
return state.countryId == self.selectedCountry();
});
});
self.cityOptions = ko.pureComputed(function() {
self.selectedCity(undefined);
return ko.utils.arrayFilter(self.cities(), function(city) {
return city.stateId == self.selectedState();
});
});