如何使用单选按钮实现这一点而不使用ko.bindingHandlers

时间:2013-12-24 20:01:37

标签: knockout.js radio-button

视图

<select data-bind="options: choices, value: selectedChoice"></select>
<div data-bind="text: ko.toJSON($root)"></div>

视图模型

var viewModel = {
    choices: ["Nie", "Täglich", "Wöchentlich"],
    selectedChoice: ko.observable("Täglich")
};

viewModel.selectedChoice.subscribe(function(newValue) {
   alert("the new value is " + newValue); 
});


ko.applyBindings(viewModel);

演示:http://jsfiddle.net/kougiland/vZC8A/1/

2 个答案:

答案 0 :(得分:1)

http://jsfiddle.net/vZC8A/2/

我想你想要上面这样的东西。 checked绑定并使用virtual elements

<!-- ko foreach: choices -->
<input type="radio" name="group1" data-bind="checked: $root.selectedChoice, value: $data" /> <span data-bind="text: $data"></span>
<!-- /ko -->

答案 1 :(得分:1)

你去http://jsfiddle.net/vZC8A/3/,希望它有所帮助,根据需要进行定制

<div data-bind="foreach: choices">
<div>
    <input type="radio" name="choices"
           data-bind="value: $data, checked: $parent.selectedChoice" />
    <span data-bind="text: $data"></span>
</div>