敲除将键值对象绑定到下拉列表 [英] knockout bind a key value object to dropdown
问题描述
我有以下型号:
var allCategories = [{
id: 1,
name: 'Red'},
{
id: 5,
name: 'Blue'}];
function model() {
self = this;
self.name = ko.observable("");
self.categoryId = ko.observable(-1);
self.categoryName = ko.computed(function() {
if (self.categoryId() == -1) return "";
return getCategoryNameById(self.categoryId()).name;
});
}
function getCategoryNameById(id) {
return _.find(allCategories, function(cat) {
return cat.id == id;
});
}
我想提供一个下拉菜单来选择类别,但是我不知道如何绑定该类别. 也许我在模型中使用了错误的方法,但是这很可能是我从服务器获取数据的方式,因此我尝试将JS包装起来.
I want to offer a dropdown to select the category but I have no clue how to bind that. Maybe I've used the wrong approach with my models but that's most likely how I get my data from the server so I've tried to wrap my JS around that.
我尝试过这样的事情:
<select data-bind="options: categories, optionsText: 'name', value: 'id', optionsCaption: 'Categorie...'"></select>
但是我不知道如何将下拉值连接到模型categoryId
.
But I don't get how to connect the dropdown value to the model categoryId
.
这是小提琴,具有可绑定的name属性.
Here is a fiddle with a working binding for the name property.
推荐答案
对于您的列表框,您需要指定:options
,optionsText
,optionsValue
和value
.
value
(当前选择的值)应指向您的model.categoryId()
.并且optionsValue
是在其中获取列表值的属性名称:
For your list box you need to specify: options
, optionsText
, optionsValue
, and value
.
value
(which is the currently selected value) should point to your model.categoryId()
. And optionsValue
is the property name where to get values for the list:
<select data-bind="options: categories, optionsText: 'name', optionsValue: 'id', value: $root.model.categoryId(), optionsCaption: 'Categorie...'"></select>
就是这样.和有效的小提琴: http://jsfiddle.net/Y7Nrc/
And that's it. And the working fiddle: http://jsfiddle.net/Y7Nrc/
这篇关于敲除将键值对象绑定到下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!