Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout string comparison in if data-binding

Tags:

knockout.js

The category variable is defined as ko.observable() and child value should be changed according to category value.
Below if statement always returns false.

<!-- ko if: $parent.category == "Electronics"-->
   <div>abc</div>
<!--/ko-->

the if satement below also always returns false:

<span data-bind="if: $parent.category == 'Electronics'">
   <div>abc</div>
</span>

How to do comparison in data-binding with hard-code values?

like image 411
Irfan Yusanif Avatar asked Aug 27 '15 18:08

Irfan Yusanif


People also ask

How do you write if condition in knockout?

If the condition evaluates to true or true-like value, then the given HTML markup will be processed. Else, it will be removed from DOM. If the condition in the parameter contains an observable value, then the condition is re-evaluated whenever the observable value changes.

What is data bind knockout?

Knockout's declarative binding system provides a concise and powerful way to link data to the UI. It's generally easy and obvious to bind to simple data properties or to use a single binding.

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.


1 Answers

KO observables are functions and to get their value inside expressions you need to call them without any argument e.g.: $parent.category()

So you need to change your code to:

<!-- ko if: $parent.category() == "Electronics"-->
   <div>abc</div>
<!--/ko-->

In your original code you are comparing the observable function ($parent.category) and not its value with "Electronics" that is why its always false.

like image 138
nemesv Avatar answered Sep 28 '22 17:09

nemesv