Angularjs orderBy on float

Angularjs orderBy on float

本文关键字:float on orderBy Angularjs      更新时间:2023-09-26

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
  • 10-21-30
  • 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
  • 10-21-30
  • 10.5-3.7-9.1
  • 11.1-5-10

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

在您的示例中,您已经映射了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;
})

普伦克