Nayeem Mansoori
Nayeem Mansoori

Reputation: 831

Filter data on the basis of alphabetical word with letter in angular js

I have used AngularJS and I want to filter data on the basis of alphabetical word in AngularJS.

Can any one please help me?

This is the code which I used:

<script src="~/Scripts/angular.min.js"></script>
<script type="text/javascript">

var app = angular.module('Napp', []);
app.controller('GetAlphabetical', function ($scope) {
        $scope.names = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

        $scope.Customer = [
                            { Name: 'Nayeem', City: 'Indore' },
                            { Name: 'Sanjay', City: 'Bhopal' },
                            { Name: 'Aditya', City: 'Jhansi' }];
    });
</script>

<div data-ng-app="Napp" ng-controller="GetAlphabetical">

<input type="text" ng-model="myfilters" /> |
    <table>
        <tr>
            <td data-ng-repeat="h in names">&nbsp;
                <span ng-click="myfilters = {cust.Name = 'Nayeem' }">{{h}}</span>|
            </td>
        </tr>
    </table>
    <br />
    <ul>
        <li ng-repeat="cust in Customer | filter: myfilters">{{cust.Name + " " + cust.City}}</li>
    </ul>
</div>

Upvotes: 1

Views: 1493

Answers (1)

Starfish
Starfish

Reputation: 3574

ng-repeat="cust in Customer | filter: myfilters | orderBy: 'Name'"

This would sort the list in ascending order. If you want to sort the list in descending order you'll have to use '-Name'

EDIT (Fiddle + Filterfix):

var app = angular.module('Napp', []);
app.controller('GetAlphabetical', function($scope) {
  $scope.filt = 'All';
  $scope.setFilter = function(letter) {
    $scope.filt = letter;
  };

  $scope.names = ['All', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

  $scope.startsWith = function(customer) {
    var lowerStr = (customer.Name + "").toLowerCase();
    var letter = $scope.filt;
    if (letter === 'All') return true;
    return lowerStr.indexOf(letter.toLowerCase()) === 0;
  }

  $scope.Customer = [{
    ID: 1,
    Name: 'Nayeem',
    City: 'Indore'
  }, {
    ID: 2,
    Name: 'Sanjay',
    City: 'Bhopal'
  }, {
    ID: 3,
    Name: 'Aditya',
    City: 'Jhansi'
  }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app="Napp" ng-controller="GetAlphabetical as ga">
  <table>
    <tr>
      <td ng-repeat="letter in names">&nbsp;<span ng-click="setFilter(letter)">{{letter}}</span>|</td>
    </tr>
  </table>
  <br />
  <ul>
    <li ng-repeat="cust in Customer | filter:startsWith | orderBy: 'Name'">{{cust.Name}}</li>
  </ul>
</div>

Upvotes: 2

Related Questions