Grouping objects with AngularJS -
i have bunch of objects in array , trying figure out how group them within angular repeater. example want group fruit items parenttag key tag key of parent. fruit has tag of 1 , apple has parent tag value of 1, meaning apple grouped fruit.
so using 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 trying group objects this...
fruit
- apple
- banana
vegetable
- carrot
meat
- chicken
so far have repeater displays 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 don't know how use groupby in case. ideas?
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>
Comments
Post a Comment