ko.utils.arrayFilter Example
HTML
<select data-bind="options: $root.gradeNames, optionsText: 'ProductName', optionsValue: 'ProductName', value: selectedChoice, optionsCaption: 'Product'"></select>
</td>
<td>
<select data-bind="options: $root.filteredItems, optionsText: 'GradeName', optionsValue: 'GradeName', enable:selectedChoice, value: selectedGrade, optionsCaption: 'Grade'"></select>
JavaScript
var obsGrade = function (grade) {
return {
Id: grade.Id,
ProductName: ko.observable(grade.ProductName),
GradeName: ko.observable(grade.GradeName),
Edit: ko.observable(false),
Locked: ko.observable(grade.Locked)
}
}
var viewModel = {
selectedChoice: ko.observable(),
selectedGrade: ko.observable(),
gradeNames: ko.observableArray([
new obsGrade({
Id: 'PA',
ProductName: 'Petroleum',
GradeName: 'A'
}),
new obsGrade({
Id: 'PB',
ProductName: 'Petroleum',
GradeName: 'B'
}),
new obsGrade({
Id: 'PC',
ProductName: 'Petroleum',
GradeName: 'C'
}),
new obsGrade({
Id: 'G1',
ProductName: 'Grains',
GradeName: '1'
}),
new obsGrade({
Id: 'G2',
ProductName: 'Grains',
GradeName: '2'
})])
}
//ko.utils.arrayFilter - filter the items using the selected Product Name
viewModel.filteredItems = ko.computed(function () {
var filter = viewModel.selectedChoice();
if (!filter) {
return viewModel.gradeNames();
} else {
var filtered = ko.utils.arrayFilter(viewModel.gradeNames(), function (item) { (item.ProductName());
return (item.ProductName() === filter);
});
return filtered
}
})
ko.applyBindings(viewModel)