AngularJS可排序订单定价问题

时间:2017-11-14 17:10:48

标签: angularjs jquery-ui-sortable

我在订购格式化为货币的价格时遇到问题。



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>
&#13;
&#13;
&#13;

问题订单:$9.5 > $10
有没有办法纠正排序?

1 个答案:

答案 0 :(得分:0)

是的,请检查这个小提琴:http://jsfiddle.net/2u3wn91z/1/。 您想要比较number而不是string,因此您需要将currency(作为price的第一个字母)分开,然后从currency中删除price {1}}):

  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;

如果您将价格与货币分开,则可以单独显示:

<td>{{purchase.currency}}{{purchase.price}}</td>