Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Incorrect order in ng-repeat

Tags:

angularjs

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

like image 280
qais Avatar asked Nov 02 '22 21:11

qais


1 Answers

Your chap_no property is a string so its ordered as a string.

You can create a custom filter like:

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;
    }
})

So then in your html you can use the filter like this:

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

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

like image 95
CD.. Avatar answered Nov 11 '22 13:11

CD..