简体   繁体   中英

Array of Arrays with ng-repeat

I am trying to show a list grouped by date but the list isn't sorted and I don't know when the date change. It's like I have this Json :

list = 
{name: first, date: 2014-05-21}, {
{name: second, date: 2014-05-20}, {
{name: third, date: 2014-05-21}

I'd like to make the following html :

<li><h3>2014-05-21</h3>
 <ul>
  <li>first</li>
  <li>third</li>
 </ul>
</li>
<li><h3>2014-05-20</h3>
 <ul>
 <li>second</li>
 </ul>
</li>

Do you have an idea ?

I tried to make an Array of arrays with two ng-repeat like this :

for (i in list){
 if ($scope.listToShow[list.date] == undefined) {
     $scope.listToShow[list.date] = newArray();
 }
 $scope.listToShow[list.date].push(list[i]); 
}

But I don't success to show this.

Check the post , it exactly mention what you want to achieve.

http://www.bennadel.com/blog/2456-grouping-nested-ngrepeat-lists-in-angularjs.htm

OR

You can also use ng-repeat-start and ng-repeat-end (inbuilt directives) to achieve the same. Click here for Reference link.

I achieved a working example. Is not very sophisticated and could be improved, but you get the basic idea by looking at the code. The trick is to group your data (no fancy angular feature, just plain old javascript) and then display the grouped data in the view. I had to mantain a keys property for the grouped object because apparently angularjs views dont' support Object.keys(obj) .

See it here

EDIT: updated with the (key,obj) in grouped construct, no more need for keys array.

I was testing a bit with a array of arrays inside a table. It's not the cleanest one.

//controller
$scope.list = [
    [
        {name: 'first', date: '2014-05-21'},
        {name: 'lala', date: '2014-07-32'},
        {name: 'fada', date: '2014-07-32'}
    ], 
    [
        {name: 'second', date: '2014-05-20'},
        {name: 'dada', date: '2014-54-32'},
        {name: 'mama', date: '2014-07-32'}
    ], 
    [
        {name: 'third', date: '2014-05-21'},
        {name: 'nana', date: '2014-78-32'},
        {name: 'rara', date: '2014-07-32'}
    ]
];

//view
<table>
    <tr class="parent" ng-repeat-start="(key, item) in list">
        <td>{{ item[0].name }}</td>
        <td>{{ item[0].date }}</td>
    </tr>
    <tr class="child" ng-repeat-end="", ng-repeat="part in list[key].slice(1, list[key].length)">
        <td>{{ part.name }}</td>
         <td>{{ part.date }}</td>
    </tr>
</table>

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