Knockout js 'with' binding, hide if array is empty

I have a category dropdown that controls a dropdown of a subcategory. I want to hide the drop-down list of subcategories if the array of subcategories is empty for the selected category.

Sample code below:

<script> self.categories = ko.observableArray([ {"name": "top 1", "subcategories":[ {"name": "sub 1"}, {"name": "sub 2"} ]}, {"name": "top 2", "subcategories":[]} ]); self.selected_category = ko.observable(); self.selected_sub_category = ko.obserable(); </script> <div> <select data-bind="options: categories, optionsText: "name", optionsCaption: "Select", value: selected_category"></select> </div> <div data-bind="with:selected_category"> <select data-bind="options: subcategories, optionsText: "name", optionsCaption: "Select", value: selected_sub_category"></select> </div> 

+7
source share
1 answer

You need to combine the with binding with if (or visible ) binding, where you can specify your condition:

 <div data-bind="with: selected_category"> <!-- ko if: subcategories.length > 0 --> <select data-bind="options: subcategories, optionsText: 'name', optionsCaption: 'Select', value: $parent.selected_sub_category"></select> <!-- /ko --> </div> 

JSFiddle demo .

Note the use of $parent in value: $parent.selected_sub_category , you need to access the "parent" object because with creates a child context.

If you do not want to display the entire div when the subsection is empty, you need to move the with and if beyond the div , because KO does not allow multiple control flows of binding to one element.

So, in this case, your HTML will look like this:

 <!-- ko with:selected_category --> <!-- ko if: subcategories.length > 0 --> <div class="mydiv"> <select data-bind="options: subcategories, optionsText: 'name', optionsCaption: 'Select', value: $parent.selected_sub_category"> </select> </div> <!-- /ko --> <!-- /ko --> 

JSFiddle demo .

+10
source

All Articles