Episode 20 of 25

Animations Part 1

Learn how to add CSS animations to AngularJS apps with the ngAnimate module.

AngularJS makes it easy to add animations to your app using CSS transitions and the ngAnimate module.

Setting Up ngAnimate

<!-- Include the animate module -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-animate.min.js"></script>
// Add as a dependency
var app = angular.module('myApp', ['ngAnimate']);

How AngularJS Animations Work

AngularJS automatically adds and removes CSS classes during certain events:

  • ng-enter / ng-leave — when elements are added/removed (ng-repeat, ng-if)
  • ng-hide-add / ng-hide-remove — when ng-show/ng-hide toggles
  • ng-move — when an item moves in ng-repeat

Animate ng-repeat

/* CSS */
.item.ng-enter {
    opacity: 0;
    transition: opacity 0.5s;
}
.item.ng-enter-active {
    opacity: 1;
}

.item.ng-leave {
    opacity: 1;
    transition: opacity 0.5s;
}
.item.ng-leave-active {
    opacity: 0;
}
<li class="item" ng-repeat="todo in todos">
    {{ todo.text }}
</li>

Animate ng-show / ng-hide

.box.ng-hide-add {
    transition: all 0.5s;
    opacity: 1;
    max-height: 200px;
}
.box.ng-hide-add-active {
    opacity: 0;
    max-height: 0;
}
.box.ng-hide-remove {
    transition: all 0.5s;
    opacity: 0;
    max-height: 0;
}
.box.ng-hide-remove-active {
    opacity: 1;
    max-height: 200px;
}

With ngAnimate loaded, these CSS classes are automatically applied whenever the directives trigger changes.