如何使用Knockout从下拉列表中获取所选值

时间:2013-03-05 15:28:41

标签: knockout.js

这是View模型

 self.choiceSelect = ko.observable();
            self.selectedItems = ko.observableArray([]);
            self.selectedComponent = ko.observable();
            self.componentList = ko.observableArray();

 self.GetData = function () {

            $.ajax({
                url: self.url + "GetComponent",
                type: "GET",
                cache: false
            })
            .fail(function (qxhr, status, errorThrown) {

            })
            .done(function (data) {

                self.componentList(data);

            });

        };

这是代码:

<select id="report-Components" data-bind="value: selectedComponent, options: componentList, optionsText: 'componentName'"></select><br /><br />
<h4>Component Attributes</h4>
<!-- ko if: selectedComponent  -->
<!-- ko if: selectedComponent().componentField  -->
<div data-bind="foreach: selectedComponent().componentField">
    <div class="control-group">
        <div class="controls">
            <input type="checkbox" data-bind="checked: $parent.selectedItems, value: $data" />
        </div>
        <label class="control-label">
            <strong data-bind="text: fieldText"></strong>
        </label>
    </div>                                    
</div>
<!-- /ko -->                            
<!-- /ko -->
<!-- ko if: selectedItems  -->
<div data-bind="foreach: selectedItems">
    <!-- ko if: fieldChoice.length > 0  -->
    <label data-bind="text: fieldText"></label>
    <select data-bind="options: fieldChoice, optionsText: 'choiceName', value: $data.choiceSelect"></select>
    <!-- /ko -->
    <!-- ko if: fieldChoice.length == 0  -->
    <label data-bind="text: fieldText"></label>
    <input type="text" value=""/>
    <!-- /ko -->
</div>  
<!-- /ko -->  

1 个答案:

答案 0 :(得分:3)

您需要将select值绑定到observable:

<select data-bind="options: fieldChoice, optionsText: 'choiceName', value: $data.nameOfObservable">

当更改选择时,这应该更新nameOfObservable。

这个observable需要在你正在查看的数组中的每个项目上。因此,无论您存储在selectedItems中的对象是什么,它们都需要具有相同名称的可观察属性。

为了使视图模型中的所有内容都可观察,我建议使用mapping plugin

self.componentList = ko.mapping.fromJS(data);

对视图模型中的其他属性执行相同的操作。

相关问题