2

私はMVCフレームワークとノックアウトjsの組み合わせを使用しています。私はjsをノックアウトするのは少し新しいです。ネストされたノックアウトテンプレートのAPI呼び出しを介してデータを動的にバインドする必要があります。私はそれを行う方法について何の方法も見つけていません。

ネストされたテンプレートは次のとおりです。

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>

私のviewModelは次のとおりです。

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);
            }
        });
});

データ配列内のfunction(goalDetail)を介してgoals配列のデータをバインドするにはどうすればよいですか?

4

1 に答える 1

2

私の理解によると、目標とデータはメインのviewModelの一部であり、Foreachバインディング内でParent Viewmodelを使用したい場合、必要なのは以下のように$parentだけです。

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

于 2012-11-06T05:47:39.287 に答える