【问题标题】:AngularJS how to use orderby with currency values?AngularJS如何使用带有货币值的orderby?
【发布时间】:2015-01-03 15:24:00
【问题描述】:

我正在尝试在我的产品页面上进行排序。我很难订购价格,现在它订购它们,因为它们是字符串。降序结果如下:

$7.00
$6.00
$55.00
$42.00 

我想这样显示:

$55.00
$42.00
$7.00
$6.00

所以我没有完全采用数字格式(它们以 $ 开头)。

   // get sort options
            var predicate, reverse;
            switch ($scope.filter.sort) {
    case 'priceAsc':
                    predicate = 'sizes[0].price';
                    reverse = true;
                    break;
                case 'priceDesc':
                    predicate = 'sizes[0].price';
                    reverse = false;
                    break;
    }

     // order data object
            var orderBy = $filter('orderBy');
            $scope.products = orderBy($scope.products, '-' + predicate, reverse);

产品数组有大小数组,每个大小都有自己的价格。我该如何解决它,有什么建议吗?任何帮助将不胜感激。

【问题讨论】:

  • 我认为,最好的方法是从服务器获取未格式化的价格(作为数字)并在客户端使用角度 currency 过滤器对其进行格式化。有可能吗?

标签: angularjs sorting angularjs-filter


【解决方案1】:

您可以尝试编写自己的过滤 orderby 函数

$scope.priceValue = function(price) {
   return parseFloat(str.replace('$', price));
};

ng-repeat="price in prices | orderBy:priceValue"

【讨论】:

    【解决方案2】:

    首先:从价格中删除 $:

    for (var i = 0; i < product.sizes.length; i++) {
        product.sizes[i].price.replace('?', '');
    }
    

    现在按大小排序您的 ng-repeat,并使用货币过滤器显示。

    <div ng-repeat="size in product.sizes | orderBy: size.price">Price: {{size.price | 'currency'}}</div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 2015-08-04
      • 2010-11-12
      • 2014-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多