Knockout使用具有可观察属性的自定义对象绑定select

时间:2015-07-26 09:21:49

标签: javascript select knockout.js data-binding bind

我试图将<select>与Knockout绑定。在我的ViewModel中,我有两个不同的对象,每个对象都有可观察的属性。

第一个对象是Propertyheadquarter_idko.observable()。 第二个对象是Headquarter,其中idname都为ko.observable()

我要尝试做的是将select与ko.observableArray()Headquarter对象绑定,如下所示:

<select id="headquarters" data-bind="options: HeadquarterOptions, optionsText: name, optionsValue: id, optionsCaption: '--Select--', value: Property().headquarter_id"></select>

但我一直在接受:

Uncaught ReferenceError: Unable to process binding "options: function (){return HeadquarterOptions }"
Message: id is not defined

以下是我的ViewModel的样子:

var Property = function () {
    var self = this;
    self.headquarter_id = ko.observable();
}

var Headquarter = function (id, name) {
    var self = this;
    self.id = ko.observable(id);
    self.name = ko.observable(name);
}

var headquarterOptions = [
        new Headquarter(1, "hq 1"),
        new Headquarter(2, "hq 2"),
        new Headquarter(3, "hq 3"),
    ]

var PropertiesViewModel = function (app, dataModel) {
    var self = this;
    self.Property = ko.observable(new Property());
    self.HeadquarterOptions = ko.observableArray(headquarterOptions);
}

ko.applyBindings(PropertiesViewModel);

我怎样才能做到这一点? 这是我现在的小提琴:http://jsfiddle.net/juandozco/dzwnb05b/

2 个答案:

答案 0 :(得分:2)

optionsValueoptionsText应声明为函数而不是值(http://knockoutjs.com/documentation/options-binding.html):

optionsText: function(item) {return item.name; }
optionsValue: function(item){ return item.id; }

查看更新后的小提琴:http://jsfiddle.net/dzwnb05b/3/

答案 1 :(得分:2)

你去http://jsfiddle.net/dzwnb05b/4/

<select class="form-control" id="headquarter" data-bind="options: HeadquarterOptions, optionsText: 'name', optionsValue: 'id', optionsCaption: '--Select--', value: Property().headquarter_id"></select>

您在名称和ID周围缺少单引号。