[英]selectedValue in knockout is not binding
我今天要淘汰賽。 這是我的簡化VM:
function UserRecruitingViewModel(apiBaseUrl, userId) {
var self = this;
self.orgs = ko.observableArray();
//ddl org view switcher stuff
self.orgDdl = ko.observableArray();
self.selectedOrg = ko.observable();
var DropdownOrg = function (name, orgId) {
this.name = name;
this.orgId = orgId;
};
//...snip ajax get to pull data...//
}
注意,我在這里有這行:
self.selectedOrg = ko.observable();
在我的頁面上,我有以下下拉列表:
<select
data-bind="options: $root.orgDdl, optionsText: 'name', optionsValue: $root.selectedOrg">
</select>
為了便於閱讀,數據綁定值:
data-bind="
options: $root.orgDdl,
optionsText: 'name',
optionsValue: $root.selectedOrg"
這是行不通的。 如果我的select元素不帶 optionsValue綁定,它將使用我從GET請求獲得的值綁定列表。
我在控制台中收到一條錯誤消息:
Unable to process binding "text: function (){return selectedOrg() }"
Message: selectedOrg is not defined
我很困惑,因為我在VM上設置了selectedOrg可觀察的集合。
如果selectedOrg是要獲取選定選項的對象,則在我的示例中使用selectedSelected 。
視圖模型
var optionModel = function(id,name){
var self = this;
self.id = id;
self.name = name;
}
var viewModel = function(){
var self = this;
self.options = [
new optionModel(1,"First"),
new optionModel(2,"Second")
];
self.selectedOptionId = ko.observable(0);
self.selectedOption = ko.computed(function(){
return ko.utils.arrayFirst(self.options, function(item){
return item.id === self.selectedOptionId();
});
});
}
ko.applyBindings(new viewModel());
HTML綁定
<select data-bind="options: options,
optionsText: 'name',
optionsValue: 'id',
value: selectedOptionId,
optionsCaption:'Choose.....'">
</select>
上面的代碼是用於帶有剔除的簡單選項綁定。 對於此問題,模型定義不明確,您使用的optionsValue值尚不清楚。
這是示例jsfiddle供參考 (由於您的問題不清楚,該示例基於示例選項模型)
您只需要綁定中的純value
,而不是optionsValue
。 value
指定可觀察得到的選擇結果; 如果要將value
設置為對象的一個特定屬性,而不是對象本身,則使用optionsValue
。 假設您希望selectedOrg()
包含您選擇的整個DropdownOrg
對象,則不需要optionsValue
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.