使用Javascript:
functional OrderViewModel() {
this.selectedVehicle = ko.observable();
this.vehicles = ko.observableArray([
new VehicleViewModel('Toyota'),
new VehicleViewModel('Ford'),
new VehicleViewModel('Chevy')
]);
}
function VehicleViewModel(name) {
this.name = name;
}
ko.applyBindings(new OrderViewModel());
HTML
<div>
<!--ko foreach: $data.vehicles -->
<label>
<input type="radio" data-bind="value: $data.name, checked: $parent.selectedVehicle" />
<span data-bind="text: $data.name"></span>
</label>
<!-- /ko -->
</div>
如何使用选定的VehicleViewModel(而不仅仅是名称)更新OrderViewModel的“selectedVehicle”属性?
答案 0 :(得分:2)
你基本上拥有它。看这个 https://jsfiddle.net/16hozLzL/
<div>
<!--ko foreach: $data.vehicles -->
<label>
<input type="radio" data-bind="value: $data, checked: $parent.selectedVehicle" />
<span data-bind="text: $data.name"></span>
</label>
<!-- /ko -->
</div>
只需从values绑定中删除.name,它就会绑定整个对象