Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate groups in ng-repeat

Tags:

angularjs

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

like image 861
Matsemann Avatar asked Apr 08 '13 21:04

Matsemann


2 Answers

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>
like image 168
lucuma Avatar answered Oct 22 '22 14:10

lucuma


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.

like image 1
Brent Washburne Avatar answered Oct 22 '22 13:10

Brent Washburne