简体   繁体   中英

AngularJS — Ng-repeat through objects of an array

I just started playing around with Angular JS a few days ago. I have this array called posts that has objects in it, which I want to be displayed and categorized by the year in which they have been posted.

This is the posts array:

var posts = [
    {
        title: "First Blog Post of 2015",
        date: "06/24/15",
        content: "This is the first post of the year 2015."
    }, {
        title: "Second Blog Post of 2015",
        date: "07/01/15",
        content: "This is the second post of the year 2015."
    }, {
        title: "First Blog Post of 2014",
        date: "07/11/14",
        content: "This is the first post of the year 2014."
    }
];

As you can see, the posts array contains 3 objects, which represent posts. Each "post" has a title, date, and some content. I want to order them like so:

在此输入图像描述

This is what I currently have:

在此输入图像描述

I was able to access the year, but I can't get into the child objects.

This is what you see in the console when you do console.log($scope.postsByYear); : 在此输入图像描述

I wrote a script that puts the posts in the arrays based on the year in which they have been recorded. It just takes apart the post's date property, which has a date format of mm/dd/yy . I don't know how to ng-repeat those objects within the posts array.

This is what I have:

<div>
    <h1>Blog</h1>
    <ul ng-repeat="year in postsByYear">
        <li>{{year.year}}</li>
        <li ng-repeat="post in postsByYear.posts">{{post.title}}</li>
    </ul>
</div>

I have absolutely no idea why this code isn't working. It gets the date fine, but it cannot access the properties of the post objects. It make sense, right? Post is a placeholder for one of the post objects, and postsByYear.posts should select the title in all the objects...

Here is the jsFiddle link to the code. Your assistance is greatly appreciated.

Just a simple mistake. In your inner repeat, you're looping over the wrong object. Should be

<li ng-repeat="post in year.posts">{{post.title}}</li>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM