bb2
bb2

Reputation: 2982

Why does a string index based array appear sorted in angularjs ng-repeat

I created the following:

interface IMap {
[name: string]: string;
}

var map: IMap = {};
map["S"] = "s";
map["C"] = "c";
map["D"] = "d";

When I go over an ng-repeat in angular, it prints them in this order c, d, s instead of s, c, d. Why is it being sorted?

Upvotes: 0

Views: 323

Answers (2)

hjl
hjl

Reputation: 2802

angular will check the type of collection you would like to iterate, below is the snippet from source code, as you can see collectionKeys.sort() is sorted by alphanumeric ASC. https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js#L333

if (isArrayLike(collection)) {
  collectionKeys = collection;
  trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
} else {
  trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  // if object, extract keys, sort them and use to determine order of iteration over obj props
  collectionKeys = [];
  for (var itemKey in collection) {
    if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') {
      collectionKeys.push(itemKey);
    }
  }
  collectionKeys.sort();
}

if you want it ordered as you put but still using object, you can create another array to keep the keys and ng-repeat on it. pseudocode below

scope.map = {S: 's', C: 'c', D: 'd'};
scope.mapKey = ['S', 'C', 'D'];

<div ng-repeat="key in mapKey">
    {{map[key]}}
</div>

Upvotes: 1

Antiga
Antiga

Reputation: 2274

Objects are not ordered in JavaScript. If you want order, you need to use an array.

I don't know exactly how to do that with TypeScript, but I imagine something like this:

var map: IMap = [];

Angular by default is sorting your object literal alphabetically because it doesn't have an order.

Think of the object literal like a dictionary.

Upvotes: 1

Related Questions