0

I add some items in the for loop with $timeout to see the animation. It works, but I see wrong values in the <li> items:

$scope.list = [{ id : 1},{ id : 2},{ id : 3},{ id : 4},{ id : 5},{ id : 6}];

for (var i = 0; i < $scope.myItems.length; i++) {
   var x = $scope.myItems[i];

   $log.log(x.id);

   $timeout(function () {
      $scope.list.push({ name: x.id });
   }, 100 * i);
};

<ul class="item-container">
  <li class="item" ng-class="animation" ng-repeat="item in list">{{item.name}}</li>
</ul>

firebug displays:

1
2
3
4
5
6

but in the <ul> tag all <li> items have 6 as a value. Why ?

1 Answer 1

3

Since timeout is on a delay, you'll have to wrap it in a closure so that the "x" is the right one:

for (var i = 0; i < $scope.myItems.length; i++) {
   var x = $scope.myItems[i];
   (function(x){

       $log.log(x.id);

       $timeout(function () {
          $scope.list.push({ name: x.id });
       }, 100 * i);
   })(x);
};

This is because the x continously gets overwriten via x = $scope.myItems[i]. By the time the timeout fires the x has changed to the last one.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.