- KnockoutJS Tutorial
- KnockoutJS - Home
- KnockoutJS - Overview
- KnockoutJS - Environment Setup
- KnockoutJS - Application
- KnockoutJS - MVVM Framework
- KnockoutJS - Observables
- Computed Observables
- KnockoutJS - Declarative Bindings
- KnockoutJS - Dependency Tracking
- KnockoutJS - Templating
- KnockoutJS - Components
- KnockoutJS Resources
- KnockoutJS - Quick Guide
- KnockoutJS - Resources
- KnockoutJS - Discussion
KnockoutJS - Ifnot Binding
Ifnot binding is the negating of if binding. It is just another flavor of if binding.
Syntax
ifnot: <binding-condition>
Parameters
Parameter is a condition you want to check. 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. Correspondingly, the related markup will be added or removed based on the condition result.
Example
Let us take a look at the following example which demonstrates the use of ifnot binding.
<!DOCTYPE html> <head> <title>KnockoutJS ifnot binding</title> <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" type = "text/javascript"></script> </head> <body> <p><strong>Product details</strong></p> <table border = "1"> <thead> <th>Product Name</th><th>Price</th><th>Nature</th> </thead> <tbody data-bind = "foreach: productArray "> <tr> <td><span data-bind = "text: productName"></span></td> <td><span data-bind = "text: price"></span></td> <td data-bind = "ifnot: $data.price < 200 ">Expensive</td> </tr> </tbody> </table> <script type = "text/javascript"> function AppViewModel() { self = this; self.productArray = ko.observableArray([ {productName: 'Milk', price: 100}, {productName: 'Oil', price: 10}, {productName: 'Shampoo', price: 1200} ]); }; var vm = new AppViewModel(); ko.applyBindings(vm); </script> </body> </html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in if-not-bind.htm file.
Open this HTML file in a browser.
This example will populate the third column which talks about the products’ nature (expensive or not) depending on the price. Note that the individual property is accessed using $data binding context.