Angularjs orderBy on float

时间:2016-01-26 06:20:20

标签: javascript angularjs sorting angularjs-orderby

JS:

(function(angular) {
  'use strict';
angular.module('orderByExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.friends =
        [{name:'John', phone:'2.5-3.3-7.5', age:10},
         {name:'Mary', phone:'10.5-3.7-9.1', age:19},
         {name:'Mike', phone:'10-21-30', age:21},
         {name:'Adam', phone:'11.1-5-10', age:35},
         {name:'Robert', phone:'1-3-7', age:27},
         {name:'Julie', phone:'9-15-20', age:29}];
    $scope.predicate = 'phone';
    $scope.reverse = true;
    $scope.order = function(predicate) {
      $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
      $scope.predicate = predicate;
    };
  }]);
})(window.angular);

HTML:

<table class="friend">
    <tr>        
     <th>
         <button ng-click="order('phone')">Phone Number</button>
         <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
     </th>         
    </tr>
    <tr ng-repeat="friend in friends | orderBy:predicate">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.age}}</td>
    </tr>
  </table>

结果:

  • 1-3-7
  • 9-15-20
  • 30年10月21日
  • 11.1-5-10
  • 2.5-3.3-7.5
  • 10.5-3.7-9.1

但我想要这个结果:

  • 1-3-7
  • 2.5-3.3-7.5
  • 9-15-20
  • 30年10月21日
  • 10.5-3.7-9.1
  • 11.1-5-10

我想仅根据phoneNumber进行排序。 http://plnkr.co/edit/JI8bJ54C3ARurK5w1hFU?p=preview

1 个答案:

答案 0 :(得分:1)

在您的示例中,您已经映射了phoneNumber并对其进行了排序:

.map(function(friend) {
  // this removes all non-digits
  friend.phoneNumber = Number(friend.phone.replace(/[^\d]/g, ''));
  return friend;
})

如果您希望将phoneNumber保持为map(),并使用parseFloat()

.map(function(friend) {
  // this will create a float from the first part until dash of friend.phone
  friend.phoneNumber = parseFloat(friend.phone);
  return friend;
})

Plunkr