0

I am not able to order a key value pair with respect to value in alphabetical order.

The sample which I am using is,

"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"}
]

I have used the following code,

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

But the sorting not happening. Any suggestions?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Gowthami Reddy
  • 430
  • 7
  • 23

3 Answers3

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>

The DEMO on PLNKR

For more information, see

Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • The code you have shared is perfectly working if the input is array. But my input was object, so I ended up writing a sort function in controller. – Gowthami Reddy May 21 '19 at 06:38
0

As orderBy in HTML won't work on Object and week_days_short is array. So sorting on controller fixed my issue.

Object.values($scope.properties.week_days_short).sort()
Gowthami Reddy
  • 430
  • 7
  • 23
-2

I think it can help you.

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"

Here is Ref: In ES6/ES2015 or later you can do this way

  • Fat arrow functions are not allowed in AngularJS expressions. For more information, see [AngularJS Developer Guide - JavaScript vs AngularJS Expressions](https://docs.angularjs.org/guide/expression#angularjs-expressions-vs-javascript-expressions). – georgeawg May 15 '19 at 01:53