Skip to content

Instantly share code, notes, and snippets.

@devdays
Created December 16, 2014 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devdays/0d0e0c214912c09baff6 to your computer and use it in GitHub Desktop.
Save devdays/0d0e0c214912c09baff6 to your computer and use it in GitHub Desktop.
Object JavaScript - Knockout foreach using nested named templates
<body>
<h2>Products</h2>
<table data-bind="template: { name: 'product-template',
foreach: productArray, as: 'productA' }">
</table>
<script type="text/html" id="product-template">
<tr>
<td data-bind="text: product"></td>
<td data-bind="text: type"></td>
<td>
<ul data-bind="template: { name: 'parts-template', foreach: parts, as: 'part' }">
</ul>
</td>
</tr>
</script>
<script type="text/html" id="parts-template">
<li>
<span data-bind="text: part"></span>
in
<span data-bind="text: productA.product"></span>
</li>
</script>
<script src="Scripts/knockout-2.2.1.debug.js"></script>
<script type="text/javascript">
function ViewModel() {
this.productArray = ko.observableArray([
{ product: "Widget", type: "Tool",
parts: ['Foo', 'Whatchmacallit' ] },
{ product: "Bolt", type: "Fastener",
parts: ['Bolt', 'Washer', 'Wingnut' ] },
{ product: "Washer", type: "Fastener", parts: ['Washer'] },
{ product: "Screwdriver", type: "Tool", parts: [] }
]);
}
ko.applyBindings(new ViewModel());
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment