self.Subject = ko.observableArray([
{"Math", "M01" },
{ "Chemistry","M02" },
{ "Physics", "M03" }
]);
self.Teacher = ko.observableArray([
{"M01","Jack"},
{"M01","Mike"},
{"M02","Albert"},
{"M02","Ching"},
{"M03","Rick"}
]);
在第一个列表(未选择)中,我正在使用数学化学和物理,当我点击列表中的数学时,它应该填充杰克和迈克的另一个列表。
答案 0 :(得分:0)
为此,您需要在视图模型中跟踪所选主题。然后,您可以创建一个计算的observable(可用教师)来跟踪要显示的教师。见下文:
https://jsfiddle.net/dw1284/9n36qcdu/
HTML:
<div>
<select multiple data-bind="options: Subjects,
optionsText: 'Name',
value: SelectedSubject,
optionsCaption: 'Choose Subject:'">
</select>
</div>
<div data-bind="visible: SelectedSubject">
Available Teachers:
<ul data-bind="foreach: AvailableTeachers">
<li data-bind="text: Name" />
</ul>
</div>
的JavaScript:
// Subject model
function Subject(id, name) {
var self = this;
self.Id = ko.observable(id);
self.Name = ko.observable(name);
}
// Teacher model
function Teacher(name, subjectId) {
var self = this;
self.Name = ko.observable(name);
self.SubjectId = ko.observable(subjectId);
}
// Main viewmodel
function ViewModel() {
var self = this;
self.Subjects = ko.observableArray([
new Subject('M01', 'Math'),
new Subject('M02', 'Chemistry'),
new Subject('M03', 'Physics')
]);
self.Teachers = ko.observableArray([
new Teacher('Jack', 'M01'),
new Teacher('Mike', 'M01'),
new Teacher('Albert', 'M02'),
new Teacher('Ching', 'M02'),
new Teacher('Rick', 'M03')
]);
self.SelectedSubject = ko.observable();
self.AvailableTeachers = ko.computed(function() {
var array = [];
if (self.SelectedSubject()) {
ko.utils.arrayForEach(self.Teachers(), function(teacher) {
if (teacher.SubjectId() === self.SelectedSubject().Id()) {
array.push(teacher);
}
});
}
return array;
});
}
ko.applyBindings(new ViewModel());