Reputation: 917
I have a dictionary (key-value pairs), that might look like this:
data = {
"key1": 1000,
"key2": 2000,
"key3": 500
}
I would like to view this in a table in AngularJS.
I can do it this way:
<tr ng-repeat="(key, value) in data">
<td>{{ key }}</td>
<td>{{ value }}</td>
</tr>
This works fine so far.
Now I would like to have the table sorted by the value. But the orderBy
filter seems to only work for lists of objects:
<tr ng-repeat="(key, value) in data | orderBy: 'value'">
Has no effect. How would I sort this by the value?
Upvotes: 0
Views: 597
Reputation: 222582
orderBy
works on a property of object not the way you mentioned in key,value. Also it expects an array as input, not an object.
You can convert it as an array using angular.forEach and use orderBy as follows
DEMO
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var data = {"key1": 1000,
"key2": 2000,
"key3": 500 }
$scope.data = [];
angular.forEach(data, function(value, key) {
$scope.data.push({
key: key,
count: value
});
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
</head>
<body>
<div ng-controller="myCtrl" ng-app="myApp">
<ul>
<li ng-repeat="element in data | orderBy:'count'">
{{ element.key }} ({{ element.count }})
</li>
</ul>
</div>
</body>
</html>
Upvotes: 2