5

I have chaps defined in my controller like this:

  $scope.chaps =  [{"id":"1","chap_no":"1","name":"chap 1"},
                  {"id":"2","chap_no":"2","name":"chap 2"},
                  ...
                  {"id":"14","chap_no":"14","name":"chap 14"},
                  {"id":"15","chap_no":"15","name":"chap 15"}];

and in the view, I have:

<li ng-repeat="ch in chaps | orderBy:'chap_no'">{{ch.name}}</li>

but I'm getting the wrong order (10 after 1, 20 after 2, and so on)

chap 1, chap 10, chap 11, chap 12, chap 13, chap 14, chap 15, chap 2, chap 3, ...

Here's the plunkr: http://plnkr.co/edit/Pc84ooB6dp2zoHXeawYn?p=preview

Can anyone tell me what I'm doing wrong here

4

1 回答 1

2

您的chap_no属性是一个字符串,因此它作为一个字符串排序。

您可以创建一个自定义filter,如:

app.filter('customSort',function(){
    function sort (a, b) {
        if (a > b) { return 1; }
        if (a < b) { return -1; }

        return 0;
    }

    return function(arrInput, prop) {
        var arr = arrInput.sort(function(a, b) {
            return sort(+a[prop], +b[prop]);
        });
        return arr;
    }
})

因此,在您的 html 中,您可以像这样使用过滤器:

<li ng-repeat="ch in chaps | customSort:'chap_no'" >{{ch.name}}</li>

示例:http ://plnkr.co/edit/UWvinthK9r0zgRbHMCGd?p=preview

于 2013-05-30T17:53:50.927 回答