ng-repeat track by performance

by Michael Hunziker

HTML

<script src="http://momentjs.com/downloads/moment.min.js"></script>
<div ng-controller="TasksCtrl">
  <button ng-click="refresh()">Refresh Tasks from "Server"</button>

  <ul class="tasks">
    <li ng-repeat="task in tasks" task="task" class="task"></li>
    <!-- <li ng-repeat="task in tasks track by task.id" task="task" class="task"></li> -->
  </ul>
</div>

CSS

.tasks {
  max-height: 19em;
  overflow-y: scroll;
  border: 3px solid #ccc;
  list-style: none;
  padding: 0;
}

.tasks .task {
  padding: 0.5em;
  border: 1px solid #007aff;
}

.tasks .task .time {
  color: #8f8f8f;
  font-size: 0.7em;
}

JavaScript

angular.module('myApp', [])
  .controller('TasksCtrl', function($scope) {
    var date = new Date();
    $scope.tasks = [];

    for (var i = 1; i < 301; i++) {
      $scope.tasks.push({
        id: i,
        title: 'Task ' + i,
        date: date
      });
    }

    $scope.refresh = function() {
      var newTasks = angular.copy($scope.tasks);
      newTasks[1].title = 'UPDATED TASK 1!!!!'
      newTasks[2] = {
        id: 999999,
        title: 'UPDATED TASK 2!!!!',
        date: new Date()
      }
      $scope.tasks = newTasks;
    };
  })
  .directive('task', function() {
    return {
      scope: {
        task: '='
      },
      template: '{{ task.title }} <span class="time">({{  task.date }})</span>',
      link: function(scope) {
        console.log('rendering', scope.task.id);
      }
    };
  });