Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS and orderby in ng-repeat with special characters

I am having trouble ordering strings containing characters that are not in the English alphabet ( š,č,ž,..)

Here is the fiddle: http://fiddle.jshell.net/vhhgh/

The letters are from the Slovenian alphabet.

like image 618
Cubeman Avatar asked Nov 29 '13 19:11

Cubeman


2 Answers

It's been a while, but I found other solution: fiddle

HTML:

<div ng-app='test'>
  <h2>Users</h2>
  <div ng-controller="UsersCtrl">
    <ul>
      <li ng-repeat="user in users | localeCompareString">
        {{user.surname}} {{user.name}}
      </li>
    </ul>
  </div>
</div>

JS:

(function(angular) {
  'use strict';
  var test=angular.module('test',[])
.controller('UsersCtrl', ['$scope',function($scope) {
  $scope.users = [
    {name:'Ben', surname:'Živkovič'},
    {name:'Ken', surname:'AlGore'},
    {name:'Erica', surname:'Červ'},
    {name:'Jane', surname:'Šinigoj'},
    {name:'Kevin', surname:'Sort'},
    {name:'Roger', surname:'Willson'},
    {name:'Kim', surname:'Zorro'}
];
}]).filter('localeCompareString',function(){
    return function (items) {
         //window.console.log(items);
        items.sort(function (a, b) {
            return a.surname.localeCompare(b.surname);
        });
        return items;
      }; 
});

})(window.angular);        
like image 180
Dariusz81 Avatar answered Oct 03 '22 23:10

Dariusz81


Ordering arrays of strings with "foreign" letters isn't as easy to do as you might think. Actally, it can be a right pain in the ... to get right. The problem boils down to the fact that the Unicode charset contains (pretty much) all charactrers in existance, so a universal lexicographical sorting isn't possible since different countries all have different ways they expect the sorting to be handled.

To get around this, I've found TCollator, a small library aiming at fixing that issue, very useful.

like image 30
Tobias Roland Avatar answered Oct 03 '22 23:10

Tobias Roland