Stop ng-repeat auto-sorting your objects in AngularJS 1.3

I was working on a project that called for an object to be used with ng-repeat. By default Angular orders this alphabetically but this wasn't what we wanted in the project at all.

As it turns out there's no way to stop this in AngularJS 1.3 by default. However, this behaviour has been removed from 1.4, which is currently in beta.

Thankfully it's not too difficult to stop this from happening in 1.3 too.

How?

In order to get this to work we need to grab our keys from the object and shove them into an array. We can then iterate this in the ng-repeat without it messing around with the order of our items.

The easiest way to do this is to create a new function that we can pass the object through to and then use the native Object.keys method to pop them into an array.

$scope.objectKeys = function(obj){
  return Object.keys(obj);
}

We can then replace the object we were using on the ng-repeat with this function, passing through our original object.

<div ng-repeat="key in objectKeys(values)">...</div>

Unfortunately as we only have an array of keys now we don't have access to the value which is probably very unhelpful. As a new scope is created on each item repeated we can use the ng-repeat directive to setup the value model for us.

<div ng-repeat="key in objectKeys(values)" ng-init="value = values[key]">...</div>

And that's it! Your values will now remain in the correct order.

Want to learn more AngularJS? My book Learning Web Development with AngularJS and Bootstrap is now available from Packt or Amazon

About Stephen Radford

Software Engineer. I take a few photos when I'm not stuck behind a keyboard too.

Leicester, UK http://stephenradford.co.uk

Comments