Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
971 views
in Technique[技术] by (71.8m points)

angularjs - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...