如何从自定义排序函数中调用默认比较器



我有一个自定义排序函数,用于将网格中的一列的字符串转换为数字。其他列由字符串或日期值组成。我有一个自定义排序函数,用于检查数字列并执行转换,但对于其他值,我希望使用默认比较器的行为。我该如何做到这一点?

$scope.sort = function (keyname) {
  $scope.sortKey = keyname;
  $scope.reverse = !$scope.reverse;
};
$scope.sortSubGrid = function (a, b) {
  if ($scope.sortKey === 'caseNumber') {
    return = parseInt(b.value) -parseInt(a.value);
  }
  else {
    return = a.value > b.value;
  }
};
<tr dir-paginate="agreement in agreements|orderBy:sortKey:reverse:sortSubGrid" ...>

sortSubGrid函数的后半部分旨在对非数字列进行排序,但没有达到我期望的结果,这只是默认比较器提供的结果。如何获得第二个子句的默认行为?

根据orderBy.js中的代码,您可以使用默认或自定义,但不能同时使用您所描述的,这将是一个很好的功能。

// Define the `compare()` function. Use a default comparator if none is specified.
var compare = isFunction(compareFn) ? compareFn : defaultCompare;

所以你总是可以得到原始的defaultCompare代码并修改它。

// source orderBy.js
function defaultCompare(v1, v2) {
  var result = 0;
  var type1 = v1.type;
  var type2 = v2.type;
  if (type1 === type2) {
    var value1 = v1.value;
    var value2 = v2.value;
    if (type1 === 'string') {
      // Compare strings case-insensitively
      value1 = value1.toLowerCase();
      value2 = value2.toLowerCase();
    } else if (type1 === 'object') {
      // For basic objects, use the position of the object
      // in the collection instead of the value
      if (isObject(value1)) value1 = v1.index;
      if (isObject(value2)) value2 = v2.index;
    }
    if (value1 !== value2) {
      result = value1 < value2 ? -1 : 1;
    }
  } else {
    result = type1 < type2 ? -1 : 1;
  }
  return result;
}

最新更新