我想實現角度orderBy指令的自定義比較器。正如你可以在代碼片段看到,自定義比較被忽略(從沒有登錄的console.log),即使它應該根據angular documentation for orderBy爲什麼角度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上的角度文檔,它也不起作用。 任何想法?
尋找在角文檔的最後一個例子,它說的第三個參數應該是閱讀作爲函數 –