问题描述:

<div id="metro-scrollbar" data-bind="foreach: data.sections , visible: data.sections.length > 0">

<section data-bind="foreach: $data.tiles, visible: $data.tiles.length > 0, css: { 'last' : $parent.isLastSection($index)}">

<div data-bind="attr : {'class' : $root.getClass($data,$parentContext.$index,$index)} ">

<div data-bind="attr : {'class' : $root.getAspectClass($data,$index)} "></div>

<div class="live-tile">

<span class="tile-title" data-bind="text: title, css:{'big' : bigtitle}"></span>

<div>

<p>a</p>

</div>

</div>

</div>

</section>

</div>

I have the above binding. I need to in some casses to inject a wrapper around the inner divs.

<div>

<section>

<-- if $myFunction() inject <div> -->

<div>

<div></div> // THIS IN HERE SHOULD BE THERE ALWAYS:

<div > // THIS IN HERE SHOULD BE THERE ALWAYS:

</div> // THIS IN HERE SHOULD BE THERE ALWAYS:

</div>

<-- if $myFunction() inject </div> -->

</section>

</div>

I hope it makes sense.

网友答案:

s093294 had the right idea. Here's an example of a solution (and a jsFiddle):

View

<button data-bind="click: click">Toggle</button>

<section data-bind="template: { name: templateName }"></section>

<script type="text/html" id="outer-tmpl">
    <div data-bind="template: { name: 'inner-tmpl' }">
    </div>
</script>
<script type="text/html" id="inner-tmpl">
    <div>first inner div</div>
    <div>second inner div</div>
</script>

Model

viewModel = {
    toggle: new ko.observable(true),
    templateName: function () {
        return viewModel.toggle() ? 'outer-tmpl' : 'inner-tmpl';
    },
    click: function () {
        viewModel.toggle(!viewModel.toggle());
    }
}
ko.applyBindings(viewModel);
相关阅读:
Top