0

I have a bunch of objects in an array and I am trying to figure out how to group them within an Angular repeater. For example I want to group the fruit items with a parentTag key to the Tag key of a parent. So Fruit has a tag of 1 and Apple has a parent tag with a value of 1, meaning Apple is grouped with Fruit.

so using this array...

[
{
    "code":"Fruit",
    "tag":1
},
{
    "code":"Apple",
    "tag":2,
    "parentTag":1
},
{
    "code":"Vegetable",
    "tag":3
},
{
    "code":"Meat",
    "tag":4
},
{
    "code":"Banana",
    "tag":5,
    "parentTag":1
},
{
    "code":"Carrot",
    "tag":6,
    "parentTag":3
},
{
    "code":"Chicken",
    "tag":7,
    "parentTag":4
}
]

I am trying to group the objects like this...

Fruit

  • Apple
  • Banana

Vegetable

  • Carrot

Meat

  • Chicken

So far I have a repeater that only displays the objects...

<div ng-repeat="product in products">
{{code}}
<span ng-if="product.tag != null">{{product.tag}}</span>
<span ng-if="product.parentTag > null">{{product.parentTag}}</span>
</div>

But I don't know how to use the groupBy in this case. any ideas?

Jose the hose
  • 1,805
  • 9
  • 33
  • 56
  • possible duplicate of [How can I group data with an Angular filter?](http://stackoverflow.com/questions/14800862/how-can-i-group-data-with-an-angular-filter) – Caramiriel Apr 01 '15 at 10:48
  • It is not the same - I am trying to match parentTags to Tags and the group. The other link is a straight up 'groupBy' – Jose the hose Apr 01 '15 at 10:51
  • You have to create a json structure for your needs. It is best way to do it. – hurricane Apr 01 '15 at 10:55

1 Answers1

2

Please see demo below

var app = angular.module('app', []);

app.controller('homeCtrl', function($scope) {

  $scope.products = [{
    "code": "Fruit",
    "tag": 1
  }, {
    "code": "Apple",
    "tag": 2,
    "parentTag": 1
  }, {
    "code": "Vegetable",
    "tag": 3
  }, {
    "code": "Meat",
    "tag": 4
  }, {
    "code": "Banana",
    "tag": 5,
    "parentTag": 1
  }, {
    "code": "Carrot",
    "tag": 6,
    "parentTag": 3
  }, {
    "code": "Chicken",
    "tag": 7,
    "parentTag": 4
  }];


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body>
  <div ng-app="app">
    <div ng-controller="homeCtrl">
      <div ng-repeat="product in products | filter :{parentTag:'!'}">
        <h3>{{product.code}}</h3>
        <div ng-repeat="subproduct in products | filter :{parentTag:product.tag}">
          <span>{{subproduct.code}}</span>
          <span>{{subproduct.tag}}</span>
          <span>{{subproduct.parentTag}}</span>
        </div>


      </div>
    </div>
</body>
sylwester
  • 16,498
  • 1
  • 25
  • 33