Search code examples
javascriptjquery-pluginsknockout.jsknockout-templating

dynamic data binding in nested templates in knockout js


I am using MVC framework and knockout js combination. I am bit new to knockout js. I need to bind data dynamically through API calls in my nested knockout templates. I am not finding any way about how to do that.

my nested templates are:

enter code here
<div data-bind="template: {name: 'ListTemplate', foreach: Data}">
</div>

<script type="text/html" id="ListTemplate">
    <h3>
        Contributions (${ Count })
    </h3>
    <img src=" ${ Image } " />
    <p>
       <span> ${ Name } </span>
       <div data-bind="template: {name: 'goalsTemplate', foreach: goals}"></div>
    </p>
</script>

<script type="text/html" id="goalsTemplate">
    Goal:
    <a href="#"> ${ Goals } </a> Ends on
    <code> ${ Date } </code>
</script>

and my viewModel is:

var viewModel = {(
    Data: ko.observableArray([]),
    goals: ko.observableArray([])
});

function userData(Count, Image, Name) {
        return {
            Count: ko.observable(Count),
            Image: ko.observable(Image),
            Name: ko.observable(Name)
        };
}

function goalDetail(Goals, Date) {
        return {
            Goals: ko.observable(Goals),
            Date: ko.observable(Date)
        };
}

$(document).ready(function() {
     $.ajax({
            type: "GET",
            url: siteBaseUrl + 'api/Detail',
            dataType: 'json',
            success: function (data) {
                $(data).each(function (index, type) {
                    viewModel.Data.push(new userData(..,..,..));
                });
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('error status code:' + xhr.status);
                alert('error message:' + thrownError);
                alert('error details:' + xhr.responseText);
            }
        });
});

How should I bind data in goals array through function(goalDetail) inside Data array?


Solution

  • As per my understanding ,Goals and Data is part of main viewModel and you want to use Parent Viewmodel inside Foreach binding , in that case all you need is $parent as below

    <div data-bind="template: {name: 'goalsTemplate', foreach: $parent.goals}">