21

我对角度有点陌生,我的 json 和 ng-repeats 有问题。我有一个“模块”列表,然后是其中的“周”列表:

{
    "modules":
        {
            "module1":
                {
                   "title":"name of module1",
                   "description":"description of module1",
                   "weeks":{"week1":{"title":"Week 01"}
                },
            "module2":
                {
                   "title":"name of module2",
                   "description":"description of module2",
                   "weeks":{"week2":{"title":"Week 02"},"week3":{"title":"Week 03"}
                }
        }
}

我的最终输出是一个表格,我可以让模块重复,但我很难通过让几周循环来理解我做错了什么。这是我的模板:

<table class="table table-bordered" ng-repeat="module in ocw.modules">
<tr>
    <td>
        <h3 class="moduletitle">{{ module.title }}</h3>
        <h4>Description</h4>
        <p>{{ module.description }}</p>
    </td>
</tr>
<tr ng-repeat="week in ocw.modules.weeks">
    <td>
        {{ week.title }}
    </td>
</tr>
</table>

所以这将输出 2 个表格,带有正确的标题和描述,但我似乎无法正确显示周数。请注意,某些“模块”有不止一个“周”。我不确定错误是在我的模板还是 json 中。

谢谢你的帮助。小号

4

3 回答 3

39

我会改变你的数据结构,所以你的模块和周是一个对象数组。

演示:http ://plnkr.co/edit/e41n9vAMMLf0WWIUQ8HO?p=preview

json数据:

{
    "modules":
        [
                {
                   "title":"name of module1",
                   "description":"description of module1",
                   "weeks":[{"id":1, "title":"Week 01"}]
                },

                {
                   "title":"name of module2",
                   "description":"description of module2",
                   "weeks":[{"id":2, "title":"Week 02"},{"id":3,"title":"Week 03"}]
                }
        ]
}

然后你的标记将是:

<table class="table table-bordered" ng-repeat="module in ocw.modules">
<tr>
    <td>
        <h3 class="moduletitle">{{ module.title }}</h3>
        <h4>Description</h4>
        <p>{{ module.description }}</p>
    </td>
</tr>
<tr ng-repeat="week in module.weeks">
    <td>
        {{ week.title }}
    </td>
</tr>
</table>

当您迭代每个模块时,在这种情况下是module为了获得周数,它module.weeksmodule.title. 在您的示例中,您在迭代中并尝试引用ocw.modules.weeks与您的 json 结构不匹配的内容。

于 2013-05-10T15:34:04.437 回答
4

改变

<tr ng-repeat="week in ocw.modules.weeks">

<tr ng-repeat="week in module.weeks">

因为你现在有一个模块在你的范围内,而这是你之后的那个模块的几周。

于 2013-05-10T15:39:51.840 回答
2

只是为了完整起见,如果你的表格有一些风格和thead,这ngRepeat将创建多个表格,这不是我们想要的。

为避免这种情况,只需在元素中使用第ng-repeat一个:tbody

<table class="table table-bordered">
    <tbody ng-repeat="module in ocw.modules">
        <tr>
            <td>
                <h3 class="moduletitle">{{ module.title }}</h3>
                <h4>Description</h4>
                <p>{{ module.description }}</p>
            </td>
        </tr>
        <tr ng-repeat="week in module.weeks">
            <td>{{ week.title }}</td>
        </tr>
    </tbody>
</table>
于 2013-07-29T13:36:58.790 回答