How to sort Polish characters with the sortBy filter in angularjs?

471 views Asked by At

I have a problem. The 'sortBy' in Angularjs 1 method does not sort alphabetically Polish characters. It should be sorted: Alfred, Ahris, Bert, Chora, Dora. In fact, there are: Alfred, Berta, Dora, Ąhris, Ćora.

index.html

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link data-require="bootstrap-css@*" data-semver="3.1.1" rel="stylesheet"
          href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
    <script data-require="[email protected]" data-semver="1.2.14"
            src="http://code.angularjs.org/1.2.14/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script type="text/javascript" src="script.js"></script>
  </head>

  <body ng-controller="MainCtrl">

    <div>
      Order By:
      <select ng-model="sortorder">
          <option selected>Name</option>
          <option value="Age">Age</option>
      </select>
      <br>
      <table style="width:300px">
          <tr>
            <td>Name</td>
            <td>Age</td>      
          </tr>
          <tr ng-repeat="contact in contacts | orderBy:sortorder">
            <td>{{contact.Name}}</td>     
            <td>{{contact.Age}}</td>
          </tr>
      </table>              
      </div>  

  </body>

</html>

script.js

var app = angular.module('app', []);

app.controller('MainCtrl', ['$scope', function ($scope) {
  $scope.sortorder = 'Name';
  $scope.contacts = [
    {Name: 'Alfred', Age: 37},
    {Name: 'Berta', Age: 65},
    {Name: 'Ąhris', Age: 25},
    {Name: 'Dora', Age: 12},
    {Name: 'Ćora', Age: 12}
    ]
}]);

Example: http://plnkr.co/edit/ZwtGPSEvlFul6cNtn7hd?p=preview

1

There are 1 answers

0
miqh On BEST ANSWER

The default comparator for orderBy isn't locale-sensitive as you've discovered. You can get your desired order by passing in a custom comparator. The latter has been available since 1.5.7. I noticed you've tagged the version with version 1.6 but in your Plunker you reference 1.2.

The comparator occupies the third argument of orderBy:

orderBy:<expression>:<reverse>:<comparator>

For example:

$scope.comparator = function (a, b) {
    if (a.type === 'string' && b.type === 'string') {
        return a.value.localeCompare(b.value);
    }
    return a.value - b.value;
};

If you add any extra properties to $scope.contacts that you need to sort by, make sure to extend the comparator to handle the data types.

Here's a forked version of your Plunker demonstrating this.