我在根据属性排序JSON对象时遇到问题。我提到了这个stackoverflow的答案https://stackoverflow.com/a/18186947/3496380,并且它在其排序函数中比较了实际属性的值,但对象仍未在页面上排序(尽管它们的顺序不同,只是不按字母顺序排列)
以下是相关代码:
<body ng-app="app" ng-controller="mainController">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">xxxxxxx</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="starter-template">
<h1>xxxxxx</h1>
<p class="lead">xxx</p>
</div>
<div class="container-fluid thumbnail">
<div class="col-xs-2" ng-repeat="champ in champions | orderObjectBy:'name'">
<div class="">
<h6>{{ champ.name }}</h6>
<img ng-src="http://ddragon.leagueoflegends.com/cdn/{{ versionNumber }}/img/champion/{{ champ.image.full }}" />
</div>
</div>
</div>
</div><!-- /.container -->
app.js文件:
var app = angular.module('app', ['ui.bootstrap']).controller('mainController', function($scope, $http, $sce) {
// champion names json
$scope.urlChampions = "https://na.api.pvp.net/api/lol/static-data/na/v1.2/champion?champData=blurb,image&api_key=KEY";
// grab list of champion names
$http.get($scope.urlChampions).then(function(response) {
$scope.champions = response.data.data;
$scope.versionNumber = response.data.version;
});
$scope.trust = $sce.trustAsHtml;
});
app.filter('orderObjectBy', function(){
return function(input, attribute) {
if (!angular.isObject(input)) return input;
var array = [];
for(var objectKey in input) {
array.push(input[objectKey]);
}
array.sort(function(a, b){
//console.log(typeof a);
a = a[attribute];
b = b[attribute];
//console.log(typeof a);
//console.log(a + " fsdfa " + b);
//console.log(a < b);
return a < b;
});
return array;
}
});
这里是抓取JSON数组的链接:http://pastebin.com/V7Jb3xpn
编辑:通过将app.js中的array.sort函数更改为以下
来实现它array.sort(function(a, b){
a = a[attribute];
b = b[attribute];
if (a < b) {
return -1;
}
else if (a > b) {
return 1;
}
else {
return 0;
}