Angular Animation
Objectives
Use the ngAnimate module to add animations to an application.
Describe the properties that ngAnimate adds to directives.
Getting started
Angular supports animations on enter, leave, and move. This is achieved by loading the ngAnimate module, which will automatically add the ng-enter/ng-leave/ng-move classes to your object when it is added/removed.
Animations are only attached to elements that have the following directives:
ngRepeat
enter, leave and move
ngView
enter and leave
ngInclude
enter and leave
ngSwitch
enter and leave
ngIf
enter and leave
ngClass
add and remove (the CSS class(es) present)
ngShow & ngHide
add and remove (the ng-hide class value)
form & ngModel
add and remove (dirty, pristine, valid, invalid & all other validations)
ngMessages
add and remove (ng-active & ng-inactive)
ngMessage
enter and leave
Read the ngAnimate Documentation
Load angular-animate.js
using a <script>
tag. Place this in the <head></head>
tags.
Inject the ngAnimate
dependency into your module.
Defining an animation class
To add an animation to an item simply add a class to that item and define a css animation that requires the item to have both your custom class and ng-enter/ng-leave/ng-move. There are also two additional classes with the -active
postfix that you'll need to define, to represent the final state of the animation.
Documentation can be found here.
Examples
Here's an example of a div that has the ng-if directive. The div will only appear if $scope.bool
is true
. This div has the class fade
so it will fade in and out as the ng-if directive adds and removes the div from the page.
We can also use animation libraries, such as animate.css. Add the CDN link.
Then add these animations via the animate
CSS property. Note that we're using ng-hide
and ng-hide-remove
for the ng-show
directive. These are the animation directives associated with this particular directive.
These CSS-Tricks articles are also great resources when playing with transitions and animations.
Note: Animation classes will only be added to items as they are manipulated using supported directives, like ng-repeat, ng-show, ng-hide, ng-if, etc...
But what about JavaScript?
We can define JavaScript animations as well, similar to how we implemented custom filters.
This block of code attaches an animation to a class and returns an object with the animations we want to run on enter and leave.
For simplicity, we can use jQuery for animations (this isn't too terrible, since we're strictly using jQuery for its animation capabilities). There's also other alternatives for JavaScript animations, like Velocity.js.
Last updated