我有以下型号:
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 来解决这个问题。
我尝试过这样的事情:
<select data-bind="options: categories, optionsText: 'name', value: 'id', optionsCaption: 'Categorie...'"></select>
但我不知道如何将下拉值连接到模型categoryId
.
Here is a fiddle http://jsfiddle.net/kannix/S5Jbt/5/具有 name 属性的工作绑定。
对于您的列表框,您需要指定:options
, optionsText
, optionsValue
, and value
.
value
(这是当前选择的值)应该指向您的model.categoryId()
. And optionsValue
是属性名称,从中获取列表的值:
<select data-bind="options: categories, optionsText: 'name', optionsValue: 'id', value: $root.model.categoryId(), optionsCaption: 'Categorie...'"></select>
就是这样。和工作小提琴:http://jsfiddle.net/Y7Nrc/ http://jsfiddle.net/Y7Nrc/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)