2011-09-14 22 views
0

私は(もjsfiddleで)次のコードでいます。これによりは、jQueryのテンプレートとmulticolumのHTMLテーブルを作成し、knockoutjs

<table> 
    <thead><tr><th>Equation</th><th>Equation</th></tr></thead> 
<tbody data-bind="template: {name: 'equationTemplate', foreach: equations}"></tbody> 
</table> 

<script language="javascript" type="text/javascript"> 

</script> 

<script type="text/x-jquery-tmpl" id='equationTemplate'> 
    <!-- In here I want to be able to break it up into two 
    columns of two rather than one column of four--> 
    <tr> 
     <td>${first}+${second}=<input data-bind="value: answer"/></td> 
    </tr> 
</script> 

はJS:私はにテンプレートを変更する方法を

$(document).ready(function() { 

    var viewModel = { 
     equations: ko.observableArray([ 
      { first: 1, second: 2, answer: 3 }, 
      { first: 4, second: 4, answer: 8 }, 
      { first: 10, second: 10, answer: 20 }, 
      { first: 5, second: 5, answer: 10}]) 
    }; 

    ko.applyBindings(viewModel); 
}); 

これを2行2列のテーブルに出力しますか?式10 + 10 = 20と5 + 5 = 10が2番目の列に表示されます。

大変助かりました。

答えて

1

1つの方法は、テンプレートバインディングのforeachオプションの代わりに{{each}}に切り替えて、インデックスにアクセスできるようにすることです。 {{each}}を使うことの欠点は、方程式が動的に追加/削除されるとテンプレートが完全に再描画されることです。ここ

<table> 
    <thead><tr><th>Equation</th><th>Equation</th></tr></thead> 
<tbody data-bind="template: { name: 'equationTemplate', foreach"></tbody> 
</table> 

<script type="text/x-jquery-tmpl" id='equationTemplate'> 
    {{each equations}} 
     {{if $index % 2 == 0}}<tr>{{/if}} 
      <td>${first}+${second}=<input data-bind="value: answer"/></td> 
     {{if $index % 2 == 1}}</tr>{{/if}} 
    {{/each}} 
</script> 

サンプル:それは次のようになり

http://jsfiddle.net/rniemeyer/QESBn/1/

別の方法としては、行/列にマップ構造でデータを表しdependentObservableを構築することです。

サンプルは次のとおりです。http://jsfiddle.net/rniemeyer/QESBn/2/

関連する問題