1
How can I create a list sorted by the initial letter using Angularjs? I have several categories in a json file and would like to list them by blocks with initials.
Blocks ordered like this:
To
Academy
Animals
B
Bars
Beauty and Aesthetics
1
How can I create a list sorted by the initial letter using Angularjs? I have several categories in a json file and would like to list them by blocks with initials.
Blocks ordered like this:
To
Academy
Animals
B
Bars
Beauty and Aesthetics
2
A simple grouping function in vanilla JS can solve your problem.
In the following implementation example an object (grp
) is created, containing the following structure:
{
"A": [
"Academia",
"Animais"
],
"B": [
"Bares",
"Beleza e Estética"
]
}
Click on Execute Snippet of Code to see the result:
(function () {
var app = angular.module('store', []);
app.controller('sampleController', function ($scope) {
var json = ["Academia","Animais","Bares","Beleza e Estética"];
var grp = {}; // Inicializando o objeto.
var result = json.forEach(function(item) {
var chr = item.charAt(0); // Obtendo o primeiro caracter
if (!grp.hasOwnProperty(chr)) grp[chr] = []; // Se não existe grupo para
// o caracter, crie e inicialize
grp[chr].push(item); // Adicione item ao grupo
});
$scope.grp = grp;
});
})();
<html ng-app="store">
<body>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<div ng-controller="sampleController">
<div ng-repeat='(k,v) in grp'>
<h2>{{k}}</h2>
<div ng-repeat="i in v">
<h4>{{i}}</h4>
</div>
</div>
</div>
</body>
</html>
Browser other questions tagged angularjs
You are not signed in. Login or sign up in order to post.
Thank you very much! I even managed to do something simpler here, only when I tried to move to Angular it didn’t work out so well, I’m still studying and with a little difficulty ^^
– Altemberg Andrade
@Altembergandrade It’s always a pleasure to help, I’m glad it worked out for you. =)
– OnoSendai
one of the categories is Audio and ended up creating a new block. How do I include it in the block A?
– Altemberg Andrade