I have array of categories that has this structure:
{
name: 'something',
main_category: 'A'
}
So each category has it's main category. I would like to display all categories in html like so:
<h1>A</h1>
<ul>
<li>list of categories that has main category A</li>
</ul>
<h1>B</h1>
<ul>
<li>list of categories that has main category B</li>
</ul>
how should I achieve it? The only way I found was doing something like this:
<h1>A</h1>
<ul>
<li ng-repeat="category in categories" ng-if="category.main_category == 'A'">..</li>
</ul>
<h1>B</h1>
<ul>
<li ng-repeat="category in categories" ng-if="category.main_category == 'B'">..</li>
</ul>
It works but I don't think it's a good idea.
You should use groupBy filter provided by https://github.com/a8m/angular-filter, and do something like this
var myApp = angular.module('mcApp', ['angular.filter']);
myApp.controller('mcController', ['$scope', function ($scope) {
console.log('asadsds');
$scope.myArray = [
{
name: 'something 1',
main_category: 'B'
},
{
name: 'something 2',
main_category: 'A'
},
{
name: 'something 3',
main_category: 'A'
},
{
name: 'something 4',
main_category: 'B'
},
{
name: 'something 5',
main_category: 'B'
}
];
}]);
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example7-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.5/angular-filter.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="mcApp" ng-controller="mcController">
<p>{{name}}</p>
<div ng-repeat="object in myArray | orderBy: 'main_category'| groupBy:'main_category' |toArray: true" >
<h1>{{object.$key}}</h1>
<ul>
<li ng-repeat="value in object">
{{value.name}}
</li>
</ul>
</div>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With