1

视图模型:

function Specialization(id, name) {
            var self = this;
            self.id = id;
            self.name = name;
        }

        function ObservableSpecialization() {
            var self = this;
            self.availableItem = ko.observable();
        }

        function ViewModel() {
            var self = this;
            self.specializations = ko.observableArray([]);
            self.availableSpecializations = [];

            self.addSpecialization = function () {
                self.specializations.push(new Specialization());
            }
            self.removeSpecialization = function (specialization) {
                self.specializations.remove(specialization)
            }
        }

文件加载:

$(document).ready(function () {
            var model = new ViewModel();

            var temp = [];
            $.each(window.availableSpecializations, function (i, item) {
                var specialization = new Specialization(item.ID, item.Name);
                model.availableSpecializations.push(specialization);
                temp.push(item.ID);
            });
            $.each(window.userSpecializations, function (i, item) {

                var idx = temp.indexOf(item.ID);
                if (idx != -1) {
                    var available = model.availableSpecializations[idx];
                    var specialization = new ObservableSpecialization();
                    specialization.availableItem = available;
                    model.specializations.push(specialization);
                }
            });

            ko.applyBindings(model);
        });

<select>片段:

<tbody data-bind="foreach: specializations">
                        <tr>
                            <td>
                                <select name="Specializations" data-bind="options: $root.availableSpecializations, value: 'availableItem', optionsText: 'name'">
                                </select>
                            </td>

结果:

正如您在下面看到的,所有值始终设置为列表中的第一项。我猜 ID 没有以某种方式绑定到选定的项目...我哪里出错了?

在此处输入图像描述

4

1 回答 1

2

有两个问题:首先,specialization.availableItem是一个可观察的,因此应该分配一个函数调用:specialization.availableItem(available)

其次,在绑定字符串中,您value: 'availableItem'只需将选择值设置为字符串“availableItem”。应该没有引号:value: availableItem

这是两个修复的小提琴:jsfiddle

于 2012-06-30T03:40:29.963 回答