使用select knockout过滤列表

时间:2016-11-24 17:06:09

标签: knockout.js

我遇到了KnockoutJs的问题。我有一个选择菜单和一个列表,它们都由相同的locationsArray填充。现在我想用选择菜单过滤列表,只有选定的位置(在这种情况下)保留在列表中。 是否可以隐藏其他列表项?

提前致谢

 <select data-bind="options: locations,value:selectedOption, optionsText: 'title'"></select> 

     <li data-bind="foreach: { data: locations, as: 'locations' }">
       <a data-bind=text:locations.title"> </a>
     </li>

var viewModel = {locations: ko.observableArray(locationsArray)};ko.applyBindings(viewModel);
var locationsArray =[{title:"Cinema",location:"NY"},{title:"Restaurant",location:"Miami"}];

1 个答案:

答案 0 :(得分:2)

在视图模型中引入以下getCurrentLocations()方法:

var locationsArray =[{title:"Cinema",location:"NY"},{title:"Restaurant",location:"Miami"}];

var viewModel = {
    locations: ko.observableArray(locationsArray),
    selectedOption: ko.observable(''),
    getCurrentLocations: function() {
        var selectedVal = this.selectedOption();

        if (!selectedVal)
            return this.locations;

        return this.locations().filter(function(f) {
            return f.location == selectedVal.location;
        });
    }
};

ko.applyBindings(viewModel);

在你的HTML中:

<li data-bind="foreach: { data: getCurrentLocations(), as: 'locations' }">

请参阅Fiddle