Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
977 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...