broc
broc

Reputation: 61

Order by numbers in Angular

I'm trying to sort json file. I have problem with numbers with a comma.

Results after sort:

0,77
10,03
18,79
2,89
24,08

Probably numbers are converted to strings.

ng-repeat="cpu in cpus | orderBy:sort:reverse"

$scope.sort = 'x';
$scope.reverse = true;
$scope.order = function(sort) {
$scope.reverse = ($scope.sort === sort) ? !$scope.reverse : false;
$scope.sort = sort;

Question: Any idea how to fix it?

Upvotes: 2

Views: 251

Answers (1)

sbedulin
sbedulin

Reputation: 4342

You may provide custom value function which converts strings back to numbers

<!DOCTYPE html>
<html ng-app="app">
  <head>
    <script data-require="[email protected]" data-semver="1.4.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script>
      angular
        .module('app', [])
        .controller('appCtrl', function($scope, $http) {
          $scope.cpus = [
              { name: 'cpu1', power: '0,77' },
              { name: 'cpu2', power: '10,03' },
              { name: 'cpu3', power: '18,79' },
              { name: 'cpu4', power: '2,89' },
              { name: 'cpu5', power: '24,08' }
          ];

          $scope.myValueFunction = function(cpu) {
              return Number( cpu.power.replace(',', '.') );
          };

          $scope.value = function(cpu) {
              return '(' + cpu.name + '; ' + cpu.power + ')';
          };
        });
    </script>
  </head>

  <body ng-controller="appCtrl">
    <ul ng-repeat="cpu in cpus | orderBy:myValueFunction">
      <li>{{cpu.name}} {{value(cpu)}}</li>
    </ul>
  </body>
</html>

Plunker

Upvotes: 1

Related Questions