2

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?

Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90
Parasignals
  • 129
  • 1
  • 3
  • 7

1 Answers1

2

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}">

Paritosh
  • 2,303
  • 2
  • 18
  • 24
  • hey, how should i add data dynamically to these arrays through function on success of ajax call, any idea??? – Parasignals Nov 09 '12 at 13:15
  • I hope you know about the mappings in knockout.Look into some of these links http://knockoutjs.com/documentation/plugins-mapping.html – Paritosh Nov 09 '12 at 13:39