How to display No Data when observable array is em

2019-02-21 18:57发布

问题:

I'm new to Knockout.js and I'm trying to display data from observable array to a table. The problem I have is it generates two tbody tags. But if I move the empty check logic into the foreach: loop, the No Data does showup at all.

Is there a better way to do this using table? I don't like to use ul or ol in this case.

<table>
    <thead>
        <tr>
            <th>Permit</th>
            <th>Region</th>
            <th>Landowner</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: requestList">
        <tr>
            <td><span data-bind="text: permit"></span></td>
            <td><span data-bind="text: region"></span></td>
            <td><span data-bind="text: landowner"></span></td>
        </tr>
    </tbody>
    <tbody data-bind="if: requestList().length === 0">
        <tr>
            <td colspan="3">No Data</td>
        </tr>
    </tbody>
</table>

回答1:

When doing this we make a lot of use of virtual elements. They are outlined here http://knockoutjs.com/documentation/if-binding.html#note_using_if_without_a_container_element

The rest of your markup is fine, but you could wrap your first tbody in a virtual element like this:

<!-- ko if: requestList().length -->
    <tbody data-bind="foreach: requestList">
        <tr>
            <td><span data-bind="text: permit"></span></td>
            <td><span data-bind="text: region"></span></td>
            <td><span data-bind="text: landowner"></span></td>
            <td><button data-bind="click: $parent.remove">Remove</button></td>
        </tr>
    </tbody>
<!-- /ko -->

JSFiddle here: http://jsfiddle.net/ZKWMh/



回答2:

Actually, your html markup is fine. I added the following javascript to your markup

$(document).ready(function() {
    var a = [{
        permit: "permit1",
        region: 'region1',
        landowner: 'landowner'},
    {
        permit: "permit2",
        region: 'region2',
        landowner: 'landowner2'}];
    var vm = {};
    vm.requestList = ko.observableArray([]);

    ko.applyBindings(vm);

    $('#loadData').click(function() {
        var a1 = ko.mapping.fromJS(a);
        var b1 = a1();
        vm.requestList(b1);
    });
});​

And it seems to be working as you describe how you want things to work. It is working at http://jsfiddle.net/photo_tom/xmk3P/10/