Home AngularJS Sortable order pricing issue
Reply: 1

AngularJS Sortable order pricing issue

Lam Nguyen
1#
Lam Nguyen Published in 2017-11-14 17:10:48Z

I'm facing an issue when ordering prices formatted as currency.

var myApp = angular.module("myApp", []);

myApp.factory("Purchases", function() {
  var Purchases = {};

  Purchases.data = [{
      date: "10/05/2012",
      text: "1 Lorem ipsum dolor sit amet ipsum dolor",
      price: "£90",
      availability: "1 Available until 10th Dec 2013"
    },
    {
      date: "24/05/2012",
      text: "2 Lorem ipsum dolor sit amet ipsum dolor",
      price: "£9.5",
      availability: "2 Available until 10th Dec 2013"
    },
    {
      date: "20/05/2012",
      text: "3 Lorem ipsum dolor sit amet ipsum dolor",
      price: "£10",
      availability: "3 Available until 10th Dec 2013"
    }
  ];
  return Purchases;
});

function PurchasesCtrl($scope, Purchases) {
  $scope.purchases = Purchases;
  $scope.sort = {
    column: '',
    descending: false
  };
  $scope.changeSorting = function(column) {

    var sort = $scope.sort;

    if (sort.column == column) {
      sort.descending = !sort.descending;
    } else {
      sort.column = column;
      sort.descending = false;
    }
  };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="PurchasesCtrl">
    <h2>Purchases:</h2>
    <table cellspacing="0">
      <tr class="first">
        <th class="first" ng-click="changeSorting('date')">Date</th>
        <th ng-click="changeSorting('text')">Description</th>
        <th ng-click="changeSorting('price')">Amount</th>
        <th ng-click="changeSorting('availability')">Status</th>
      </tr>
      <tr ng-repeat="purchase in purchases.data|orderBy:sort.column:sort.descending">
        <td class="first">{{purchase.date}}</td>
        <td>{{purchase.text}}</td>
        <td>{{purchase.price}}</td>
        <td>{{purchase.availability}}</td>
      </tr>
    </table>
  </div>
</div>

The issue order: $9.5 > $10
Is there any way to correct the ordering?

Radek Anuszewski
2#
Radek Anuszewski Reply to 2017-11-14 17:28:49Z

Yes, check this fiddle: http://jsfiddle.net/2u3wn91z/1/ . You want to compare numbers, not strings, so you need to separate currency (as first letter of price) and then remove currency from price):

  Purchases.data = Purchases.data.map(function (purchase) {
    purchase.currency = purchase.price.charAt(0);
    purchase.price = Number(purchase.price.substr(1));
    return purchase;
  });
   $scope.purchases = Purchases;

When you have price separated from currency, you can display it separately:

<td>{{purchase.currency}}{{purchase.price}}</td>
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.320734 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO