angular.module('app', [])
.controller('appCtrl', function($scope,$filter) {
$scope.cities = [{
city: 'London',
count: 2000,
country: 'United Kingdom'
}, {
city: 'Liverpool',
count: 1000,
country: 'United Kingdom'
}, {
city: 'Manchester',
count: 500,
country: 'United Kingdom'
}, {
city: 'Newport',
count: 800,
country: 'United Kingdom'
}, {
city: 'Northampton',
count: 90,
country: 'United Kingdom'
}];
$scope.cities = $filter('alphsort')($scope.cities);
})
.filter('alphsort', function() {
return function(input) {
var result = {};
angular.forEach(input, function(val, index) {
var key = val.city.charAt(0).toUpperCase();
result[key] = result[key] || [];
result[key].push(val);
});
return result;
}
});
<script src="//cdn.bootcss.com/angular.js/1.4.7/angular.js"></script>
<div ng-app="app" ng-controller="appCtrl">
<div>
<div ng-repeat="(alph,list) in cities track by alph">
<ul>
<li>
<strong ng-bind="alph"></strong>
</li>
<li ng-repeat="item in (list | orderBy: 'city') track by $index">
<p>
<a href="javascript:;" ng-bind="item.city"></a>
<span>({{item.count}})</span>
</p>
</li>
</ul>
</div>
</div>
</div>
哦,我明白了。這對我有用! 我還沒有讀過濾器。這真的很簡單。我絞盡腦汁4個小時,謝謝! –