Sasi Dhivya Sasi Dhivya - 1 month ago 7
Javascript Question

How to bind the JSON object data to knockout binding with template option?

I am working with knockout js. Now i am using template option and local json data as datasource.In this i am unable to bind the data to node within template.

Please get my html code below:

<div data-bind="template:{name:'treeTemplate',data:{da:Data}}"></div>
<script id="treeTemplate" type="text/html">
<b data-bind="text:$data.text"></b>

Please get my script section below

var treeData = [
{ id: 1, text: "UK"},
{ id: 2, text: "Steven John" },
{ id: 3, text: "USA" },
{ id: 5, text: "Andrew" },
{ id: 4, text: "Angelica" }

window.viewModel = {
value: ko.observable(new Date(2015, 06, 15)),
Data: ko.observableArray(treeData)
$(function () {
// declaration

I have updated the sample in jsfiddle also. Please get the below link:

Can you please anyone suggest on this.Thanks for any help.


your first problem is the use of data in the template object.


for iterating through a array you need to use foreach


so because of this you need to update your bindings

// from this
<b data-bind="text:$data.text"></b>

// to this
<b data-bind="text: text"></b>

here is a working example :

Also, documentation on using "foreach" with a named template :