2

I use angularjs to add animation to a table when array in scope changes. here is the HTML code:

<div ng-app="myapp" ng-controller="myCtrl"> 
        <table>
            <tr ng-repeat="x in items track by $index" class="fade2">                                   
                <td >
                     {{ x }}
                </td>
            </tr>
        </table>
    <button ng-click="add()">add</button>
    <button ng-click="reset()">reset</button>       
</div>

and the javascript code:

var app = angular.module('myapp', ['ngAnimate']);
app.controller('myCtrl', function($scope) {
    $scope.items = ['hello'];

    $scope.add = function() {
        $scope.items.push('hello')
    }

    $scope.reset = function() {
        $scope.items = ['hello','hello','hello','hello'];
    }
});

after add some CSS, it works fine if I click the button 'add' and 'reset', however, when I click the reset twice, there is no animation. Actually the array is updated but the elements in the $scope.items array doesn't change. How can I add a animation for this situation?

fudy
  • 1,540
  • 5
  • 25
  • 41
  • If you click reset twice is it not just the same array and doesn't change? Could try $scope.items = []; $scope.$apply(); $scope.items = ['hello','hello'] Feels hacky though. Whats the CSS look like? – Lee.Winter Nov 26 '15 at 02:34
  • @fudy, because you are tracking `items` by `$index`, even if `$scope.reset()` is called multiple times to set a new array, as far as `ng-repeat` is concerned, the data has not changed (i.e. same number of items in the new arrays), thus it will not trigger a re-render. If you still want a workaround to force your animations, the gist of this question will help you - https://stackoverflow.com/questions/12595656/angular-js-is-it-possible-to-re-render-ng-repeats-based-on-existing-scope-data – miqh Nov 26 '15 at 03:23

1 Answers1

1

I don't see why you would want the reset to animate every time but this could essential do it

$scope.reset = function() {
    $scope.items = [];
    $timeout(function(){
      $scope.items = ['hello','hello','hello','hello'];
    },200);
}
Lee.Winter
  • 700
  • 9
  • 16