我创建了一个简单的模板,用于设置" selectedItem"点击时。我还添加了一个简单的文本框,它绑定到" selectedItem"方法,但点击模板列表时我无法更新。
HTML
<div data-bind="template: { name: 'address-template', foreach: addresses }"></div>
<input type="text" id="textBoxAddressLine1" name="textBoxAddressLine1Name" data-bind="value: selectedItem ? selectedItem.AddressLine1 : ''" />
<script type="text/html" id="address-template">
<a href="#" data-bind="click: function() { viewModel.selectItem($data); }">
<h4 >Suggested Address</h4>
<p>
<dl>
<dt>Address line 1:</dt>
<dd data-bind="text: AddressLine1"></dd>
<dt>Address line 2:</dt>
<dd data-bind="text: AddressLine2"></dd>
</dl>
</p>
</a>
</script>
JS
viewModel = {
addresses: ko.observableArray(),
selectedItem: ko.observable(),
selectItem: function (data) {
this.selectedItem = data;
}
};
viewModel.addresses = [{"AddressSuggestionId":"895528b3-b5a3-4dc8-966c-094ef74d88d2","AddressLine1":"111 Test street","AddressLine2":"Test address line 2"},{"AddressSuggestionId":"d149b694-6450-4d86-a441-1f41cee732dd","AddressLine1":"222 test street","AddressLine2":"test addresline2"}]
ko.applyBindings(viewModel);
查看测试代码:http://jsfiddle.net/patremb/7meN8/6/
感谢您的帮助!
帕特里克
答案 0 :(得分:0)
由于selectedItem
是一个可观察的,你需要调用它来访问/更改它的数据。
试试这个:
<input type="text" id="textBoxAddressLine1" name="textBoxAddressLine1Name"
data-bind="value: selectedItem() ? selectedItem().AddressLine1 : ''" />
在你的ViewModel中:
selectItem: function(data) {
this.selectedItem(data);
}