【问题标题】:Drop-down list not working in a Knockout KoGrid下拉列表在 Knockout KoGrid 中不起作用
【发布时间】:2013-04-09 17:22:56
【问题描述】:

我正在尝试使用自定义单元格模板在 KoGrid 单元格中显示下拉列表,但我不知道为什么它不能正常工作。

我有一个使用options, optionsText, optionsValue and optionsCaption 的下拉列表示例,并且绑定可以正常工作。但是 KoGrid 中的类似下拉菜单不显示任何元素。我的问题是我错过了什么/做错了什么,我该如何解决这个问题?

jsFiddle 链接:http://jsfiddle.net/AxyWz/6/

HTML:

<p>
    Working drop-down list:
    <select data-bind="options: data, optionsText: 'name', optionsValue: 'id', optionsCaption: '-', value: selectedItemId"></select>
</p>

<p>
    Drop-down list not working in KoGrid:
    <div class="grid" data-bind="koGrid: gridOptions"></div>
</p>

<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>

<script type="text/html" id="template">
    <select data-bind="options: $root.data, optionsText: 'name', optionsValue: 'id', optionsCaption: '-', value: $parent.entity[$data.field]"></select>
</script>

Javascript:

function Item(id, name) {
    this.id = ko.observable(id);
    this.name = ko.observable(name);
    this.parentId = ko.observable();
}

function ViewModel() {
    this.selectedItemId = ko.observable();

    this.data = ko.observableArray([
        new Item(1, 'aaa'),
        new Item(2, 'sss'),
        new Item(10, 'xxx'),
        new Item(14, 'zzz')
    ]);

    this.gridOptions = {
        data: this.data,
        canSelectRows: false,
        columnDefs: [
            { field: 'id', displayName: 'id' },
            { field: 'name', displayName: 'name' },
            { 
                field: 'parentId', displayName: 'parent',
                cellTemplate: $.trim($('#template').html())
            },
        ]
    };
}

ko.applyBindings(new ViewModel());

【问题讨论】:

    标签: javascript knockout.js kogrid


    【解决方案1】:

    当您在单元格模板中时,您需要使用$userViewModel 来访问您的“$root”视图模型。

    来自documentation

    $userViewModel: {{ko binding context}}// 用于实例化网格的视图模型的访问器。

    所以你需要写:

    <script type="text/html" id="template">
        <select data-bind="options: $userViewModel.data, 
                           optionsText: 'name', optionsValue: 'id', 
                           optionsCaption: '-', value: $parent.entity[$data.field]">
        </select>
    </script>
    

    演示JSFiddle.

    【讨论】:

      猜你喜欢
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      • 2013-12-06
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多