我目前正在使用knockout.js框架。我已经采用example形式的基本联系人,并根据自己的需要对其进行了修改。每位联系人的状态均为ACTIVE
或INACTIVE
。在状态下拉菜单中,我想显示联系人的选定状态。我得到一个通常的选择选项列表,而不是获得两个选项。如何在knockout.js中正确显示下拉菜单? DEMO
编辑@ haim770:
var ContactsModel = function (contacts) {
var self = this;
self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) {
return {
firstName: contact.firstName,
lastName: contact.lastName,
selectedOptionValue : contact.selectedOptionValue,
phone: contact.phone,
alt_phone: contact.alt_phone,
main1: ko.observable(contact.main1),
main2: ko.observable(contact.main2)
};
}));
self.statusList = ['ACTIVE', 'INACTIVE'];
self.addContact = function () {
self.contacts.push({
firstName: "",
lastName: "",
selectedOptionValue : ko.observable("ACTIVE"),
phone: "",
alt_phone: "",
main1: false,
main2: false
});
};
self.removeContact = function (contact) {
self.contacts.remove(contact);
};
self.addPhone = function (contact) {
contact.phones.push({
number: ""
});
};
self.removePhone = function (phone) {
$.each(self.contacts(), function () {
this.phones.remove(phone)
})
};
self.save = function () {
self.lastSavedJson(JSON.stringify(ko.toJS(self.contacts), null, 2));
};
self.lastSavedJson = ko.observable("");
};
$.getJSON("functions/getPerson.php", function(allData) {
ko.applyBindings(new ContactsModel(allData));
});
HTML
<li>
<select data-bind="options: $root.statusList, value: selectedOptionValue"></select>
</li>
JSON
[{"firstName":"James","lastName":"Southerland","phone":"1234567890","statusList":"ACTIVE","alt_phone":"1234567890","main1":true,"main2":false},{"firstName":"Tina","lastName":"Turner","phone":"1234567890","statusList":"INACTIVE","alt_phone":"1234567890","main1":false,"main2":true}]
答案 0 :(得分:1)
<强> 1 强>
从服务器返回的JSON格式不正确。不是在selectedOptionValue
中设置实际联系人状态(与在addContact
方法中一样),而是将其作为statusOptionValues
字段返回。
<强> 2 强>
无需在每个联系人中包含“活动/非活动”数组(statusOptionValues
)。试试这个:
self.statusList = ['ACTIVE', 'INACTIVE'];
然后适当地更改您的绑定声明:
<select data-bind="options: $root.statusList, value: selectedOptionValue"></select>
第3 强>
您最好依赖boolean
字段而不是string
数组:
contact.isActive = ko.observable(true);