In Knockoutjs is it possible to have a condition for the child elements for a options binding
e.g:
viewModel.array([{name: 1, show: true}, {name: 2, show: false}, {name: 3, show: true}]);
<select data-bind="options: array, optionsText: name, if: show"></select>
will show in select box:
1
3
In Knockoutjs is it possible to have a condition for the child elements for a options binding
e.g:
viewModel.array([{name: 1, show: true}, {name: 2, show: false}, {name: 3, show: true}]);
<select data-bind="options: array, optionsText: name, if: show"></select>
will show in select box:
1
3
Share
Improve this question
edited Aug 17, 2012 at 7:37
nehz
asked Aug 17, 2012 at 7:21
nehznehz
2,1823 gold badges23 silver badges37 bronze badges
2 Answers
Reset to default 3Checkout this demo
You can do it like this :
<select data-bind="value: selectedCountry , foreach : countryArray" >
<!-- ko if: show -->
<option data-bind="value : name, text : name "></option>
<!-- /ko -->
</select>
function viewModel() {
var self = this;
this.countryArray = ko.observableArray([{"name" : "France" ,"show" : true},
{"name" : "Italy" , "show" : true},
{"name":"Germany" , "show" : false}]);
this.selectedCountry = ko.observable("");
}
$(document).ready(function() {
var vm = new viewModel();
ko.applyBindings(vm);
})
Try this demo
Here's a 2017 update: The best way to do this (especially without containerless conditional binding) es from the knockout documentation for post-processing option bindings, using the optionsAfterRender binding. optionsAfterRender was added in version 2.3
Your code would look like this :
<select data-bind="value: selectedCountry , options : countryArray, optionsText: 'name', optionsAfterRender: setOptionsShow" ></select>
function viewModel() {
var self = this;
this.countryArray = ko.observableArray([{"name" : "France" ,"show" : true},
{"name" : "Italy" , "show" : true},
{"name":"Germany" , "show" : false}]);
this.selectedCountry = ko.observable("");
this.setOptionsShow = function(option, item) {
ko.applyBindingsToNode(option, {visible: item.show}, item);
}
}
$(document).ready(function() {
var vm = new viewModel();
ko.applyBindings(vm);
})
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745167945a4614748.html
评论列表(0条)