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

我应该如何通过数据数组中的函数(goalDetail)绑定目标数组中的数据?

4

1 回答 1

2

根据我的理解,目标和数据是主视图模型的一部分,您想在 Foreach 绑定中使用父视图模型,在这种情况下,您只需要 $parent 如下

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

于 2012-11-06T05:47:39.287 回答