Joe82 Joe82 - 9 months ago 843
AngularJS Question

AngularJS - orderBy value when ng-repeat by key, value pair

I have counted the ocurrences of each item in a set of data with countBy function in lodash, and the result is this:

$scope.colors= {
"Orange": 3,
"Blue": 2,
"Pink": 1,
"Red": 1,
"Black": 2,

Now I would like to display the data and order it by its value. I've tried with

<div ng-controller="myCtrl" ng-app="myApp">
<li ng-repeat="(key,value) in colors | orderBy:value">
{{key}} ({{value}})

But the orderBy filter doesn't seem to do the trick (see the plunkr here)

Is there any way to do it with the current data form, or is it a better way to structure the data in order to achieve the desired result? Thanks in advance!


As the documentation says, orderBy expects an array as input, not an object. In general, although it's supported, I've never met a use-case where using an object with ng-repeat was a good idea.

Just transform your object into an array:

$scope.colors = [];
angular.forEach(occurrences, function(value, key) {
        color: key,
        count: value

and then use

<li ng-repeat="element in colors | orderBy:'count'">
    {{ element.color }} ({{ element.count }})

See your updated plunkr.