Knockout JS 设置可观察数组下拉列表的初始值 object 属性 值

Knockout JS Setting Initial value for dropdown from observable array object property value

我正在创建一个会议出席管理器,信息正在保存到我们的数据库中。我的登录表单上有一个名为 "Attendee Type" 的下拉 select 列表,其中包含从名为 attendeeTypes 的可观察数组中填充的值。与会者类型在表格中填写 objects
{Id:1, 姓名: "Parent"}
{Id:2, 姓名: "Staff"}等

现在,我的 table 中的行也是由 运行 对可观察数组 meetingAttendees 的 foreach 动态创建的。

与会者
self.meetingAttendees = ko.observableArray([{ AttendeeTypeId: ko.observable(1),<br> AttendeeNames: ko.observableArray([{ Name: "Marlin" }, { Name: "Dory" }]),<br> AttendeeSiteNumber: ko.observable(40), <br>StudentNames: ko.observableArray([{ Name: "P. Sherman" }, { Name: "42 Wallaby Way" }, { Name: "Sydney" }]), <br>Email: ko.observable("test@test.com"), <br>Telephone: ko.observable("559-222-5555") }

如您所见,table 中的每一行都有一个 attendeeTypeId。如果这个值是 pre-populated,就像这里一样,我希望下拉列表切换到适当的值。这将有助于在发生刷新时保留数据。

我的Html:
<table class="table table-responsive table-condensed table-bordered table-striped"> <thead> <tr> <th class="attendeeTypeCol">Attendee Type</th> <th class="attendeeNameCol">Attendee Name(s)</th> <th class="schoolNameCol">School Name</th> <th class="studentNameCol">Student Name</th> <th class="emailCol">E-Mail Address</th> <th class="telephoneCol">Telephone Number</th> </tr> </thead> <tbody data-bind="foreach: $root.meetingAttendees"> <tr> <td class="attendeeTypeCol"> <select style="margin-right: 15px;" data-bind="options: $root.attendeeTypes, optionsText: 'Name',value: $root.meetingAttendees()[$index()].AttendeeTypeId,optionsValue: 'Id', optionsCaption: 'I am a(n)...'"> </select> <span data-bind="text:$index()"></span> <span data-bind="text:$root.meetingAttendees()[$index()].AttendeeTypeId()"></span> </td> ... </tr> </tbody> </table>

我有两个调试跨度,所以我总能看到 $root.meetingAttendees()[$index()].AttendeeTypeId() 的值。当我 select 下拉列表中的值时,该值会相应地更新和更改,因此我确信它在正确的位置查找,但在初始加载时,值绑定未将下拉列表设置为适当的选项。它实际上是将变量设置为默认值 'undefined'.

有没有人想过如何让下拉菜单从 $root.meetingAttendees()[$index()].AttendeeTypeId() 中的 Id 中设置为适当的值?

这个问题的答案就是评论里说的。

感谢 Quango 进行验证。

对于敲除绑定 select 列表,必须在应用绑定之前填充该列表。

我的 AJAX 调用在绑定之前尚未完成,因此我的列表绑定 observable 被设置为默认值 "undefined"。

通过将我的绑定包装在一个函数中,并在使用 $.ajax({}).done(--call function--) 完成 AJAX 调用后调用该函数,这保证在应用绑定之前将填充列表。

正如 Quango 所说,如果列表是静态的,最好在 HTML 中注入选项,但这对于动态加载的列表很有用。

"Yes, be careful with binding order when binding lists and the bound values - I've tripped over it as well. The list must be filled before the value is bound. If not, and the list is empty, then the value gets set to undefined. There are many different ways to address this - it depends on whether the list is static or dynamic. For static lists you can inject the values into HTML if this is possible. If a dynamic list, one approach is to pass the values in the same AJAX call as the model data, so the viewmodel has both lists and data at the same time." – Quango