angularjs Ascending Distance和Descending Distance工作不正常?

时间:2015-08-09 20:55:59

标签: javascript angularjs

http://jsfiddle.net/U3pVM/17782/ 我在这里附上代码用于Ascending place。下降的地方工作正常。当我进行升序距离时,降序距离无法正常工作。

我附上了我的jsfiddle:

angular.module('myApp', [])
    .controller("myCntrl", function ($scope, $filter) {
    
    var data = [{
            Place: "Place1",
            Distance:"4.97 km",
        }, {
            Place: "Place2",
            Distance:"2.97 km",
            
        }, {
            Place: "Place3",
            Distance:"3.23 km",
        }, {
           Place: "Place4",
            Distance:"14.85 km",
        }, {
            Place: "Place5",
            Distance:"7.04 km",
        }, {
            Place: "Place6",
            Distance:"12.62 km",
        }
    ];
    
    $scope.tests = data;
    var orderBy = $filter('orderBy');
    $scope.order = function (predicate, reverse)
    {
        $scope.tests = orderBy($scope.tests, predicate, reverse);
    };
    
    console.log(data);
});
<div ng-app="myApp">
    <div ng-controller="myCntrl">
    
        <label>List Of students</label>
        <div class="list"  ng-click="popover.hide()">
            <a class="item" ng-click="reverse=false;order('Name', false)" target="_blank">
             ▲ A-Z Name 
            </a>
            <a class="item"  ng-click="order('-Name',false)" target="_blank">
            ▼ Z-A Name 
            </a>
            <a class="item"  ng-click="reverse=false;order('Distance', false)" target="_blank">
            ▲ Ascending Distance 
            </a>
            <a class="item" ng-click="order('-Distance',false)" target="_blank">
              ▼ Descending   Distance 
            </a>
      
          </div>
        <br>
        <input ng-model="search" type="text" placeholder="search" />
        <br>
        <br>
        
        <div ng-repeat="test in tests | filter:search" >{{test.Place}}
            <br>{{test.Distance}}
            <br>
            <br>
            <br>
            <br>
        </div>
    </div>
    <br>
    <br>
</div>

1 个答案:

答案 0 :(得分:1)

删除距离值中的引号。 OrderBy正在排序&#39;距离&#39;用字符串表示(输出似乎只按第一个数字排序)而不是浮点数。

var data = [
  { Place: "Place1", Distance: 4.97 },
  { Place: "Place2", Distance: 2.97 }, 
  { Place: "Place3", Distance: 3.23 },
  { Place: "Place4", Distance: 14.85 },
  { Place: "Place5", Distance: 7.04 },
  { Place: "Place6", Distance: 12.62 }
];

编辑:如果您从其他来源接收数据,则必须将这些值从字符串转换为浮动。

angular.forEach($scope.tests, function (test) {
  test.Distance = parseFloat(test.Distance);
});

可能重复:AngularJS orderby integer field not working properly