Jose the hose
Jose the hose

Reputation: 1895

Grouping objects with AngularJS

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

Vegetable

Meat

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?

Upvotes: 0

Views: 757

Answers (1)

sylwester
sylwester

Reputation: 16498

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>

Upvotes: 2

Related Questions