Does anybody know how I can SKIP JSON ordering altogether when I use ng-repeat (in a painless way probably)?
For example, my source JSON looks something like this -
{
"title": "Title",
"description": "Description",
"moreInfo": "Moreinformation"
}
Once I use it in ng-repeat, it orders them alphabetically. Something like this -
{
"description": "Description",
"moreInfo": "Moreinformation",
"title": "Title"
}
My ng-repeat looks something like this -
<div ng-repeat="(key,data) in items">
<span class="one"> {{key}} </span>
<span class="two"> {{data}} </span>
</div>
I've seen people having a separate array of the keys and using them to identify the JSON objects, ultimately avoiding alphabetical sorting.
Is there an elegant way to do this?
At the moment there is no elegant way to do this. Reason being that - ngRepeat creates an associative array, which is called and not the JSON itself. Although the ECMAScript Standard mentions that:
The declaration order of object properties must be preserved, and iteration must happen in the same order.
But somehow, Angular guys overlooked it. This might get rectified in the later releases.
I still think Angular's behaviour makes more sense. As objects often have more initialisation logic around them than arrays, I think it's fair to assume that the order often might not be what the user actually wants/expected, so forcing a specific sorting ensure the proper behaviour - especially when we also have to deal with older browsers.
I am using this approach to override the alphabetical ordering:
Controller:
PLEASE NOTE that _.keys($scope.steps); is LoDash substituting Object.keys();
HTML:
Nice workaround found at google groups:
And in scope:
Working: http://jsfiddle.net/DnEXC/
Original: https://groups.google.com/forum/#!topic/angular/N87uqMfwcTs
This answer using filter works best for me.
https://groups.google.com/d/msg/angular/N87uqMfwcTs/EGoY6O2gtzsJ
http://jsfiddle.net/er52h/1/
You can use like this: