2016-11-24 49 views
2

我遇到KnockoutJs問題。我有一個選擇菜單和一個列表,這兩個列表都由相同的locationsArray填充。現在我想用select菜單過濾列表,只有選定的位置(在本例中)保留在列表中。 是否可以隱藏其他列表項目?使用select敲除篩選列表

在此先感謝

<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"}]; 

回答

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

+0

感謝您的快速響應。我介紹了方法,但我得到錯誤: 「knockout.js:72 Uncaught TypeError:無法處理綁定」foreach:function(){return {data:getCurrentLocations(),as:'位置'}}「(...)」 – user2355793

+0

怎麼樣'{data:$ root.getCurrentLocations(),如:'locations'}'?你真的把這個方法添加到你的模型中了嗎? – haim770

+0

不能正常工作。是我複製了你的代碼:) 「消息:this.locations.filter不是函數」 – user2355793