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.
Note: Using “if” and “ifnot” without a container element-- ko --> and <! -- /ko --> comments act as start/end markers, defining a “virtual element” that contains the markup inside. Knockout understands this virtual element syntax and binds as if you had a real container element.
To clear an observableArray you can set the value equal to an empty array.
To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.
You just need to declare ViewModel property with function ko. observable() to make it Observable.
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 -->
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With