david.s
david.s

Reputation: 11403

Drop-down list not working in a Knockout KoGrid

I'm trying to display a drop-down list in a KoGrid cell using a custom cell template and I have no ideea why it's not working as it should.

I have an example of a working drop-down list using the options, optionsText, optionsValue and optionsCaption and the bindings work as it should. But a similar drop-down in a KoGrid does not display any elements. My question is what am I missing/doing wrong and how can I fix this problem?

Link to 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());

Upvotes: 3

Views: 1238

Answers (1)

nemesv
nemesv

Reputation: 139798

When you are inside a celltemplate you need to use the $userViewModel to access your "$root" viewmodel.

From the documentation:

$userViewModel: {{ko binding context}}// accessor to your viewmodel that you used to instantiate the grid.

So you need to write:

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

Demo JSFiddle.

Upvotes: 3

Related Questions