I'm using AngularJs and found a problem in ordering properties of a hash object in a template.
My object is like:
function TestCtrl($scope){
$scope.week = {'MONDAY': ['manuel'], 'TUESDAY': [], 'WEDNESDAY': ['valerio'], 'THURSDAY': ['manuel', 'valerio'], 'FRIDAY': []}
}
Now, when I try to print these values in my template:
<div ng-repeat="(day, names) in week">
<span>{{day}}</span>
<ul> <li ng-repeat="name in names">{{name}}</li> </ul>
</div>
The order of the days printed is different: FRIDAY MONDAY THURSDAY TUESDAY WEDNESDAY
I tried to apply the filter orderBy
but I think it doesn't work with objects, but just with arrays...
How can I order it?
As per AngularJS docs (version 1.3.20):
A workaround is to use an array of keys:
Use the array in view for iteration:
Update from AngularJS version 1.4.6 docs:
This question is old, but I ended up coming up with an answer to this that I thought might be an improvement on some of the previous answers.
Rather than simply convert the object into an array, it's much more DRY to create an angular filter that does that for you, and then
ngRepeat
orngOptions
over that.As an example:
Then, with an object like:
We could use it like so:
This way, you neither have to create a new array and pollute
$scope
, nor do you have to go back and change your actualdegrees
object, which could have unwanted side-effects.This was fixed in Angular 1.4. As stated in the official Angular documentation below:
https://docs.angularjs.org/api/ng/directive/ngRepeat
There is actually a simple solution ... The object keys are not ordered by default BUT if you create the object in browser from scratch your browser WILL know the order ;)
Example:
So simply ... recreate the object ... or use this simple filter:
Example with regular objects:
Example with sorted objects:
There is no way to order hash objects like that. Not just in angular but in javascript in general.
I would convert the hash object to an array of objects, something like that:
And then change the view to something like that: