Reputation: 5721
I want to be able to have a table show only if there are items in an array. I have simplified down my needs to this jsfiddle example.
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>
Basically I have a web app where lines can be removed from table. If array.length == 0
, I want to hide the entire table.
Upvotes: 29
Views: 35102
Reputation: 4959
if you want to show message or image like 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 when table lines datas appeared successfully
<div data-bind="visible: !lines().length">
You will see this message only when "lines" holds a false value.
<img src=""/>
</div>
Upvotes: 0
Reputation: 1124
It is considered bad practice to add logic 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>
Upvotes: 0
Reputation: 772
Another solution, slight variation on your 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>
Upvotes: 8
Reputation: 22338
You can do this in several ways. The fiddle below uses the containerless bindings to hide the entire table if the lines array 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 -->
Upvotes: 47