Adding Animations in AngularJS

Published on Jul 20, 2014

AngularJS is a superheroic web framework written in JavaScript that enables declarative dynamic web views in HTML by extending the HTML vocabulary. One of its great features is automatic data-binding of models and templates. In this blogpost I will discuss how to extend an existing AngularJS application to support animations. A working demo can be found here.

Adding Animations in AngularJS 1.2

Disclaimer: Animations in AngularJS 1.2 are different than in older versions of AngularJS. Please follow the tutorial on Year of Moo to use animations with older versions of AngularJS.

In AngularJS 1.2 animations are not part of the core library anymore, so the animation package has to be included additionally. We install angular-animate via the Bower package manager.

bower install angular-animate

Now, we load the animation package together with the AngularJS core library.

We have to register the animation package in the application, so we add ngAnimate as a dependency in the initialization of the MyApp application.

varmyApp=angular.module('MyApp',['ngAnimate']);

After these steps, we have animation enabled in the application and we can use CSS classes to define the elements that should be animated. The animations itself are declared with CSS transitions.

Animating Elements in ngRepeat

To enable animations in an existing ngRepeat directive, we simply add a CSS class anim.

<divng-repeat="item in items"class="anim">
{{ item.id }}
</div>

We now define the CSS transition of the class anim.

/* you can also define the transition style
on the base class as well (.anim) */.anim.ng-enter,.anim.ng-leave{-webkit-transition:0.5slinearall;transition:0.5slinearall;}.anim.ng-enter,.anim.ng-leave.ng-leave-active{opacity:0;}.anim.ng-leave,.anim.ng-enter.ng-enter-active{opacity:1;}

That’s all we have to do, to add animations to an existing AngularJS application. A working demo of this example can be found here.