0

我嘗試獲取具有字母排序的城市的集合。 我有對象的列表,它看起來那麼[{city: 'Liverpool', count: 1000, country: 'United Kingdom'}, ...]角度ng-repeat對象,if-else,密鑰的第一個字母

我希望得到物品這樣

L 
Liverpool (1000) 
London (2000) 
M 
Manchester (500) 
N 
Newport (800) 
Northampton (90) 

最大,我已經可以 - 我得到的只是名單的城市數不信。 我想我會錯誤的方式,但我不知道一個正確的algorytm。

的jsfiddle:https://jsfiddle.net/valsaven/ysf56w48/

回答

0

創建自己的filter,然後更新您的html:

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>

+0

哦,我明白了。這對我有用! 我還沒有讀過濾器。這真的很簡單。我絞盡腦汁4個小時,謝謝! –