template: foreach -- what if the data set is empty

5,642 views
Skip to first unread message

FraserOrr

unread,
Oct 22, 2011, 6:50:00 PM10/22/11
to KnockoutJS
I need to render a table from an array, however, if the array is empty
I need to put in a message like "There are no records". I don't see an
obvious way to do this with template: foreach, and I'm thinking I have
to artifically hack something in in javascript in a non declarative
way. Am I missing something?

sini...@gmail.com

unread,
Oct 22, 2011, 8:05:41 PM10/22/11
to knock...@googlegroups.com
put some element before foreach, bind it to "visible" for example "isempty"..
<span data-bind="visible: isempty"></span>

in your view,
 isempty:ko.observable(false),

when you load your array ( i suppose you are loading it from somewhere),
if (array.length==0){isempty(true)}else{push items to array}

Thats one way to do it, Im sure Ryan and others have alot more :)




sini...@gmail.com

unread,
Oct 22, 2011, 8:06:20 PM10/22/11
to knock...@googlegroups.com
i forgot :)

<span data-bind="visible: isempty">ITS EMPTY</span>

:)

Mark Bradley

unread,
Oct 22, 2011, 8:25:48 PM10/22/11
to knock...@googlegroups.com
Or you could have an expression that just references the array
directly in the binding (no separate boolean variable).

<span data-bind="visible: array().length == 0">observableArray is empty</span>

--
-barkmadley
sent from an internet enabled device
http://barkmadley.com

FraserOrr

unread,
Oct 22, 2011, 9:22:48 PM10/22/11
to KnockoutJS
Perfect, thanks.

FraserOrr

unread,
Oct 22, 2011, 9:23:02 PM10/22/11
to KnockoutJS
Both answers are perfect, thanks.

On Oct 22, 7:25 pm, Mark Bradley <barkmad...@gmail.com> wrote:
> Or you could have an expression that just references the array
> directly in the binding (no separate boolean variable).
>
> <span data-bind="visible: array().length == 0">observableArray is empty</span>
>

Leandro de los Santos

unread,
Oct 23, 2011, 11:27:12 AM10/23/11
to KnockoutJS
I solve this problem in this way.

IsEmpty as a dependent observable and for html, instead using visible
binding i use 1.3 feature for templates "if"


viewModel.emptyArray= ko.dependentObservable(function () {
return this.ArrayWithItems().length==0;
}, viewModel);

<ul>
<!-- ko foreach: ArrayWithItems -->
<li> items for array... </li>
<!-- /ko -->
<li data-bind="if: emptyArray">
¡¡¡No records message!!!
</li>
<ul>

It's not the same like Visible, becouse in this way i have the "<li>"
for emtpy rows only when the list is empty.
> > sent from an internet enabled devicehttp://barkmadley.com- Hide quoted text -
>
> - Show quoted text -

gere...@gmail.com

unread,
Mar 5, 2013, 11:47:02 AM3/5/13
to knock...@googlegroups.com
<span data-bind="visible: array().length == 0">observableArray is empty</span> of Mark.
works for me.

thanks.

G.
Reply all
Reply to author
Forward
0 new messages