Knockout JS的'with'绑定,如果数组为空则隐藏

8
我有一个类别下拉列表,它控制一个子类别下拉列表。如果所选类别的子类别数组为空,我想隐藏子类别下拉列表。
以下是示例代码:
<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>  

1个回答

11
你需要将with绑定与if(或visible)绑定结合起来,以便在其中指定条件:
<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。

请注意在value: $parent.selected_sub_category中使用$parent,因为with创建了一个子上下文,你需要它来访问“父”对象。

如果您不想在子集为空时呈现整个div,则需要将withif移动到div之外,因为KO不允许在同一元素上使用多个控制流绑定。

因此,在这种情况下,您的HTML将如下所示:

<!-- 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。


谢谢nemesv。有没有一种方法将with和if结合到一个data-bind属性中。原因是我希望div根本不被渲染出来。 - the-a-train
“if”和“with”不能在一个数据绑定属性中组合使用。如果您尝试这样做,您将收到以下错误消息:“多个绑定(with 和 if)正在尝试控制同一元素的后代绑定。您不能在同一元素上同时使用这些绑定。”但是,您可以将它们“移出去”,请参见我的更新答案。 - nemesv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接