KnockoutJS选择选项和选定值 [英] KnockoutJS Select Options and Selected Value

查看:90
本文介绍了KnockoutJS选择选项和选定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似的问题:选择元素的初始值

我在设置select元素的初始值时遇到问题.我基本上有一个来自服务器的种子数据列表,用于填充下拉列表,并且我希望所选的值表示应该从实体中选择的内容.

I'm having an issue setting the initial value of the select element. I basically have a list of seed data coming in from the server to populate the drop down list, and I want the selected value to represent what should be selected from the entity.

由于数据模型的选择值不等于种子数据中的对象引用,因此什么也没有选择.

Because the data model's selected value doesn't equal the object reference in the seed data, nothing is selected.

现在,我遍历每个实体,找到正确的选定值,将其设置为等于种子数据的等效值,然后敲除知道如何进行连接.

Right now, I'm looping through each entity, finding the correct selected value, setting that equal to the seed data's equivalent, then Knockout knows how to wire it up.

有没有更优雅的解决方案呢?我摆弄了一个简化的示例,提供了更多详细信息... http://jsfiddle.net/hbrYM/14/

Is there a more elegant solution that this? I fiddled a simplified example with more details... http://jsfiddle.net/hbrYM/14/

推荐答案

当您正确地猜到selectedValue引用不匹配时,KO就不会选择该项目.使此方法起作用的方法是,不将复杂对象保存为所选值,而是选择ID,因为基本类型相等可以成功并且选择了正确的值.

As you correctly guessed the selectedValue reference doesn't match so KO doesn't select that item. The way to get this to work is to not save the complex object in the selected value and instead select the ID, as a primitive type equality can succeed and the correct value is selected.

http://jsfiddle.net/VLTFB/3/

您需要在选项绑定上使用optionsValue选项(如果有意义的话:)

You'll need to use the optionsValue option on the options binding (if that makes sense :)

<select data-bind="options: seedData,
                    optionsText: 'firstName',
                    optionsValue: 'ID',
                    value: data.selectedValue">

编辑

如前所述,您可以重新选择带有计算(未测试)的正确项目.

As discussed you can reselect the correct item with a computed (untested).

vm.currentlySelected = ko.computed(function () { 
   for (var i = 0; i < this.seedData().length; i += 1) {
       var data = this.seedData()[i];
       if (data.ID === this.selectedValue()) {
           return data;
       }
   }
   return null;
}, vm);

希望这会有所帮助.

这篇关于KnockoutJS选择选项和选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆