具有所选对象的父对象的单选按钮设置属性

时间:2016-03-08 17:29:51

标签: knockout.js

使用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”属性?

1 个答案:

答案 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,它就会绑定整个对象