Salvador Dali
Salvador Dali

Reputation: 222461

knockout if with function inside a template

Continuing my study journey with knockout I encountered the following problem.

I try to output few galleries together with pictures inside of them. Nothing special and my model looks like this:

this.elements = ko.observableArray([{
    type: 'img',
    text: 'fish',
    imgs: ko.observableArray([
        'http://c1.wag.com/images/products/rdg/rdg-010_Small2a.jpg',
        'https://www.uoguelph.ca/cio/sites/uoguelph.ca.cio/files/images/SmallFish_0.jpg'
    ])
}, ...]);

But I want to have the following functionality. When there are not images in imgs, write about it.

So I tried it with <div data-bind="if: !imgs.length">No images</div> inside my template. But with no result (check my fiddle for the whole code). The output is written in every iteration.

But when I try to do the similar thing but explicitly showing the number of images, it works nicely.

So what is the problem with my imgs.length approach?

Upvotes: 0

Views: 64

Answers (2)

DevelopmentIsMyPassion
DevelopmentIsMyPassion

Reputation: 3591

You should use imgs().length. The imgs is observable array and its length can be accesses with use of (). See Fiddle here

Upvotes: 1

Ivan.Srb
Ivan.Srb

Reputation: 1851

You should use !imgs().length (with ()). imgs is observable array, so it is function and you should execute it before get length property of array.

Upvotes: 1

Related Questions