[ACCEPTED]-knockout.js change visible status based on if array is empty or not-knockout.js

Accepted answer
Score: 46

You can do this in several ways. The fiddle 3 below uses the containerless bindings to 2 hide the entire table if the lines array 1 has no entries.

http://jsfiddle.net/johnpapa/WLapt/4/

<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 -->​
Score: 8

Another solution, slight variation on your 1 original attempt:

<div data-bind="visible:lines().length">
    <span>Lines Exist</span> 
    <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>
</div>
Score: 0

It is considered bad practice to add logic 1 to the html template. I suggest this solution:

<div data-bind="with: lines">     
    <span data-bind="if: length">Lines Exist</span>
    <ul data-bind='foreach:$data'>
        <li>
            <button data-bind="click:$parent.remove">
                Remove
            </button>
            <span data-bind="text:content"></span>
        </li>
    </ul>
</div>
Score: 0

if you want to show message or image like 3 this jsfiddle example

<div data-bind="visible:lines().length">
    You will see this message only when "lines" holds a true value.
    <img src=""/>
</div>

if you want to hide message 2 when table lines datas appeared successfully 1

<div data-bind="visible: !lines().length">
    You will see this message only when "lines" holds a false value.
    <img src=""/>
</div>

More Related questions