admin管理员组文章数量:1415101
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);
})
本文标签: javascriptKnockout js conditional options bindingStack Overflow
版权声明:本文标题:javascript - Knockout js conditional options binding - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745167945a2645797.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论