Angular ng-repeat对象,if-else,键的第一个字母

时间:2016-05-12 15:16:16

标签: angularjs if-statement filter angularjs-ng-repeat ng-repeat

我尝试使用字母排序来获取城市的集合。 我有一个看起来如此[{city: 'Liverpool', count: 1000, country: 'United Kingdom'}, ...]

的对象列表

我想以这种方式获取物品

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

我可以获得的最大值 - 我只获得没有Letter的城市计数列表。 我想我的方式不对,但我不知道正确的算法。

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

2 个答案:

答案 0 :(得分:0)

查看角度过滤器

https://docs.angularjs.org/api/ng/filter/orderBy

您可以设置如下内容:

<div ng-repeat="city in cities | orderBy : expression : reverse">

答案 1 :(得分: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>