在 AngularJS 中按字母顺序排序下拉列表 [英] Sorting dropdown alphabetically in AngularJS

查看:37
本文介绍了在 AngularJS 中按字母顺序排序下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过使用 ng-options 填充下拉列表,该选项连接到一个控制器,而该控制器又调用一个服务.不幸的是,传入的数据一团糟,我需要能够按字母顺序对其进行排序.

I'm populating a dropdown through the use of ng-options which is hooked to a controller that in turn is calling a service. Unfortunately the data coming in is a mess and I need to be able to sort it alphabetically.

你认为像 $.sortBy 这样的东西会做,但不幸的是它没有做 jack.我知道我可以通过 javascript 使用辅助方法 function asc(a,b) 或类似的方法对其进行排序,但我拒绝相信没有更干净的方法可以做到这一点,而且我不想要使用辅助方法使控制器膨胀.这是原则上如此基本的东西,所以我不明白为什么 AngularJS 没有这个.

You figure that something like $.sortBy would do it but unfortunately it didn't do jack. I know I can sort it via javascript with a helper method function asc(a,b) or something like that but I refuse to believe that there is not cleaner way of doing this plus I don't want to bloat the controller with helper methods. It is something so basic in principle so I don't understand why AngularJS doesn't have this.

有没有办法做类似 $orderBy('asc') 的事情?

Is there a way of doing something like $orderBy('asc')?

示例:

<select ng-option="items in item.$orderBy('asc')"></select>

orderBy 中有选项非常有用,这样您就可以做任何想做的事情,无论何时您通常尝试对数据进行排序.

It would be extremely useful to have options in orderBy so you can do whatever you want, whenever you usually try to sort data.

推荐答案

Angular 有一个 orderBy 过滤器可以这样使用:

Angular has an orderBy filter that can be used like this:

<select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name'"></select>

参见这个小提琴的例子.

值得注意的是,如果使用了 track by,它需要出现在 orderBy 过滤器之后,就像这样:

It's worth noting that if track by is being used it needs to appear after the orderBy filter, like this:

<select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name' track by f.id"></select>

这篇关于在 AngularJS 中按字母顺序排序下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆