1

选择自动完成项后,我想在模板中填充多个输入。我正在关注http://jsfiddle.net/rniemeyer/MJQ6g/但不确定如何将其应用于多个输入。

模型:

<script>
        var ContactModel = function (contactsInfo) {
            var self = this;
            self.Company = ko.observable();
            self.ContactsInformation = contactsInfo;
            self.Name = ko.observable();
        };

        var ContactsInformationModel = function () {
            var self = this;
            self.Address1 = ko.observable();
        };

     var viewModel;

     var ViewModel = function () {
         var self = this;
         self.Contact1 = new ContactModel(new ContactsInformation);
         self.Contact2 = new ContactModel(new ContactsInformation);
     };

     $(function () {
         viewModel = new ViewModel();
         ko.applyBindings(viewModel);
     });

    function getContacts(searchTerm, sourceArray) {
        $.getJSON("web_service_uri" + searchTerm, function (data) {
            var mapped = $.map(data, function (item) {
                return {
                    label: item.Name,
                    value: item
                };
            });
            return sourceArray(mapped);
        });
    }
</script>

模板:

<script type="text/html" id="contact-template">                 
     <div>   
            Name
              <input data-bind="uniqueName: true,
                jqAuto: { autoFocus: true, html: true }, 
                jqAutoSource: $root.Contacts, 
                jqAutoQuery: getContacts, 
                jqAutoValue: Name, 
                jqAutoSourceLabel: 'label', 
                jqAutoSourceInputValue: 'value', 
                jqAutoSourceValue: 'label'"
                class="name" />    
     </div>
    <div>
        Company
        <input data-bind="value: Company, uniqueName: true" class="company" />
    </div>
    <div>
        Address
        <input data-bind="value: ContactsInformation.Address1, uniqueName: true" class="address1" />
    </div>        
</script>

html:

<div data-bind="template: { name: 'contact-template', data: Contact1 }">
        </div>
<hr/>
        <div data-bind="template: { name: 'contact-template', data: Contact2 }">
        </div>
4

1 回答 1

2

如果您从 中省略该jqAutoSourceValue选项data-bind,那么它会将值设置为等于实际对象。然后,您可以读取该对象的属性。

通常,您将有一个可观察对象:mySelectedPerson然后将一个部分(可能带有with绑定)绑定到它并访问该对象的各个属性/可观察对象。

这是修改为省略jqAutoSourceValue选项的示例,绑定jqAutoValue到调用的可观察对象mySelectedPerson并使用with绑定显示所选对象的一些属性。 http://jsfiddle.net/rniemeyer/YHvyL/

于 2012-06-03T16:31:28.860 回答