如何在 angularjs 中对下拉列表进行排序

How to sort dropdown in angularjs?

本文关键字:下拉列表 排序 angularjs      更新时间:2023-09-26

我尝试使用angularjs通过下拉列表进行排序。 但是,排序不起作用。请帮助我。请检查此链接: jsfiddle

.HTML:我的 HTML 代码在这里

<select ng-options="key as value for (key, value) in charityList | orderBy:'value'" ng-model="reportSearch.charityId">
     <option value="">All Charity</option>
</select>

JSON 数组:我的 Json "键=>值"数组,用于使用下拉列表

 $scope.charityList = {
     "1": "softweb charity",
     "2": "charity 1",
     "3": "charity update",
     "4": "Engagement1 Name",
     "6": "United Way Enagagement",
     "7": "Indian Noble Charity"
 }

请检查此链接: jsfiddle

你拥有的是一个对象而不是数组。数组由 V 形定义。

charityList = [ 
     {"name": "softweb charity"}, 
     {"name": "charity 1"},
     {"name": "charity update"},
     {"name": "Engagement1 Name"},
     {"name": "United Way Enagagement"},
     {"name": "Indian Noble Charity"}
],

如果你能使它看起来像这样,你可以用 orderBy 对它进行排序

ng-options="value.name for value in charityList | orderBy:'name'"

试试这个方式。

控制器:

$scope.sort = function(list) { //returns an array : ["charity 1","charity update","Engagement1 Name","Indian Noble Charity","softweb charity", "United Way Enagagement"]
  return $.map(list, function(el) { return el }).sort(function (a, b) {
      return a.toLowerCase().localeCompare(b.toLowerCase());
  });
}

.html:

<select ng-options="value as value for value in sort(charityList)" ng-model="reportSearch.charityId">
     <option value="">All Charity</option>
</select>

你必须将你的对象转换为一个对象数组,否则 orderBy 将不起作用。

 angular.forEach($scope.charityList, function(value, key) {
        arr.push({key: key, value: value})
      })

琴师