Change visible status based on if array is empty or not in knockout.js

I want to be able to have a table show only if there are items in an array.

JS

var view_model = {
    lines: ko.observableArray([
        {
        content: 'one'},
    {
        content: 'two'},
    {
        content: 'three'},
    {
        content: 'four'},
        ]),
    remove: function(data) {
        view_model.lines.remove(data);
    }
};

ko.applyBindings(view_model);

HTML

<span data-bind="visible:lines">Lines Exist</span> 
<ul data-bind='foreach:lines'>
    <li>
        <button data-bind="click:$parent.remove">
            Remove
        </button>
        <span data-bind="text:content"></span>
    </li>
</ul>

Here is one solution;

<span data-bind="visible:lines">Lines Exist</span> 
<!-- ko if: lines().length > 0-->
<p>Here is my table</p>
<ul data-bind='foreach:lines'>
    <li>
        <button data-bind="click:$parent.remove">
            Remove
        </button>
        <span data-bind="text:content"></span>
    </li>
</ul>
<!-- /ko -->​

Refer to Stackoverflow

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect