开发者

How to write a template expanding to multiple elements?

I'd like to write a knockout.js template which should expand into a set of table cells. In other words, something like:

<tr>
    <td>Cell one</td>
    <td>Cell two</td>
    <div data-bind="template: ..."></div>
    <td>Cell six</td>
</tr>
<script id="..." type="text/html">
    <td>Cell three</td>
    <td>Cell four</td>
    <td>Cell five</td>
</script>

But the div tag isn't allowed in the tr, of course, and I can't figure out any way to coax knockout to replace the div tag with the template expansion, rather than nesting the expansion inside the div.

Anybody know 开发者_运维技巧a way to accomplish this?


You can do this with the new "containerless" templates like this:

<tr>
<td>Cell one</td>
<td>Cell two</td>    
<!-- ko foreach: names -->
    <td>Cell three<span data-bind="text: name"></span></td>
    <td>Cell four</td>
    <td>Cell five</td>
<!-- /ko -->
<td>Cell six</td>

with js like this:

$(function() {
var viewModel = {
    names: ko.observableArray([ { name: "Bob"}, {name: "John"}])
};
ko.applyBindings(viewModel);

});

Here is a jsfiddle that shows it in action: jsfiddle

Here is a jsfiddle that shows it without the foreach: jsfiddle

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜