HomeAngularJSAngular ng-repeat trackby and $$hashkey

Angular ng-repeat trackby and $$hashkey

In this blog post we will look into more advanced things related to ng-repeat directive.

$$hashkey

$$hashkey is a auto generated key which angular assigns to array,collection passed in ng-repeat directive. Angular uses it to keep track of any changes made to array and update doom accordingly. Lets see this with with an example

To remove $$hashkey from array you need to use angular.copy() or angular.toJson()
Below is example showing the same.

ng-repeat trackby

As we know ng-repeat is used to tight up collection to DOM. Suppose we have an collection of 20 elements and are using it create a complex DOM structure.
Suppose we make changes to the array and add or edit elements, this would result in angularjs recreating entire dom structure for the new array. This can become a costly operation in many cases, causing lot of browser repaints. Angular introduced a new feature in version 1.3 called ‘track by’ in which we can pass a parameter to ng-repeat which is unique to the array. So when we change the array, angular only recreates dom only for the changed array value, and not the entire array.

A very simple way to do this is
[js]
<ul>
<li id=’row.id’ ng-repeat=’row in demo_array track by $index’>
{{row.name}} – {{$index}}
</li>
</ul>
[/js]
This increase the performance on ng-repeat a lot and should always be used. Another thing to notice, when we use ‘track by’, angular no longer adds $$hashkey to the array.

%d bloggers like this: