Skip to content Skip to sidebar Skip to footer

Keeping Insertion Order In Angular

I have a HTML fragment that iterates over key, value collection. When I create an object and put some value in, then iterate trough that object via HTML fragment, all works perfect

Solution 1:

From Angular reference on ng-repeat (link):

Iterating over object properties

It is possible to get ngRepeat to iterate over the properties of an object using the following syntax:

<div ng-repeat="(key, value) in myObj"> ... </div>

You need to be aware that the JavaScript specification does not define the order of keys returned for an object. (To mitigate this in Angular 1.3 the ngRepeat directive used to sort the keys alphabetically.)

Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser when running for key in myObj. It seems that browsers generally follow the strategy of providing keys in the order in which they were defined, [...]

If this is not desired, the recommended workaround is to convert your object into an array that is sorted into the order that you prefer before providing it to ngRepeat. You could do this with a filter such as toArrayFilter or implement a $watch on the object yourself.

Additionally, I do not think Angular 1.x knows how to iterate over a Map. I believe this line in the code proves it:

collectionKeys = [];
for (var itemKey in collection) { // iterates your object using `in`, not `of` or `Map.forEach()`
    ...
}
// ng-repeat then iterates the collectionKeys to create the DOM

So you will probably need to act as Angular docs suggest:

[...] convert your object into an array that is sorted into the order that you prefer before providing it to ngRepeat. You could do this with a filter such as toArrayFilter or implement a $watch on the object yourself.

Post a Comment for "Keeping Insertion Order In Angular"