Reputation: 87
I am having problems with KnockoutJs. I have a select menu and an list which are both populated by the same locationsArray.Now i want to filter the list with the select menu that only the selected Location(in this case) stays in the list. Is it possible to just hide the other list Items?
Thanks in advance
<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"}];
Upvotes: 2
Views: 1954
Reputation: 49115
Just introduce the following getCurrentLocations()
method in your view-model:
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);
And in your HTML:
<li data-bind="foreach: { data: getCurrentLocations(), as: 'locations' }">
See Fiddle
Upvotes: 2