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.

<html ng-app="MyApp">
<head>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-animate/angular-animate.js"></script>
</head>
<body>
...
</body>
</html>

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

var myApp = 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.

<div ng-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.5s linear all;
  transition:0.5s linear all;
}

.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.

Further Readings

I strongly recommend to read the tutorial on Year of Moo on animations in AngularJS and the official documentation itself.

Various built-in timing functions can be used to customize CSS transitions. Please read the specification on timing functions in CSS or the tutorial on cubic bezier curves in CSS on Hongkiat’s blog.

To quickly add more fancy animations, you can include Animate CSS, a predefined set of CSS transitions - ready to use.

References