Purpose
I would like to be able to have a Knockout custom component that can have either static content or dynamic content using the foreach binding.
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<h2>Static - Items 1 through 3</h2> | |
<custom-element> | |
<span>item 1.1</span> | |
<span>item 1.2</span> | |
<span>item 1.3</span> | |
</custom-element> | |
<hr /> | |
<h2>Dynamic Attempt 1 - Items 1 through 3</h1> | |
<custom-element> | |
<!-- ko foreach: { data: ['item 2.1', 'item 2.2', 'item 2.3'], as: 'item' } --> | |
<span data-bind="text: item"></span> | |
<!-- /ko --> | |
</custom-element> | |
<hr /> | |
<h2>Dynamic Attempt 2 - Items 1 through 3</h1> | |
<custom-element data-bind="foreach: { data: ['item 2.1', 'item 2.2', 'item 2.3'], as: 'item' }"> | |
<span data-bind="text: item"></span> | |
</custom-element> | |
<script src="//rawgit.com/knockout/knockout/v3.3.0/dist/knockout.debug.js"></script> | |
<script id="tmpl" type="text/html"> | |
<!-- ko foreach: { data: $componentTemplateNodes, as: 'node' } --> | |
<!-- ko if: node.nodeType == 1 --> | |
<h3 data-bind="template: { nodes: [node] }"></h3> | |
<!-- /ko --> | |
<!-- /ko --> | |
</script> | |
<script> | |
ko.components.register('custom-element', { | |
template: { | |
element: 'tmpl' | |
} | |
}); | |
ko.applyBindings(); | |
</script> |