Create list sorted by letter with AngularJS

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 started blocks.

Blocks ordered like this:

A

Academy

Animals

B

Bars

Beauty and Aesthetics

    
asked by anonymous 26.07.2016 / 05:01

1 answer

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 Run Code Snippet 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><divng-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>
    
26.07.2016 / 05:53