击倒绑定选择与自定义对象的可观察属性
Knockout bind select with custom object with observable properties
我正试图将<select>
与Knockout绑定。在我的ViewModel中,我有2个不同的对象,每个对象都有可观察属性。
第一个对象是Property
,它的headquarter_id
是ko.observable()
。第二个对象是Headquarter
,它有一个id
和一个name
,都是ko.observable()
。
我要做的是绑定一个选择与ko.observableArray()
的Headquarter
对象,像这样:
<select id="headquarters" data-bind="options: HeadquarterOptions, optionsText: name, optionsValue: id, optionsCaption: '--Select--', value: Property().headquarter_id"></select>
但是我一直得到:
Uncaught ReferenceError: cannot to process binding "options: function (){return HeadquarterOptions}"
消息:id未定义
下面是我的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/
好了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>
name和id之间缺少单引号。
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/
相关文章:
- 未激发路由的控制器属性上的观察者
- 如何从具有动态可观察属性的淘汰对象中获取 JSON 字符串
- 使用挖空 JS 映射选项将可观察属性添加到映射的可观察数组
- Knockout.js - 如何在计算的可观察量中获取可观察属性的值
- 更改一个对象的可观察属性会更改集合中所有对象的属性
- PUT 期间不包括视图模式可观察属性
- 观察属性的角度指令
- 如何观察属性并在重新加载时清除它们
- 使用Jquery观察属性更改
- 一个JSON对象数组,用可观察属性击倒可观察对象数组
- 对数组中所有对象的可观察属性进行单个MobX自动运行或反应
- Knockoutjs:绑定到模板中数组之外的一个可观察属性
- 使用ko.computed和if语句来设置对象的可观察属性
- 在可观察数组中推入具有可观察属性的对象仍然跟踪对象的属性
- 如何在angularjs指令中观察属性
- 循环遍历具有可观察属性的JS对象
- 击倒绑定选择与自定义对象的可观察属性
- AngularJS:观察/观察属性的改变
- 如何创建具有可观察属性的对象
- 带有KnockoutJS可观察属性的JavaScript克隆对象