ng-options orderBy键值对中的值

时间:2019-05-15 01:23:07

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

我无法以字母顺序的顺序针对value订购键值对。

我正在使用的示例是

"week_days_short":[
    {"key":"1","value":"Mon"},
    {"key":"2","value":"Tue"},
    {"key":"4","value":"Thu"},
    {"key":"3","value":"Wed"},
    {"key":"5","value":"Fri"},
    {"key":"6","value":"Sat"},
    {"key":"7","value":"Sun"}
]

我使用了以下代码,

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

但是排序没有发生。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

angular.module("app",[])
.controller("ctrl", function($scope) {

$scope.properties = {
  "week_days_short":[
    {"key":"1","value":"Mon"},
    {"key":"2","value":"Tue"},
    {"key":"4","value":"Thu"},
    {"key":"3","value":"Wed"},
    {"key":"5","value":"Fri"},
    {"key":"6","value":"Sat"},
    {"key":"7","value":"Sun"}
  ]};

})
 <script src="//unpkg.com/angular/angular.js"></script>
 <body ng-app="app" ng-controller="ctrl">
    selection={{selection}}<br>
    Select with Alphabetical Order<br>
    <select ng-model="selection"
            ng-options="item.key as item.value for item in 
              properties.week_days_short | 
              orderBy:'value' track by item.value">
      <option value="">Select day</option>
    </select>
  </body>

DEMO on PLNKR

有关更多信息,请参见

答案 1 :(得分:0)

因为HTML中的orderBy无法在Object上使用,而且week_days_short是数组。因此,对控制器进行排序解决了我的问题。

Object.values($scope.properties.week_days_short).sort()

答案 2 :(得分:-2)

我认为它可以为您提供帮助。

ng-options="key as value.sort((a, b) => a.key.localeCompare(b.key)) for (key, value) in 
        properties.week_days_short | 
        orderBy:'value' track by value"

这里是参考:In ES6/ES2015 or later you can do this way