tenfour
tenfour

Reputation: 36896

How does AngularJS ng-repeat track items by default?

I understand that you can use track by expr to specify how items are keyed in a ng-repeat directive.

But without track by, how does AngularJS identify items?

Could I control how objects are tracked by altering the object, without using track by, for example?

From the docs:

If no tracking function is specified the ng-repeat associates elements by identity in the collection.

But this is not clear. What does "identity in the collection" mean?

Upvotes: 2

Views: 2889

Answers (3)

mccainz
mccainz

Reputation: 3497

Without a track expression a hash based on the value is computed. WIth a track expression you can supply your own function to compute the hash if you want that level of control.

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@*" data-semver="1.3.0" src="//code.angularjs.org/1.3.0/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="myCtrl">
    <h1>User Defined Indexer</h1>
    <ul>
      <li ng-repeat="item in data track by getTracker()">{{item}}</li>
    </ul>

    <script>
      var app=angular.module("app",[]);
      app.controller("myCtrl",function($scope){
        $scope.data=[1,2,3,4,5]
        $scope.getTracker = function(v){
          return Math.random();
        }
      });
      angular.bootstrap(document,["app"]);
    </script>

  </body>

</html>

Upvotes: 1

Gruff Bunny
Gruff Bunny

Reputation: 27976

If the repeat is performed on object keys then the tracking identifier is the key

e.g. ng-repeat="(key,value) in thingies"

For an array the tracking identifier is determined by calling the hashKey function for each array item. The comments from the hashKey function indicates how this is determined:

  • string is string
  • number is number as string
  • object is either result of calling $$hashKey function on the object or uniquely generated id,
  • that is also assigned to the $$hashKey property of the object.

Upvotes: 2

Rahil Wazir
Rahil Wazir

Reputation: 10132

If you omit the track by expression, then angular by default will track by $$hashkey which is automatically inserted by angular to your list of objects. $$hashkey is refer to as identity of collection.

You can find more here What is the $$hashKey added to my JSON.stringify result

Upvotes: 3

Related Questions