Using ng-repeat on JSON containing JSON

坚强是说给别人听的谎言 提交于 2019-11-27 18:49:22

I would change your data structure so your modules and weeks are an array of objects.

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

json data:

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

And then your markup would be:

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

As you are iterating over each module which in this case is module to get the weeks it is just module.weeks much the same as module.title. In your example you are inside the iteration and trying to reference ocw.modules.weeks which doesn't match your json structure.

Change

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

to

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

because you now have a module in your scope, and it's that module's weeks you're after.

Just for the sake of completeness, if your table has some style and thead, this ngRepeat will create multiple tables, which is not what we want.

To avoid this, just use the first ng-repeat in a tbody element:

<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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!