Title is taken from here. I just wanted to write my small example of template binding for future reference.
HTML:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/index.js"></script>
<script type="text/javascript" src="/knockout-3.2.0.js"></script>
</head>
<body onload="doTheApply()">
Here is example from knockout:
<span data-bind="template: { name: 'person-template', data: buyer}"></span>
<script type="text/html" id="person-template">
<h3 data-bind="text: name"></h3>
<p>Credits: <span data-bind="text: credits"></span></p>
</script>
</body>
</html>
JS:
myViewModel = {
buyer: {name: "Franklin1", credits: 450}
}
function doTheApply() {
ko.applyBindings(myViewModel);
}
Example download from here.
---
Another example:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/knockout-3.2.0.js"></script>
</head>
<body>
My template:
<script type="text/html" id="myTemplate">
<input data-bind="attr: {type: inputType}" placeholder="I am going to be changed">
</script>
<span data-bind="template: {name: 'myTemplate', data: {inputType: 'search'}}">
</body>
<script type="text/javascript">
ko.applyBindings();
</script>
</html>
Here notice line:
<span data-bind="template: {name: 'myTemplate', data: {inputType: 'search'}}">
As you can see, $data I bind directly in the template definition.
---
One example with radio buttons:
HTML:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/knockout-3.2.0.js"></script>
<script type="text/javascript" src="/index.js"></script>
</head>
<body>
<span data-bind="template: { name: 'myRadioButtons', foreach: myRadioButton }"></span>
<script type="html/text" id="myRadioButtons">
Test: <input type="radio" data-bind="checked: myValue"><p/>
</script>
</body>
</html>
JS:
var myRadioButtonViewModel = {
myRadioButton: [
{myValue: 1},
{myValue: 2}
]
}
window.onload = function () {
ko.applyBindings(myRadioButtonViewModel);
}