Angularjs按数字和字母过滤排序

时间:2017-10-05 03:06:23

标签: angularjs angularjs-filter

我想按'displayName'排序。有时displayName包含所有数字或字母。 $ filter('orderBy')适用于字母表。但数字是这样渲染的。

1,13,2,23,3,43. 

如何过滤数字和字母?

    vm.temp=[{id:15, displayName:'ff'},
    {id:2, displayName:'f'},
    {id:10, displayName:'cc'},
    {id:3, displayName:'aa'},
    {id:5, displayName:'h'},
    {id:8, displayName:'y'}]
OR
   vm.temp=[{id:15, displayName:'3'},
    {id:2, displayName:'2'},
    {id:3, displayName:'43'},
    {id:5, displayName:'13'},
    {id:8, displayName:'1'},
 {id:9, displayName:'23'}]

    vm.items = $filter('orderBy')(vm.temp, 'displayName');

3 个答案:

答案 0 :(得分:2)

添加分拣机功能:

function sorter(a) {
  if(isNaN(parseInt(a.displayName))) {
    return a.displayName;
  }
  else {
    return parseInt(a.displayName);
  }
}

使用以下代码更新代码的最后一行:

vm.items = $filter('orderBy')(vm.temp, sorter);

演示: https://plnkr.co/edit/OfNpqSv3Pj9CDD3bMyoQ?p=streamer

答案 1 :(得分:1)

为什么不在另一边使用HTML。

  <p ng-repeat="employee in employees | orderBy:'displayName'">{{employee}}</p>

请查看这个,即使它是字符串,排序也在两种方式都有效。

DEMO:https://codepen.io/mkarrfan/pen/QqOaPa

答案 2 :(得分:0)

使用简单的javascript和this script by Brian Huisman based on David koelle's

yourarr.sort(function naturalSorter(as, bs){
var a, b, a1, b1, i= 0, n, L,
rx=/(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.\D+)|(\.$)/g;
if(as=== bs) return 0;
a= as.displayName.toLowerCase().match(rx);
b= bs.displayName.toLowerCase().match(rx);
L= a.length;
while(i<L){
    if(!b[i]) return 1;
    a1= a[i],
    b1= b[i++];
    if(a1!== b1){
        n= a1-b1;
        if(!isNaN(n)) return n;
        return a1>b1? 1:-1;
    }
}
return b[i]? -1:0;

});

Here is working plunker