What I am trying to do is sort some data by property. Here is example that I tought should work but it doesn't.
HTML part:
<div ng-app='myApp'> <div ng-controller="controller"> <ul> <li ng-repeat="(key, value) in testData | orderBy:'value.order'"> {{value.order}}. {{key}} -> {{value.name}} </li> </ul> </div> </div>
JS part:
var myApp = angular.module('myApp', []); myApp.controller('controller', ['$scope', function ($scope) { $scope.testData = { C: {name:"CData", order: 1}, B: {name:"BData", order: 2}, A: {name:"AData", order: 3}, } }]);
And the result:
- A -> AData
- B -> BData
- C -> CData
... that IMHO should look like this:
- C -> CData
- B -> BData
- A -> AData
Did I miss something (here is ready JSFiddle to experiment on)?
AngularJS' orderBy filter does just support arrays - no objects. So you have to write an own small filter, which does the sorting for you.
Or change the format of data you handle with (if you have influence on that). An array containing objects is sortable by native orderBy filter.
Here is my orderObjectBy filter for AngularJS:
app.filter('orderObjectBy', function(){ return function(input, attribute) { if (!angular.isObject(input)) return input; var array = []; for(var objectKey in input) { array.push(input[objectKey]); } array.sort(function(a, b){ a = parseInt(a[attribute]); b = parseInt(b[attribute]); return a - b; }); return array; } });
Usage in your view:
<div class="item" ng-repeat="item in items | orderObjectBy:'position'"> //... </div>
The object needs in this example a position attribute, but you have the flexibility to use any attribute in objects (containing an integer), just by definition in view.
Example JSON:
{ "123": {"name": "Test B", "position": "2"}, "456": {"name": "Test A", "position": "1"} }
Here is a fiddle which shows you the usage: http://jsfiddle.net/4tkj8/1/
It's pretty easy, just do it like this
$scope.props = [{order:"1"},{order:"5"},{order:"2"}] ng-repeat="prop in props | orderBy:'order'"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With