gpt4 book ai didi

javascript - 为什么 Angular orderBy 自定义比较器不起作用?

转载 作者:搜寻专家 更新时间:2023-11-01 04:53:49 25 4
gpt4 key购买 nike

我正在尝试为 Angular orderBy 指令实现自定义比较器。正如您在代码片段中看到的那样,自定义比较器被忽略(没有从 console.log 中记录任何内容),即使它应该根据 angular documentation for orderBy 工作。

angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.files = [
{name: 'File1', size: '1.2 Mb'},
{name: 'File2', size: '2.4 Kb'},
{name: 'File3', size: '241 Bytes'},
{name: 'File4', size: '2.0 Mb'},
{name: 'File5', size: '16.1 Kb'}
];

$scope.fileSizeComparator = function(s1, s2) {
// split the size string in nummeric and alphabetic parts
console.log(s1);
console.log(s2);
var s1Splitted = s1.size.split(" ");
var s2Splitted = s2.size.split(" ");
if (s1Splitted[1] === s2Splitted[1]) {
// if size type is the same, compare the number
return s1Splitted[0] > s2Splitted[0];
}
// default : compare on size type Mb > Kb > Bytes
return s1Splitted[1] > s2Splitted[1];
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="orderByExample">
<div ng-controller="ExampleController">
<table>
<tr>
<th>Name</th>
<th>Size</th>
</tr>
<tr ng-repeat="file in files | orderBy:'size':false:fileSizeComparator">
<td>{{file.name}}</td>
<td>{{file.size}}</td>
</tr>
</table>
</div>
</div>

我已经在 JsFiddle 上测试了 Angular 文档中的示例代码而且它也不起作用。有什么想法吗?

最佳答案

在@morels 的帮助下我找到了解决方案:是的,我确实应该返回 1 和 -1。但主要问题是比较器被忽略了。显然是因为此功能仅适用于 Angular 1.5.7 及更高版本。我还需要在 s1 和 s2 传递的参数的 .value 上使用 .split

这是代码片段中的工作解决方案:

angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.files = [
{name: 'File1', size: '1.2 Mb'},
{name: 'File2', size: '2.4 Kb'},
{name: 'File3', size: '241 Bytes'},
{name: 'File4', size: '2.0 Mb'},
{name: 'File5', size: '16.1 Kb'}
];

$scope.fileSizeComparator = function(s1, s2) {
// split the size string in nummeric and alphabetic parts
var s1Splitted = s1.value.split(" ");
var s2Splitted = s2.value.split(" ");
if (s1Splitted[1] === s2Splitted[1]) {
// if size type is the same, compare the number
return parseFloat(s1Splitted[0]) > parseFloat(s2Splitted[0]) ? -1 : 1;
}
// default : compare on size type Mb > Kb > Bytes
return s1Splitted[1] > s2Splitted[1] ? -1 : 1;
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<div ng-app="orderByExample">
<div ng-controller="ExampleController">
<table>
<tr>
<th>Name</th>
<th>Size</th>
</tr>
<tr ng-repeat="file in files | orderBy:'size':false:fileSizeComparator">
<td>{{file.name}}</td>
<td>{{file.size}}</td>
</tr>
</table>
</div>
</div>

关于javascript - 为什么 Angular orderBy 自定义比较器不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38141367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com