I would like to sort a table by 'numbers'. Those 'numbers' represent version-numbers of applications or dependencies of those. They look like "2.11.7" or "6.41.6". Because of that, i can't convert them into numbers. But when handling them like a String, angulars orderBy sorts them not properly. To be more specific:
will end up in (DESC)
or (ASC)
Now i got stuck. Any idea how to solve that?
Sorting can be accomplished by plain javascript. Here is an example adapted from the accepted answer for sorting of versions
As far as AngularJs is concerned, the order by also allows for a custom comparator to be provided. Here they have an example with a custom comparator to sort the values. All it requires is to use a function similar to the one above (or your own logic) to provide for a custom comparator. The flag for sorting direction can be provided via the expression itself by passing true/false.
Here is a plunker edited from their own example to provide for your values. Feel free to play around. This example will run properly in the Plunker environment. The code is listed here for documentation
(function(angular) {
'use strict';
angular.module('orderByExample4', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.friends = [
{ name: 'John', favoriteLetter: '2.11.5' },
{ name: 'Mary', favoriteLetter: '2.11.5' },
{ name: 'Mike', favoriteLetter: '2.11.7' },
{ name: 'Adam', favoriteLetter: '2.11.7' },
{ name: 'Julie', favoriteLetter: '2.11.5' }
];
function pad(version) {
var paddingString = "0000000000";
return version
.split('.')
.map(function(majorMinorVersion) {
var index = paddingString.length - majorMinorVersion.length;
return paddingString.substr(0, index) + majorMinorVersion;
})
.join('.');
}
$scope.localeSensitiveComparator = function(v1, v2) {
// If we don't get strings, just compare by index
if (v1.type !== 'string' || v2.type !== 'string') {
return (v1.index < v2.index) ? -1 : 1;
}
var a = pad(v1.value);
var b = pad(v2.value);
return a.localeCompare(b);
};
}]);
})(window.angular);