KnockoutJS If Binding

In the last article we started control flow bindings. We saw what foreach binding is and how to use it. In this article we shall study yet another type of control flow binding i.e. KnockoutJS if binding. This binding is similar to if statement (if you familiar with any programming language). Basically if binding specifies whether a section of HTML markup along with its data-binding attributes shall be displayed or not. The decision of if binding is based on expression that returns true-like or false-like output. If the expression evaluates to true, the markup section is displayed and vice versa.

It is important to differentiate here between the if binding and the visible binding. The visible binding maintained the html markup on the screen and the associated data-bind attributes remained on the webpage, visible binding only toggled its visibility. However, if binding adds or removes the markup from page totally along with their associated data-bind attributes. Let’s have a look at our first example to see KnockoutJS if binding in action.

If binding Example!

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
    
</head>

<body>
    

    <label><input type="checkbox" data-bind="checked: Male" /> Male</label>
 
<div data-bind="if: Male">Student is a Male.</div>
    
    
<script>
    function StudentModel() {
    this.Male = false;
}

ko.applyBindings(new StudentModel());
    
</script>
    
</body>
</html>

Download the code Try the code

In the above code we have check box and a div in html view section. In the javascript view model section we create model named StudentModel with one parameter i.e. Male. The value assigned to Male is true by default. Now come back to view section, here we set the “checked” attribute of the check box to the value of Male parameter which is true. Therefore, when you open the page in the browser, you shall see Male checkbox checked. Secondly, the div contains an if binding which says that display the div only if Male parameter is set to true. When you open the page, the text inside the div shall be visible.

Now in the javaScript view model, change the value of Male parameter to false and open the page. You shall male checkbox unchecked and the contents of the div removed from the page.

<<< knockoutJS foreach BindingsKnockoutJS If Not Binding >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .