icanbeacoder icanbeacoder - 1 month ago 8
AngularJS Question

ng-repeat directive sort the data when using (key, value)

I have a code something like this with ng-repeat = "(key,value) in data".
In Controller:

$scope.Dates = {"Today":"30",
"This Week":"42",
"This Month": "Oct",
"This Quarter" : "Bad",
"This Year" : 2013
}


and ng-repeat directive as

<div ng-repeat="(key,value) in Dates">
{{key}} ==> {{value}}
</div>


The output comes in sorted order as

This Month ==> Oct
This Quarter ==> Bad
This Week ==> 42
This Year ==> 2013
Today ==> 30


How to get rid of this sorting(strange) as I want keys to be used in code.. I checked google group but there was a fiddle for using two arrays of which one was storing the key values. http://jsfiddle.net/Saulzar/puhML/3/b . Don't want to go with this approach.

Answer

This is limitation of JavaScript not Angular.

From ECMAScript Third Edition:

4.3.3 An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

From ECMAScript Language Specification

The [...] order of enumerating the properties [...] is not specified.

Angular sorts object keys explicitly in order to provide at least some sort of persistent behavior.

Workaround is to iterate over extracted keys:

<div ng-repeat="key in keys(Dates)">
  {{key}} ==> {{Dates[key]}}
</div>
$scope.keys = function(obj){
  return obj? Object.keys(obj) : [];
}

$scope.Dates = {
  "Today":"30",
  "This Week":"42",
  "This Month": "Oct",
  "This Quarter" : "Bad",
  "This Year" : 2013
};