ng-options:我如何按collection.item.itemName排序

时间:2017-01-30 09:24:28

标签: javascript angularjs sorting ng-options

我有一个选择迭代的集合,如下所示:

ctrl.countriesList = {
    'DK': {countryName: 'Denmark', preferredLanguage: 'DA'}
    'US': {countryName: 'USA', preferredLanguage: 'EN'}
}

并迭代对象:

ng-options="country as country.countryName for country in $ctrl.countriesList"

所以我的下拉列表现在正确地在每个国家/地区的下拉列表中显示countryName属性,但它仍然按ISO代码值(DK,US)进行排序,在我的情况下,它通常与国家/地区名称不一致,因此排序下拉列表中的countryNames不是按字母顺序排列的

如何按字母顺序按countryName排序?提前谢谢!

4 个答案:

答案 0 :(得分:0)

您使用对象数据源时不能使用orderBy过滤器,而orderBy过滤器适用于阵列数据源

See this question

如果您想使用orderBy过滤器,请按照其他答案中的说明对数据源进行更改

如果你想使用对象,我建议你添加一个能返回排序值的函数。

在控制器中:

$scope.ctrl = {//---> Source
            countriesList : {
        'DK': {countryName: 'Denmark', preferredLanguage: 'DA'},
        'US': {countryName: 'USA', preferredLanguage: 'EN'},
        'BEL':{countryName: 'Belgium', preferredLanguage: 'NL'}
      }
}



 $scope.getSortedCountryList = function(){ //--> Sort Function
$scope.sorted = {};
Object.keys($scope.ctrl.countriesList)
        .sort(function(a,b){
          if($scope.ctrl.countriesList[a].countryName < $scope.ctrl.countriesList[b].countryName) return -1;
          if($scope.ctrl.countriesList[a].countryName > $scope.ctrl.countriesList[b].countryName) return 1;
          return 0;
         })
         .forEach(function(v, i) {
           $scope.sorted[v] = $scope.ctrl.countriesList[v];
         });
return $scope.sorted;
}

在HTML select

ng-options="country as country.countryName for country in getSortedCountryList()"

<强> FIDDLE

答案 1 :(得分:-1)

首先,将数据集重写为更“简单”/“JSON”的方法。由于orderBylinkObjects没有(也不会)实施 $scope.countriesList = [ {countryName: 'Denmark', preferredLanguage: 'DA'}, {countryName: 'Belgium', preferredLanguage: 'NL'}, {countryName: 'USA', preferredLanguage: 'EN'} ] ,因此

<select ng-options="country.countryName for country in countriesList | orderBy:'countryName':false" ng-model="selected"></select>

在视图级别:

$.post()

SEE PLUNKR

答案 2 :(得分:-1)

在select标签中使用orderBy服务

<select  ng-options="country as country.countryName for country in ctrl.countriesList | orderBy:'countryName':false" ng-model="country">

还要更新json

 $scope.ctrl.countriesList = [
  {countryName: 'Denmark', preferredLanguage: 'DA'},
  {countryName: 'USA', preferredLanguage: 'EN'}
  ]

Plunkr

答案 3 :(得分:-1)

您也可以直接在Javascript中对数组进行排序。

$scope.countriesList = [
      {countryName: 'Denmark', preferredLanguage: 'DA'},
      {countryName: 'Belgium', preferredLanguage: 'NL'},
      {countryName: 'USA', preferredLanguage: 'EN'}
  ]
.sort(function(a, b){
  return a.countryName < b.countryName;
});