我使用过滤器的angularjs顺序来排序json。按照优先顺序,小写后跟大写,但不适用于单个字符。任何人都可以帮忙找出来吗?
$scope.friends = [
{name: 'A'},
{name: 'a'},
{name: 'B'},
{name: 'b'},
{name: 'C'},
{name: 'c'}
];
<table class="friends">
<tr>
<th>Name</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:'name'">
<td>{{friend.name}}</td>
</tr>
</table>
结果:
Name
====
A
a
B
b
C
c
答案 0 :(得分:0)
你可以尝试这个自定义过滤器,如下所示吗?
<body ng-app="MyApp">
<div ng-controller="MyCtrl">
<table class="friends">
<tr>
<th>Name</th>
</tr>
<tr ng-repeat="friend in friends | localeOrderBy:'name'">
<td>{{friend.name}}</td>
</tr>
</table>
</div>
</body>
app.filter("localeOrderBy", [function () {
return function (array, sortPredicate, reverseOrder) {
if (!Array.isArray(array)) return array;
if (!sortPredicate) return array;
var isString = function (value) {
return (typeof value === "string");
};
var isNumber = function (value) {
return (typeof value === "number");
};
var isBoolean = function (value) {
return (typeof value === "boolean");
};
var arrayCopy = [];
angular.forEach(array, function (item) {
arrayCopy.push(item);
});
arrayCopy.sort(function (a, b) {
var valueA = a[sortPredicate];
var valueB = b[sortPredicate];
if (isString(valueA))
return !reverseOrder ? valueA.localeCompare(valueB) : valueB.localeCompare(valueA);
if (isNumber(valueA) || isBoolean(valueA))
return !reverseOrder ? valueA - valueB : valueB - valueA;
return 0;
});
return arrayCopy;
}
}]);
答案 1 :(得分:0)
尝试此解决方案仅适用于单个字符:
angular.module('app', []).controller('MyController', ['$scope', function($scope) {
$scope.friends = [
{name: 'A'},
{name: 'a'},
{name: 'B'},
{name: 'b'},
{name: 'C'},
{name: 'c'}
];
}]).filter('customOrderBy', function(){
return function(input, name)
{
var result = []
for(var item of input)
{
var prop = item[name];
var toUpper = prop.toUpperCase().charCodeAt(0);
result.push({item, code: toUpper + (prop.toLowerCase() == prop ? 0 : 1)});
}
return result.sort(function(a, b){return a.code > b.code ? 1 : (a.code == b.code ? 0 : -1);}).map(function(x) { return x.item; });
}
})
&#13;
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="MyController">
<table class="friends">
<tr>
<th>Name</th>
</tr>
<tr ng-repeat="friend in friends | customOrderBy: 'name'">
<td>{{friend.name}}</td>
</tr>
</table>
</div>
</body>
&#13;