【问题标题】:how to order by numeric and character [closed]如何按数字和字符排序[关闭]
【发布时间】:2018-03-08 05:26:09
【问题描述】:

PLUNKER

我有一个ng-repeat,在下拉列表中有以下值。

Up to 6 months
From 13 to 24 months
Higher than 24 months
From 6 to 12 months

我需要像下面这样对值进行排序

//following is the expected output
// Up to 6 months
//From 6 to 12 months
//From 13 to 24 months
//Higher than 24 months




$scope.items = [{name: 'Up to 6 months', id: 30 },{ name: 'From 13 to 24 months', id: 27 },{ name: 'Higher than 24 months', id: 50 },{ name: 'From 6 to 12 months', id: 50 }];

【问题讨论】:

  • 你不能在每个项目中放置一个排序顺序,然后按那个排序顺序排序吗?
  • 我需要根据什么对每个项目进行排序
  • 基于名称值在逗号分隔字符串中的位置“最长 6 个月,从 6 到 12 个月,从 13 到 24 个月,高于 24 个月”。我希望这不是它在数据库中的存储方式 - 您将如何处理将“超过 24 个月”更改为“超过两年”的请求?

标签: javascript html angularjs angularjs-orderby


【解决方案1】:

您的姓名字段不是格式化文本,您无法按姓名排序,请添加一个如下所示的字段,该字段将使用排序条件填充字段值。这里给出了一个示例排序函数:

$scope.items.sort(
function(a,b) {
// Change the logic based on your criteria
return (/*Your criteria*/) ? 1 : 0);
} 
);

您的数据将如下所示:

$scope.items = [{name: 'Up to 6 months',sort:0, id: 30 },{ name: 'From 13 to 24 months',sort:1, id: 27 },{ name: 'Higher than 24 months',sort:3, id: 50 },{ name: 'From 6 to 12 months', sort:4, id: 50 }];

使用以下内容:

<div ng-repeat="item in items | orderBy:['sort','id']">{{item.name}}-{{item.id}}</div>

【讨论】:

  • 似乎更好,但顺序有点改变
  • //从 13 到 24 个月 / 最多 6 个月 //从 6 到 12 个月 //高于 24 个月
  • 检查更新的答案
  • 你维护了另一个排序ID...,值来自db...所以我需要维护另一个列...。这很难
  • 是的。您必须根据您的姓名字段创建一个密钥。由于名称不是按字母顺序排列的,因此无法对该字段进行排序,您必须创建一个键。
【解决方案2】:

您的项目将像这样加载,

 $scope.selectedItem = { name: 'two', id: 27 };
 $scope.items = [{name: 'Up to 6 months',sort:1, id: 30 },{ name: 'From 13 to 24 months',sort:3, id: 27 },{ name: 'Higher than 24 months',sort:4, id: 50 },{ name: 'From 6 to 12 months', sort:2, id: 50 }];

ng-重复

<select ng-model="selectedItem">
   <option ng-repeat="item in items  | orderBy:['sort']" value={{item.id}}>
    {{item.name}}
   </option>
</select>

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 2011-12-06
    相关资源
    最近更新 更多