Matsemann
Matsemann

Reputation: 21784

How to separate groups in ng-repeat

I have items I want to show, normally by using ng-repeat. I want to show the in some order (easy), but whenever the ordered attribute changes, I want some HTML in-between.

Example: (Fiddle):

<div ng-app ng-controller="Main">
   <div ng-repeat="item in items | orderBy:'role'">
        {{item.role}} - {{item.name}}
   </div>
</div>

function Main($scope){
    $scope.items = [{name: 'First', role: 1}, 
                    {name: 'Second', role:2}, 
                    {name: 'Third', role: 1}, 
                    {name: 'Fourth', role: 2}];
    }

I want it to print:

1 - First
1 - Third
(some separator kode)
2 - Second
2 - Fourth

Upvotes: 8

Views: 10327

Answers (2)

Brent Washburne
Brent Washburne

Reputation: 13148

The solution by @lucuma only works on the first time through the loop. If Angular refreshes the list, the variable will still be set from the previous loop.

Instead, I added a new attribute to the list (say, header) during initialization:

function Main($scope){
    $scope.items = [{name: 'First', role: 1, header: false}, 
                    {name: 'Second', role:2, header: false}, 
                    {name: 'Third', role: 1, header: true}, 
                    {name: 'Fourth', role: 2, header: false}];
}

Then the HTML by @lucuma works:

<div ng-app ng-controller="Main">
  <div ng-repeat="item in items | orderBy:'role'">
    <div ng-show="item.header">    // <== with this change
      something here for the header
    </div>
    {{item.role}} - {{item.name}}
  </div>
</div>

Oh, and you could sort the list once at initialization and remove the orderBy filter.

Upvotes: 1

lucuma
lucuma

Reputation: 18339

You will want to create a function in your scope.

$scope.currentRole = 'something';
$scope.CreateHeader = function(role) {
      showHeader = (role!=$scope.currentRole); 
       $scope.currentRole = role;
      return showHeader;
}

And then in your HTML:

<div ng-app ng-controller="Main">
   <div ng-repeat="item in items | orderBy:'role'">
       <div ng-show="CreateHeader(item.role)">
       something here for the header
      </div>
        {{item.role}} - {{item.name}}

   </div>
</div>

Upvotes: 15

Related Questions