我试图将<select>
与Knockout绑定。在我的ViewModel中,我有两个不同的对象,每个对象都有可观察的属性。
第一个对象是Property
,headquarter_id
为ko.observable()
。
第二个对象是Headquarter
,其中id
和name
都为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/
答案 0 :(得分:2)
optionsValue
和optionsText
应声明为函数而不是值(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周围缺少单引号。