如何按键对ng-options中的数组进行排序?

时间:2015-06-03 13:08:28

标签: javascript angularjs select angularjs-filter angularjs-ng-options

有这样的数组:

month: Array[13]0: "M"1: "January"2: "February"3: "March"4: "April"5: "May"6: "June"7: "July"8: "August"9: "September"10: "October"11: "November"12: "December"

我做:

ng-options="key as value for (key, value) in data.month | orderBy:key"

但我得到未分类的选择列表。

3 个答案:

答案 0 :(得分:11)

要使用过滤器跟踪,请使用track by

<强>标记

ng-options="key as value for (key, value) in data.month | orderBy:'key' track by key"

<强>更新

这个orderBy永远不会起作用,因为你有文字数组。您需要将此数组转换为类似JSON的对象,其结构类似于[{id: 0, value: "M"}, {id: 1, value: "January"},......]

<强> HTML

ng-options="item.id as item.value for items in data.month | orderBy:'id'"

Demo Plunkr

答案 1 :(得分:2)

你遗失的两个'。这部分orderBy: key应为orderBy:'key'

试试这个:

ng-options="key as value for (key, value) in data.month | orderBy: 'key'"

答案 2 :(得分:1)

要解决此问题,需要重新格式化ng-option,如:

day.id as day.value for day in data.month

数组data.month将告诉用户pankajparkar