Joe82 Joe82 - 6 months ago 699
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">
<ul>
<li ng-repeat="(key,value) in colors | orderBy:value">
{{key}} ({{value}})
</li>
</ul>
</div>


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!

Answer

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) {
    $scope.colors.push({
        color: key,
        count: value
    });
});

and then use

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

See your updated plunkr.