knockoutjs模板jquery自动完成 - 如何在自动完成选择中填充输入?

时间:2012-06-01 23:17:25

标签: jquery-ui knockout.js

我想在选择自动完成项后填充模板中的多个输入。我正在关注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>

1 个答案:

答案 0 :(得分:2)

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

通常,你会有一个像mySelectedPerson这样的observable,然后绑定一个部分(可能带有with绑定),然后从该对象访问各个属性/ observable。

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