0

我创建了一个简单的模板,在单击时设置“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/

谢谢您的帮助!

帕特里克

4

1 回答 1

0

由于selectedItem是可观察的,因此您需要调用它来访问/更改它的数据。

尝试这个:

<input type="text" id="textBoxAddressLine1" name="textBoxAddressLine1Name"
       data-bind="value: selectedItem() ? selectedItem().AddressLine1 : ''" />

在您的 ViewModel 中:

selectItem: function(data) {
            this.selectedItem(data);
            }
于 2014-05-27T17:51:09.590 回答