我是JS和Knockout的新手。我想将observableArray中的特定observable复制到另一个observableArray。我怎么能这样做?
HTML
<table>
<thead>
<tr>
<th>Passenger Name</th>
<th>Meal</th>
<th>Amount ($)</th>
<th></th>
</tr>
</thead>
@*render a copy of seats child elements for each entry in the seats array*@
<tbody data-bind="foreach: seats">
<tr>
<td data-bind="text: name"></td>
@*update the view to make use of the formatted Price*@
<td>
<select data-bind="options: $root.availableMeals,
value: meal, optionsText: 'mealName'">
</select>
</td>
<td data-bind="text: formattedPrice"></td>
<td><a href="#" data-bind="click: $root.removeSeat">Remove</a></td>
</tr>
</tbody>
</table>
要求
答案 0 :(得分:1)
我已经创建了一个 JS fiddle ,它显示了如何使用以下代码在可观察数组之间移动项目:
<强> HTML 强>
<p>first list:</p>
<table>
<tbody data-bind="foreach: contents">
<td> <strong>
<span id="textKey" data-bind="text: displayKey" />
</strong>
</td>
<td>
<input id="textValue" type="text" data-bind="value: displayValue" />
</td>
<td>
<input type="button" data-bind="click: $root.copyItem" value="select" />
</td>
</tbody>
</table>
<p>Second list:</p>
<table>
<tbody data-bind="foreach: selectedContents">
<td> <strong>
<span id="textKey" data-bind="text: displayKey" />
</strong>
</td>
<td>
<input id="textValue" type="text" data-bind="value: displayValue" />
</td>
</tbody>
</table>
查看型号:
function ViewModel() {
var self = this;
self.contents = ko.observableArray([{
"displayKey": "Fruit",
"displayValue": "Bananas"
}, {
"displayKey": "Colour",
"displayValue": "Red"
}, {
"displayKey": "Car",
"displayValue": "Ferrari"
}]);
self.selectedContents = ko.observableArray([]);
self.copyItem = function(item) {
self.selectedContents.removeAll();
self.selectedContents.push(item);
}
}
ko.applyBindings(new ViewModel());