Angularjs ng-repeat 对象中的数组

Angularjs ng-repeat over an array in objects

我想使用 ng-repeat 遍历对象中数组中的元素。

这是我目前所做的:

控制器:

app.controller('videoDisplayCtrl', function($scope){

var videos = 
    [
        {
        title: 'Course introduction',
        pictureUrl: 'https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcS_kNT5UnXz5dQ6tId9YO0wIJ7YSgRvD1SUxyfdXcXZVdOH7z4b',
        length: '3:32',
        category: 'IT',
        subscribers: 3,
        date: new Date(2014, 12, 15),
        haveSubtitles: false,
        comments: [
            {
            username: 'Pesho Peshev',
            content: 'Congratulations Nakov',
            date: new Date(2014, 12, 15, 12, 30, 0),
            likes: 3,
            websiteUrl: 'http://pesho.com/'
            },
            {
            username: 'Pesho Peshev1',
            content: 'Congratulations Nakov',
            date: new Date(2014, 12, 15, 12, 30, 0),
            likes: 3,
            websiteUrl: 'http://pesho.com/'
            },
            {
            username: 'Pesho Peshev2',
            content: 'Congratulations Nakov',
            date: new Date(2014, 12, 15, 12, 30, 0),
            likes: 3,
            websiteUrl: 'http://pesho.com/'
            }
            ]
        }
    ];
    $scope.videos = videos;
    console.log(videos);});

在视图中我这样做了:

<div ng-controller="videoDisplayCtrl">
    <h2 ng-repeat="x in videos">
        {{x.comments[0].username}}
    </h2>
</div>

这将只显示 "comments" 数组第一个对象的第一个 "username"。我错过了一些东西,但我看不到什么。

那是因为您只显示了第 [0] 个元素。 删除它!

<h2 ng-repeat="x in videos">
    <div ng-repeat="y in x.comments"> 
         {{y.username}}
     </div>    
</h2>

更新:

工作FIDDLE

<div ng-controller="videoDisplayCtrl">
    <div ng-repeat="x in videos">
         <h2 ng-repeat="comment in x.comments">
        {{comment.username}}
         </h2>
    </div>
</div>

您需要两个循环,一个循环遍历您的视频,第二个循环遍历每个视频中的评论,这是另一个数组。

你的评论也在Array里面,所以你还需要一个ng-repeat才能显示:

<div ng-controller="videoDisplayCtrl">
    <div ng-repeat="video in videos">
        <h2 ng-repeat="comment in video.comments">{{comment.username}}</h2>
    </div>
</div>

顺便说一句,为您的 variables/properties 选择一个可读的名称是一个很好的做法,而不是像 x.

这样的名称

有两种方法可以做到:

1 - 删除“[0]”,这将使 ng-repeat 从数组的迭代中获取数据。

<div ng-controller="videoDisplayCtrl">
   <h2 ng-repeat="x in videos">
       {{x.comments.username}}
   </h2>
</div>

2 - 分配给 "x" ng-repeat 声明中的数组

<div ng-controller="videoDisplayCtrl">
    <h2 ng-repeat="x in videos.comments">
        {{x.username}}
    </h2>
</div>