Grayda
Grayda

Reputation: 2150

'track by' in AngularJS causes "10 $digest() interations" error

After reading a few other questions on SO, I'm still wondering why the use of 'track by' in my Angular app causes the thing to bog down and display the 10 $digest() iterations error.

I'm using an internal API to retrieve a list of users (~1000, which I know I shouldn't be grabbing all at once, but this is a PoC app). The data returned looks like this:

[
    { FirstName: "John", LastName: "Smith", Login: "SMITJOH1" }, 
    { FirstName: "Jane", LastName: "Citizen", Login: "CITIJAN1" },
    { ... }
]

Login is always unique, so it makes sense to use it as a tracker.

My controller looks like so:

idfixerApp.controller('addController', function($scope, $http, $route, $rootScope) {

  $scope.loadUsers = function() {
      $http.get("/users/all").success(function(data) {
        $scope.users = data
        $scope.selected = $scope.users[0]
      })
  }

  $scope.orderBy = 'LastName';
  $scope.loadUsers()

})

And my view looks like this:

<div ng-controller="addController" id="addController">
    <input ng-model="query">
    <select ng-model="orderBy">
          <option value="LastName">Last Name</option>
          <option value="FirstName">First Name</option>
    </select>
    <select ng-options="user as (user.LastName | uppercase) + ', ' + user.FirstName for user in users track by user.Login | filter:query | orderBy:orderBy" ng-model="selected" size="20"></select>
</div>

If I don't use track by, I can speedily filter and sort, but as soon as I add in track by user.Login, I start getting $digest() errors and my whole page slows down to a crawl.

Since I'm only grabbing the API data once (I added a console.log in to make sure) and since user.Login never changes, I'm confused as to why track by is causing my app to grind to a halt.

An explanation would be wonderful!

Upvotes: 0

Views: 79

Answers (1)

j3k2
j3k2

Reputation: 36

From the docs:

Note: track by must always be the last expression

Try moving it to the end of your ng-repeat statement, after the filter and orderBy expressions.

Upvotes: 2

Related Questions