AngularJS ng-repeat orderBy錯誤地命令數字

[英]AngularJS ng-repeat orderBy orders numbers incorrectly


I'm having an issue with using the ng-repeat orderBy when there are numbers in text.

當文本中有數字時,我遇到使用ng-repeat orderBy的問題。

Sample Data:

[
   {booth: 'p1'},
   {booth: 'p2'},
   {booth: 'p3'},
   {booth: 'p4/5'},
   {booth: 'p6/7'},
   {booth: 'p8'},
   {booth: 'p9'},
   {booth: 'p10'},
   {booth: 'p11'},
   {booth: 'p12'},
   {booth: 'p13'}
]

When using the ng-repeat with the orderBy: 'booth' is list it out as such: p1, p10, p11, p13, p2, ect

當使用ng-repeat和orderBy時:'booth'列出如下:p1,p10,p11,p13,p2,ect

I understand this is expected behavior but does anyone know how I can get it to list out the booths in the order that I expect?

我理解這是預期的行為,但有誰知道如何讓我按照我期望的順序列出展位?

Which would be: p1, p2, p3, p4/5, ect

這將是:p1,p2,p3,p4 / 5等

I have also tried seeing if the issue was because the numbers weren't integers but returned the same issue.

我也試過看問題是不是因為數字不是整數而是返回了同樣的問題。

Thank you in advance for any help.

預先感謝您的任何幫助。

1 个解决方案

#1


12  

JavaScript's built-in string comparison won't work for your purposes. I think what is needed is a natural sort, to sort the strings the way a human would. I found a solid implementation here from the blog here. It is pretty comprehensive and fairly complex so I won't try to explain the source code here (check the blog for explanation).

JavaScript的內置字符串比較不適用於您的目的。我認為所需要的是一種自然的排序,按照人類的方式對字符串進行排序。我從博客這里找到了一個可靠的實現。它非常全面且相當復雜,所以我不會在這里解釋源代碼(請查看博客的解釋)。

You can then create a custom filter for the natural sort and use in your HTML like:

然后,您可以為自然排序創建自定義過濾器,並在HTML中使用,如:

HTML

<div ng-app="myApp">
    <div ng-controller="ctrlMain">
        <div ng-repeat="item in data | naturalSort">{{item.booth}}</div>
    </div>
</div>

Javascript - I've left out the implementation of the sort since it's long and not created by me, but check the demo at the bottom to see it in action.

Javascript - 我已經省略了排序的實現,因為它很長並且不是由我創建的,但請查看底部的演示以查看它的實際效果。

app.filter('naturalSort',function(){
    function naturalSort (a, b) {
        // Please see the demo for this code, it is somewhat long.
    }
    return function(arrInput) {
        var arr = arrInput.sort(function(a, b) {
            return naturalSort(a.booth,b.booth);
        });
        return arr;
    }
});

The sort implementation in the demo below covers various possibilities (date, hex values, whitespace) that could be used in many situations (though it may be a little overkill for your example).

下面演示中的排序實現涵蓋了可以在許多情況下使用的各種可能性(日期,十六進制值,空白)(盡管對於您的示例可能有點過分)。

Here is a demo

這是一個演示


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/06/17/7206b4ac357ef432b69151e801ff9e3c.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com