Last Updated: September 09, 2019
·
2.486K
· lperrin

Selectively disable AngularJS animations

AngularJS 1.2 added a very powerful animation framework. One problem you'll have is that animations will play whether you want it or not. Here's a simple fix.

Parasitic animations? Let's take an example:

<ul class="my-list">
  <li class="my-cell slide" ng-repeat="item in items>
  {{item.title}}
</li>
</ul>

You could decide to animate this with CSS:

.slide.ng-enter {
  animation: slideIn 0.4s ease-in forwards;
}

.slide.ng-leave {
  animation: slideOut 0.4s ease-in forwards;
}

@keyframes slideIn {
  0% { transform: translate3d(-100px, 0, 0); }

  100% { transform: translate3d(0, 0, 0); }
}

@keyframes slideOut {
  0% { transform: translate3d(0, 0, 0); }

  100% { transform: translate3d(-100px, 0, 0); }
}

If you add an item dynamically, the new <li> will appear to come from the left.

Unfortunately, the animation will now play whenever you add new items. If you have an infinite scroll, you'll want to add items without drawing any attention.

What you'd like to do is tell AngularJS to disable animations for the next $digest cycle, when you're about to change your list. There's a very simple way of doing it:

function skipAnimations() {
  $animate.enabled(false);

  $timeout(function () {
    $animate.enabled(true);
  });
}

Now, your infinite scroll would look like:

$scope.loadMore = function () {
  return $http.get(url).success(function (json) {
    $scope.items = $scope.items.concat(json.items);
    skipAnimations();
  });
};

And that's all you need to do!