Sort a key/value-pair object

2,071 views
Skip to first unread message

Thomas Benzingson

unread,
Jul 12, 2013, 10:55:22 AM7/12/13
to ang...@googlegroups.com

I have a simple select drop down list that is bound by key/value pairs. However, the drop down list does not show option items in the order I want.  I try to use "orderBy" filter, but I do not know how to do it.  Please help. Thank you in advance.

I want it to show as follows:
10
20
30
50
100

However, it shows those option items as (100 is in the wrong place) before I try to use the "orderBy" filter.

10
100
20
30
50

The following is my JS codes for my controller:

var myApp = angular.module('ListLogsModule', []);

myApp.controller('ListLogsCtrl', function ($scope) {
    // the data is made in order I want.
    $scope.pageSizeOptions= {"10": "10", "20" : "20", "30" : "30", "50" : "50", "100" : "100"};
    // default selected item
    $scope.SelectedPageSize = "10";
}

And HTML as follows.  How can I specify the "orderBy" expression?

<div ng-app="ListLogsModule" ng-controller="ListLogsCtrl">
    <span>Page Size:</span>
    <span>
       <select ng-model="SelectedPageSize" ng-options="k as v for (k,v) in pageSizeOptions | orderBy:?" >
       </select>
    </span>
</div>

Mark Ferguson

unread,
Jul 12, 2013, 12:04:41 PM7/12/13
to ang...@googlegroups.com
It appears that orderBy is not implemented for key/value pairs:


I suspect that angular is ordering the list by string value which is why 100 is appearing after 10.

The easiest would probably be to change your pageSizeOptions to use an array instead of an object. If you're not able to do that for some reason, the link above has a toArray function that you can use before passing it on to orderBy (requires lodash library).

Here's an example using an array of k/v pairs:


Mark

Thomas Benzingson

unread,
Jul 15, 2013, 2:13:16 PM7/15/13
to ang...@googlegroups.com
Thank you, Mark.  I follow your approach to use array.

However, given an key/value pair object as my original post, I can use a trick like:

1. For the key/value pair object, change the values for keys like (values in bold red)

JS

$scope.pageSizeOptions= {"1001": "10", "1002" : "20", "1003" : "30", "1004" : "50", "1005" : "100"};

2. v in bold red
HTML:

<select ng-model="SelectedPageSize" ng-options="v as v for (k,v) in pageSizeOptions | orderBy:?" >
</select>

Reply all
Reply to author
Forward
0 new messages