AngularJS $ filter('orderBy')奇怪的排序

时间:2015-10-02 15:54:33

标签: javascript angularjs sorting angularjs-filter angularjs-orderby

看起来AngularJS $filter("orderBy")的工作方式与Array.prototype.sort的工作方式不同。 我为这个问题写了一个例子:

模板:

<div ng-app="app" ng-controller="ctrl">
    <div>arr1 angular </br>{{ arr1ang }}</div>
    <div>arr2 angular </br>{{ arr2ang }}</div>
    <div>arr1 js </br>{{ arr1js }}</div>
    <div>arr2 js </br>{{ arr2js }}</div>
</div>

控制器:

angular.module('app', []);

function ctrl ($scope, $filter) {
    arr1 = [
      {value: "AA"}, 
      {value: "AB"}, 
      {value: "aa"}, 
      {value: "ab"}
    ];
    arr2 = [
      {value: "d"}, 
      {value: "D"}, 
      {value: "w"}, 
      {value: "e"}, 
      {value: "i"}, 
      {value: "O"}, 
      {value: "o"}, 
      {value: "r"}
    ];

    $scope.arr1ang = $filter('orderBy')(arr1, "value");
    $scope.arr2ang = $filter('orderBy')(arr2, "value");

    function comp(a,b){
        if (a.value > b.value)
            return 1;
        else if (b.value > a.value)
            return -1;
        else
            return 0;
    }

    arr1.sort(comp);
    arr2.sort(comp);
    $scope.arr1js = arr1;
    $scope.arr2js = arr2;
}

angular
  .module('app')
  .controller('ctrl', ctrl);

结果:

arr1 angular
[{"value":"AA"},{"value":"aa"},{"value":"AB"},{"value":"ab"}]
arr2 angular
[{"value":"d"},{"value":"D"},{"value":"e"},{"value":"i"},{"value":"O"},{"value":"o"},{"value":"r"},{"value":"w"}]
arr1 js
[{"value":"AA"},{"value":"AB"},{"value":"aa"},{"value":"ab"}]
arr2 js
[{"value":"D"},{"value":"O"},{"value":"d"},{"value":"e"},{"value":"i"},{"value":"o"},{"value":"r"},{"value":"w"}]

我制作了一个关于它的Codepen示例here

我不明白某事或者是AngularJS中的错误?

1 个答案:

答案 0 :(得分:5)

Angularjs按字母顺序排列不区分大小写。在JavaScript中,字符串比较区分大小写。

一种解决方案是在比较之前将所有值转换为小写或大写字符串。