Angular orderBy字符串(数字范围)为Number

时间:2015-05-13 22:23:46

标签: javascript angularjs

我有一组像这样的对象:

$scope.businesses = [ 
  { name: 'BusinessName', cost: '12' },
  { name: 'AnotherBusinessName', cost: '79-122' },
  { name: 'LastBusinessName', cost: '120' }
];

我正在尝试使用orderBy按成本排序,如下所示:

<ul>
    ...
    <li ng-click="sortProps('-cost')">Price: High to Low</li>
</ul>

sortProps被声明如下:

$scope.sortProps = function(prop) {
    $scope.sortBy = prop;
    $scope.reverse = false;
};

出于某种原因,当按'-cost'(或其相反)排序时,我总是得到 12> 120> 79-122显示。按'-cost'排序时,我希望看到120&gt; 79-122&gt; 12.我知道问题出在哪里(成本是对象中的一个字符串),但我不完全确定如何将其作为Number投射,同时仍显示全价格范围,例如79- 122。

我在构建parseFloat(business.cost)时尝试$scope.businesses,但这会在-之后删除任何内容,这是预期的。但奇怪的是,这仍然给我12>的排序顺序。 120> 79(从79-122解析)。

我也尝试过类似的东西:

$scope.sortProps = function(prop) { 
  if (prop === 'cost' || prop === '-cost') {
    angular.forEach($scope.businesses, function(business) { 
      business.cost = parseFloat(business.cost);
    });
  }
  // ...
};

尝试按成本排序时仅转换为数字。我输了,有什么建议吗?

1 个答案:

答案 0 :(得分:1)

此解决方案包含两部分:

  1. &#34;标记&#34;带有&#34; costNum&#34;的数据财产(这是一个数字)&#39;
  2. 通常在新属性上使用orderBy过滤器。
  3. 这里是plunker

    的JavaScript

    (function(){
      'use strict';
       angular.module('app', []).controller('TestCtrl', Controller);
       function Controller($scope){
         $scope.orderByProp = null;
         $scope.sort = function() {
           $scope.orderByProp = 'costNum';
         };
         $scope.reverseSort = function() {
           $scope.orderByProp = $scope.orderByProp === 'costNum' ? '-costNum' : 'costNum';
         };
         $scope.removeSort = function() {
           $scope.orderByProp = null;
         };
         $scope.businesses = [ 
          {name: 'Business Zero', cost: '345'},
          {name: 'Business One', cost: '12'},
          {name: 'Another Two', cost: '79-122'},
          {name: 'Business Three', cost: '120'}, 
          {name: 'Business Four', cost: '20'}, 
          {name: 'Business Five', cost: '80'}
        ];
        function markupBiz() {
          for(var i = 0, len = $scope.businesses.length; i < len; i++) {
            $scope.businesses[i].costNum = parseFloat($scope.businesses[i].cost);
          }
        }
        markupBiz();
      }
    })();
    

    HTML

    <div ng-controller="TestCtrl">
      <button ng-click="sort()">Sort</button>
      <button ng-click="reverseSort()">Reverse sort</button>
      <button ng-click="removeSort()">Remove sort</button>
      <ul>
        <li ng-repeat="business in businesses | orderBy:orderByProp">
          {{business.name}}: ${{business.cost}}
        </li>
      </ul>
    </div>