How to render a table with some fixed and some dyn

2019-04-10 13:25发布

I want to get a table with these columns:

  • [Name]
  • [Club]
  • [Dynamic1]
  • [Dynamic2]
  • [Dynamic3]
  • etc etc.

I tried this:

<table>
    <tbody data-bind="template: { name: 'rowTmpl', foreach: runners }">
    </tbody>
</table>
<script id="rowTmpl" type="text/html">
    <tr data-bind="template: { name: 'colTmpl', foreach: radios }" >
        <td data-bind="text: name"></td>
        <td data-bind="text: club"></td>
    </tr>
</script>
<script id="colTmpl" type="text/html">
        <td>aa</td>
</script>
@section Scripts{
    <script src="/Scripts/knockout-1.3.0beta.js" type="text/javascript"></script>
    <script type="text/javascript">
        var vm = {
            id: 1,
            name: 'H21',
            radios: ['2km', '4km', 'mål'],
            runners: ko.observableArray([
                { name: 'Mikael Eliasson', club: 'Göteborg-Majorna OK', radios: ko.observableArray([{}, {}, {}]) },
                { name: 'Ola Martner', club: 'Göteborg-Majorna OK', radios: ko.observableArray([{}, {}, {}]) }
            ])
        };

        ko.applyBindings(vm);
    </script>
}

My problem is that the tds inside colTmpl is not databoud, it's empty and placed after the third column with the text 'aa'. See this fiddle.

2条回答
地球回转人心会变
2楼-- · 2019-04-10 14:14

It is because of the fact that the content of <tr data-bind="template: { name: 'colTmpl', foreach: radios }" > is getting replaced by the template you specify.

If you instead do:

<script id="rowTmpl" type="text/html">
<tr> 
    <td data-bind="text: name"></td>
    <td data-bind="text: club"></td>
    <td data-bind="template: { name: 'colTmpl', foreach: radios }" ></td>
</tr>
</script>
<script id="colTmpl" type="text/html">
    <span> . aa . </span>
</script>

It will render.

查看更多
放荡不羁爱自由
3楼-- · 2019-04-10 14:32

If you are using 1.3 beta (your fiddle is referencing the latest build), then you can do this:

<table>
    <tbody data-bind="foreach: runners">
        <tr>
            <td data-bind="text: name"></td>
            <td data-bind="text: club"></td>
            <!-- ko foreach: radios-->
            <td>aa</td>
            <!-- /ko -->
        </tr>
    </tbody>
</table>

Sample here: http://jsfiddle.net/rniemeyer/bd7DT/

If you need to do this prior to 1.3 with jQuery templates, then you would want to pass the first item in your array into the template via templateOptions and do an {{if}} to check if you are on the first radio and render the two cells. Another option in jQuery templates is to use {{each}} around your dynamic cells rather than the foreach option of the template binding on the parent. You would lose some efficiency, if your columns are frequently changing dynamically. I can provide a sample for these two options, if necessary.

查看更多
登录 后发表回答