Angularjs groupBy + orderBy

后端 未结 5 1747
暗喜
暗喜 2020-12-07 01:01

I am using groupBy from angular-filter to group an array of objects by their date property.

相关标签:
5条回答
  • 2020-12-07 01:45

    try using -

    <div ng-repeat="(day, dayEvents) in events | groupBy: '-date' ">
    

    P.S- I have not used groupBy till now anywhere!But this minus thing works well with orderBy attribute!

    0 讨论(0)
  • 2020-12-07 01:48

    An easier way to reverse an array is to use the code from this answer

    app.filter('reverseOrder', function() {
      return function(items) {
        return items.slice().reverse();
      };
    });
    
    <div ng-repeat="(day, dayEvents) in events | groupBy: 'date' | reverseOrder )">
         <h3>{{ day | date: mediumDate }}</h3>
    </div>
    
    0 讨论(0)
  • 2020-12-07 01:50

    It appears the proper method is to use the | toArray: true | orderBy: customMappingFunction, however, I found the performance on this to be terrible. I came up with a solution that keeps performance up and produces the correct result -- (although it does seem a bit odd!)

    <div ng-repeat="(key, results) in allResults | groupBy: '-someKey' )">
        <h3>{{ key | ltrim: '-' }}</h3>
        <ul>
            <li ng-repeat="result in results">
                {{ result }}
            </li>
        </ul>
    </div>
    

    For whatever reason, adding the - does force the groupBy to sort correctly, but it also adds it to the key, so we can just remove it!

    0 讨论(0)
  • 2020-12-07 01:56

    Recently had the same issue. groupBy creates an object, but the orderBy needs an array, so there's a little bit of funkiness involved. I ended up getting the answer straight from their issues page where one of the authors does an excellent job of explaining it complete with code samples that was basically copy/paste for me.

    https://github.com/a8m/angular-filter/issues/57#issuecomment-65041792

    0 讨论(0)
  • 2020-12-07 01:57

    We can achieve this by ordering the data in controller & converting groupBy output to Array.

    In controller, order the records before sending it to view :

    $scope.events = $filter('orderBy')(events, '-date');
    

    Now the template, receives data in sorted order. After grouping, we need to transform it to Array :

    <div ng-repeat="(day, dayEvents) in events | groupBy: 'date' | toArray:true )">
         <h3>{{ day | dayEvents[0].date: mediumDate }}</h3>
    </div>
    
    0 讨论(0)
提交回复
热议问题