我想使用knockout通过下拉列表中的选定值动态更新输入元素,但我不明白如何使用我在此处评论的代码与下拉列表相比,我不确定如果这是正确的方法...请帮助我理解并解决这个问题。
查看:
<div class="form-group">
<label for="dropDownRelationType">Business relation type</label>
<div class="input-group">
<input type="text" class="form-control" id="txtRelationTypeId" name="txtRelationTypeId" data-bind="value: companyModel.relationTypeId" placeholder="Business relation type"
<div class="input-group-btn">
<button type="button" id="dropDownRelationType" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" data-bind="foreach: relationTypes">
<li><a role="menuitem" href="#" data-bind="text: relationTypeId"></a></li>
</ul>
</div>
</div>
</div>
淘汰赛:
function companyModel() {
var self = this;
self.companyName = ko.observable("");
self.status = ko.observable("1");
self.relationTypeId = ko.observable("");
self.relationTypes = ko.observableArray();
}
function CompanyViewModel() {
var self = this;
self.companyModel = new companyModel();
self.relationTypes = ko.observableArray([
{ relationTypeId: "1" }, { relationTypeId: "2" }, { relationTypeId: "3" }, { relationTypeId: "4" }
])
//-------------------------------------------------------
//self.relationTypes.subscribe(function (selectedRelationTypeId) {
// shouter.notifySubscribers(selectedRelationTypeId, "valueToPublish");
//});
//shouter.subscribe(function (selectedRelationTypeId) {
// self.relationTypeId(selectedRelationTypeId);
//}, self, "valueToPublish");
//-------------------------------------------------------
}
var companyViewModel = new CompanyViewModel();
$(function () {
ko.applyBindings(companyViewModel);
});
答案 0 :(得分:1)
您可以添加一个observable来选择relationTypeId,如
function CompanyViewModel() {
var self = this;
self.companyModel = new companyModel();
self.selectedRelationTypeId = ko.observable();
self.relationTypes = ko.observableArray([
{ relationTypeId: "1" }, { relationTypeId: "2" }, { relationTypeId: "3" }, { relationTypeId: "4" }
])
self.selectRelationTypeId = function(relationType){
self.selectedRelationTypeId(relationType.relationTypeId);
};
}
并将您的html标记更改为
<div class="form-group">
<label for="dropDownRelationType">Business relation type</label>
<div class="input-group">
<input type="text" class="form-control" id="txtRelationTypeId" name="txtRelationTypeId" data-bind="value: selectedRelationTypeId" placeholder="Business relation type" />
<div class="input-group-btn">
<button type="button" id="dropDownRelationType" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" data-bind="foreach: relationTypes">
<li><a role="menuitem" href="#" data-bind="text: relationTypeId, click: $root.selectRelationTypeId"></a></li>
</ul>
</div>
</div>
</div>
您应该能够在输入字段中看到您所做的选择。