Knockout:如何从observableArray对象中按属性名称选择项目

时间:2016-06-17 19:39:52

标签: javascript html knockout.js

我通过开发一个打印有关所选人信息的小应用程序来完成敲门的第一步,问题是我根本不知道如何根据特定属性从数组中选择对象

在我的小提琴中,我需要打印有关我选择的人的所有信息,但是人名不会出现在选择框中,它会显示[Object Object]

我想要的结果是什么?



var people = [{
    name: "Contact 1",
    address: "1, a street, a town, a city, AB12 3CD",
    tel: "0123456789",
    email: "anemail@me.com",
    type: "family"
}, {
    name: "Contact 2",
    address: "1, a street, a town, a city, AB12 3CD",
    tel: "0123456789",
    email: "anemail@me.com",
    type: "friend"
}, {
    name: "Contact 3",
    address: "1, a street, a town, a city, AB12 3CD",
    tel: "0123456789",
    email: "anemail@me.com",
    type: "friend"
}];

function ContactsViewModel(people) {
    var self = this;
    self.contacts = ko.observableArray(people);
}

ko.applyBindings(new ContactsViewModel(people));

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div>
    Show me:
    <select data-bind="options: contacts"></select>
</div>
<div>
    Name: <span databind="text: name"></span><br>
    Adress: <span data-bind="text: address"></span><br>
    Tel: <span data-bind="text: tel"></span><br>
    Email: <span data-bind="text: email"></span><br>
    Type: <span data-bind="text: type"></span><br>
</div>
&#13;
&#13;
&#13;

我的小提琴:http://jsfiddle.net/VxT5Y/146/

2 个答案:

答案 0 :(得分:2)

使用select optionsText data-bind property:

 <select data-bind="options: contacts,
                   optionsText: 'name',
                   value: selectedName,
                   optionsCaption: 'Choose...'"></select>

答案 1 :(得分:2)

您需要一个observable来获取值并使用它来显示在表单中。

<强> [编辑]

正如@Tomalak所建议的

&#13;
&#13;
var people = [{
        name: "Contact 1",
        address: "1, a street, a town, a city, AB12 3CD",
        tel: "0123456789",
        email: "anemail@me.com",
        type: "family"
    }, {
        name: "Contact 2",
        address: "1, a street, a town, a city, AB12 3CD",
        tel: "0123456789",
        email: "anemail@me.com",
        type: "friend"
    }, {
        name: "Contact 3",
        address: "1, a street, a town, a city, AB12 3CD",
        tel: "0123456789",
        email: "anemail@me.com",
        type: "friend"
    }];


    function ContactsViewModel(people) {

        var self = this;
        self.contacts = ko.observableArray(people);
        self.selectedPerson = ko.observable();
    }

    ko.applyBindings(new ContactsViewModel(people));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>

<p>Show me:
  <select data-bind="options: contacts, optionsText: 'name', value:selectedPerson"></select>
</p>
<!-- ko with: selectedPerson -->
Name:
<p data-bind="text:name"></p>
adress:
<p data-bind="text:address"></p>
tel:
<p data-bind="text:tel"></p>
email:
<p data-bind="text:email"></p>
type:
<p data-bind="text:type"></p>
 <!--/ko -->
&#13;
&#13;
&#13;