0

I have simple object:

"socials": {
  "f": "#/facebook/",
  "B": "#/behance/",
  "d": "#/dribble/",
  "L": "#/linkedin/",
  "P": "#/pinterest/"
}

When I try to use ng-repeat="(key, value) in data.socials" it sorts like this: B L P d f.

$index catches wrong index, just as it is ordered by already. How can I order it correctly as it is in jSON file? Or maybe how can I get correct index to use orderBy: correctIndex? I found a fiddle that shows an issue exactly like this: http://jsfiddle.net/zMjVp/

nikoloza
  • 968
  • 2
  • 12
  • 30
  • possible duplicate of [AngularJS sorting by property](http://stackoverflow.com/questions/14478106/angularjs-sorting-by-property) – lucuma Jul 03 '14 at 00:18
  • 1
    http://stackoverflow.com/questions/19287716/skip-ng-repeat-json-ordering-in-angular-js – pratiklodha Jul 03 '14 at 00:33

1 Answers1

4

ngRepeat iterates over object keys in alphabetical order to manage tracking items by $index (see the code for ngRepeat on Github).

To control the order of iteration in ngRepeat you should convert your object structure into an Array which has guaranteed iteration ordering:

JavaScript:

var jsonData = {
    "socials": {
        "f": "#/facebook/",
        "B": "#/behance/",
        "d": "#/dribble/",
        "L": "#/linkedin/",
        "P": "#/pinterest/"
    }
};

var socialsList = [];
angular.forEach(jsonData.socials, function(value, key){
    socialsList.push({
        key: key,
        value: value
    });
});
$scope.socialsList = socialsList;

HTML:

Then update your HTML to iterate over the list instead of the object.

<div ng-repeat="item in socialsList">
    <p> {{item.key}} : {{item.value}} </p> 
</div>

NOTE:

Unless you're using the delete operator you can generally rely on the order of the for...in loop. It's not guaranteed, but it's generally reliable. See the MDN documentation on for...in loops

Sly_cardinal
  • 12,270
  • 5
  • 49
  • 50