javascript - Knockout js 中嵌套模板中的动态数据绑定(bind)

标签 javascript jquery-plugins knockout.js knockout-templating

我正在使用MVC框架和knockout js组合。我对 knockout js有点陌生。我需要通过嵌套 knockout 模板中的 API 调用动态绑定(bind)数据。我没有找到任何方法来做到这一点。

我的嵌套模板是:

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>

我的 View 模型是:

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)绑定(bind)目标数组中的数据?

最佳答案

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

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

关于javascript - Knockout js 中嵌套模板中的动态数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13244734/

相关文章:

javascript - 如何列出 Node js 脚本中的所有函数?

javascript - nodejs中如何保证Knex连接

javascript - ASP.NET网站结构

jquery - 未捕获的类型错误 : Cannot read property 'id' of undefined

javascript - 使用 Knockout 映射插件使用非规范化数据

javascript - jQuery mouseover 在 mouseout 上运行

Jquery插件获取DIV ID

Jquery Li 图片库

javascript - knockout 计算的可观察值未触发 'write'

javascript - knockout 因变量: how to define structure properly