为了能够使用该选项绑定,您需要确保还应用了value
绑定到它来标记哪个项目被选中。然后你可以使questions
array 一个计算的可观察量,将根据所选值返回一组经过过滤的问题。
Environment Type: <select id="qEnv" data-bind="value: selectedEnvironment, options: envTypes, optionsCaption: 'Select...', optionsValue: 'envId', optionsText: 'envName'"></select>
还要确保使用您创建的映射数组初始化可观察数组。大学教师
不要像你那样更换它们。 (尽管在本例中这并不重要,因为数组没有被修改)
function viewModel() {
var self = this;
// initialize the array with the mapped array
self.envTypes = ko.observableArray(ko.utils.arrayMap(environments, function(item) {
return {
envName: item.Text,
envId: item.EnvId
};
}));
// this tracks our selected environment value
self.selectedEnvironment = ko.observable();
// return a filtered array where the items match the selected environment
self.questions = ko.computed(function () {
return ko.utils.arrayFilter(quests, function (item) {
return item.EnvId == self.selectedEnvironment();
});
});
}
您可能希望根据问题数组是否为空来显示问题或消息,因此您必须调整测试。
data-bind="if: questions().length"
环境有重复EnvId
值,所以我更新了这些值并添加了optionsCaption
绑定以增加效果。
更新了小提琴