JQuery Knockout for while loop inside template

I want to create a tree structure table.

I have a json array of strings. One line may have other child lines.

[ { "Name": "Row 1", "Depth": 1, "Rows": [{ "Name": "Row 1.1", "Depth": 2, "Rows": [] }] }, { "Name":" Row 2", "Depth": 1, "Rows": [] } ] 

The template that I have for the line (which does not work) is as follows:

 <script type="text/html" id="row-template"> <tr> {{ for(var i = 1; i<= Depth; i++) { }} <td class='col'></td> {{/for}} <td data-bind="text: Name"></td> </tr> </script> 

Is there a way to use duplicate statements inside a knockout pattern, so I can add extra n columns that I need for each row?

+4
source share
1 answer

I think in terms of MVVM you are overloading the markup; So my suggestion is: why are you not defining a computed value that returns an array of elements from viewModel?

For example, ViewModel

 function MyViewModel() { var self = this; self.Depth= ko.observable(10); self.DepthRepeated= ko.computed(function(){ var ret = []; for(var i =0; i<self.Depth(); i++) ret.push(i);//note: very dirty way to create/populate an array!..but it just for PoC return ret; }); } 

Html:

 <div data-bind="foreach: DepthRepeated"></div> 

(of course, in the html part I inserted a div, you will enter td / tr)

+1
source

All Articles