user3082385
user3082385

Reputation: 93

Using observableArray element in if condition

I am using the ko if statement in my html view, which refers to a knockout observableArray.

You can see my code on jsfiddle.

I am curious why this line of code is not working?

<!-- ko if: numbers()[1].value > 1 -->

If I print out the value, I am getting the value that I expected.

Upvotes: 0

Views: 686

Answers (3)

TSV
TSV

Reputation: 7641

You should use brackets after "value", because the "value" is an observable and you want to use its content:

<!-- ko if: numbers()[1].value() > 1 -->

Upvotes: 1

G_S
G_S

Reputation: 7110

It should be <!-- ko if: numbers()[1].value() > 1 --> since numbers()[1].value is an observable (every observable is a function).

In the above case when if: numbers()[1].value > 1 is considered, you are comparing a function with 1 (which is always false).

Upvotes: 3

Asim Shaikh
Asim Shaikh

Reputation: 169

Here's one way

<h4>Numbers</h4>
<button data-bind="click: add">Add</button>
 <input id="myid" data-bind="value: numbers()[1].value"></input>
 <!-- ko foreach: numbers -->    
<!-- ko if: $index() == 1-->
<div data-bind="text: value">
</div>
<!-- /ko -->
<!--/ko-->
<span data-bind="text: sum"></span>

Upvotes: 0

Related Questions