0

我的自定义排序方法有问题。我有一个 json 结构,其中整数值作为字符串传递。在排序时,我需要根据整数值对列表进行排序,但它被排序为字符串值。

我为此创建了一个 JsFiddle:

http://jsfiddle.net/ayan_2587/vjF2D/14/

角码如下:-

var app = angular.module('myModule', []);

app.controller('ContactListCtrl', function ($scope, $timeout, $filter) {

var sortingOrder = 'price';
$scope.sortingOrder = sortingOrder;

$scope.sortorder = '-sort';
$scope.contacts = [{
    "name": "Richard",
    "surname": "Stallman",
    "price": "7200"
}, {
    "name": "Donald",
    "surname": "Knuth",
    "price": "34565"
}, {
    "name": "Linus",
    "surname": "Torvalds",
    "price": "23454"
}];

$scope.setLoading = function (loading) {
    $scope.isLoading = loading;
}


$scope.layoutDone = function (value) {
    console.log(value);
    $scope.setLoading(true);

     $timeout(function() { 
    // take care of the sorting order
    if ($scope.sortingOrder !== '') {

        if(value == 'sort'){
        $scope.contacts = $filter('orderBy')($scope.contacts, $scope.sortingOrder, false);
        }
        else if(value == '-sort'){
        $scope.contacts = $filter('orderBy')($scope.contacts, $scope.sortingOrder, true);
        }
    }
            $scope.setLoading(false);
        }, 1000);

}

$scope.loadFeed = function(url) {       
  $scope.setLoading(true);          
}

$scope.loadFeed();
});



app.directive('repeatDone', function() {
    return function(scope, element, attrs) {
        if (scope.$last) { // all are rendered
            scope.$eval(attrs.repeatDone);
        }
    }
})

请帮帮我!!!

4

1 回答 1

3

因为你在 JS 中排序,你总是可以使用Array.sort()- 至少在现代浏览器上 - 传递一个排序函数,如:

function sortAsc(a,b) {
    a = parseInt(a.price);
    b = parseInt(b.price);
    return a > b ? 1 : (a === b ? 0 : -1);
}

然后执行如下排序:

if(value == 'sort'){
    $scope.contacts.sort(sortAsc);
}

见分叉小提琴: http: //jsfiddle.net/sRruf/(初始状态未排序)

排序属性(这里price)可以通过一些额外的工作来参数化。


这是使用orderBy过滤器和自定义谓词的版本:http: //jsfiddle.net/sRruf/1/

于 2013-10-15T07:09:53.430 回答