AngularJS Made Easy, by Example – Part 6; Animation

The sixth part of a series on rapidly learning the AngularJS JavaScript framework. Today I illustrate a simple implementation of animations to transition View changes

With all the formalities of an AngularJS application up and running it’s time to finesse certain things; to soften the transitions between Views I would like to have them fade in when the user navigates between pages in my application, rather than just a sudden change.

Back in Part 1 of this series I imported the JavaScript library “angular-animate.min.js”. However up until now I haven’t made use of it, so I’ll need to change my configuration settings. The first line of “app.js” within the “configuration” folder (see Part 2 of this series) needs to be changed from:

var app = angular.module('elearningapp', ['ngRoute']);

to:

var app = angular.module('elearningapp', ['ngRoute', 'ngAnimate']);

to import the animation tools. Then within my main View containers I add a reference to a CSS class called “animationfadein”:

<div data-ng-app ="elearningapp">
	<div data-ng-view="" class="animationfadein"></div>
</div>

In my site’s CSS file I need to add a few classes to bring this all together:

/* AngularJS animations */
.animationfadein.ng-enter
{
	-webkit-transition: 1s linear all;
	-moz-transition: 1s linear all;
	-o-transition: 1s linear all;
	transition: 1s linear all;
}

.animationfadein.ng-enter
{
	opacity: 0;
}

.animationfadein.ng-enter.ng-enter-active
{
	opacity: 1;
}

.animationfadein.ng-leave
{
	opacity: 1;
}

.animationfadein.ng-leave.ng-leave-active
{
	opacity: 0;
}

Voila; that’s all I need. When navigating between Views the current one instantly disappears and the new one fades in over a period of 1 second. I admit with my predilection for Ajax loading there is some further stutter after the fade in, as data is received back from the server and the View updated, but this can be softened with further animations placed on any troublesome HTML elements.