Sikander Sikander - 7 months ago 36
Javascript Question

Filter the list with letter in angular js

I have a list displayed in table where I need to filter the result with first letter of name,above the list I have a letter A B C D and so on.
After click the letter list will be filter by its first name

For ex: list details are

Apple Boy Bridge

after click
will be displayed


Instead of fruit, I had to filter names of countries to display their sales representatives:

'use strict';

.filter('firstLetter', function () {
    return function (input, letter) {
        input = input || [];
        var out = [];
        input.forEach(function (item) {
            //console.log("current item is", item, item.charAt(0));
            if (item.charAt(0).toLowerCase() == letter) {
        return out;

A quick way to generate an array with letters of the alphabet:

$scope.alphabet = "abcdefghijklmnopqrstuvwxyz".split("");

and the view, which also sets a different background colour if the letter is active:

<button type="button" class="btn-alphabet btn btn-default" ng-repeat="letter in alphabet" ng-click="setActiveLetter(letter)" ng-class="{'btn-primary': letter==activeLetter}">{{letter}}</button>

I filtered elements of the array of countries like this:

<ul class="list-group countries-salesreps" >
    <li class="list-group-item" ng-repeat="country in filteredCountriesArray = (countriesArray | firstLetter:activeLetter)" ng-click="showSalesRep(country)" ng-class="{'btn-primary': country==currentCountry}">{{country}}</li>

You can check if there are elements in the filtered list using .length:

<div class="alert alert-warning" ng-hide="filteredCountriesArray.length">No available countries starting with <em>{{activeLetter}}</em></div>