ng-newbie
ng-newbie

Reputation: 35

How to order a Parent Child Hierarchy in Angularjs

This is my data:

$scope.data = [{
        id: 1,
        group: 'Parent Comment 1',
        pid: 0
    }, {
        id: 2,
        group: 'Parent Comment 2',
        pid: 0
    }, {
        id: 3,
        group: 'Child 1 P1',
        pid: 1
    }, {
        id: 4,
        group: 'Child 1 P2',
        pid: 2
    }, {
        id: 5,
        group: 'Parent Comment 3',
        pid: 0
    }];

I want output as below:

ParentComment 1
Child 1 P1
Parent Comment 2
Child 1 P2
Parent Comment 3

I tried using orderBy but was unable to get desired output.

Upvotes: 2

Views: 1014

Answers (1)

raina77ow
raina77ow

Reputation: 106395

To output such a (two-level) tree, you just provide an orderBy predicate expression as an array:

['pid || id', 'id']

That means following:

  • the first ordering criteria will be either parentId or id, if the former is 0. With this trick child and parents will be grouped in the output...
  • ... but, as you 1) still need to place the parents above the children, and 2) order children themselves, there should be a second criteria - id alone.

In other words, your ng-repeat might look as following:

<tr ng-repeat="record in data | orderBy:['pid || id', 'id']">
   <td>{{record.group}}</td>
</tr>

Plunkr.


If you need to process more complex hierarchies, it's probably better to reorganize your data so that each parent comment contains all the children comments. Still, it's possible to implement a predicate for the existing structure too:

$scope.predicate = function(el) {
  var res = [];
  while (el.pid) {
    res.unshift(el.id);
    el = $scope.data[el.pid - 1];
  }
  res.unshift(el.id);
  return res;
};

...
<tr ng-repeat="record in data | orderBy:predicate">...

... but there's a catch: in this code, I assume that id of an element is linearly mapped to its position in the source array. Otherwise you'll have to either look for it at each step, or implement an index; both ways are cumbersome.

Upvotes: 5

Related Questions