- AngularJS provides animation service to control the animation in an AngularJS application.
- The package name is ngAnimate present inside ng module.
- It can be used by including angular-resource.min.js script file.
- In this Demo, "We will only get started with AngularJS animation with really simple dumb example".
- AngularJS provides $animate object to be get injected to directives where animation is required.
- $animate object many useful method to manage an animation cycle.However in this post we will only see an example of setClass() method. This method is very basic function which takes the element and class name that need to be bonded.In reality this class does the real animation.
- The main benefit a developer can get from using $animate object is the the promise callback which adds more control over the animation.
- However in this demo we are not going into the promise callback.We will go onto more details on animation callback in a separate post.
- Below code has two directive definition.One of them takes the user supplied string and splits into character array.The other directive takes these character adds the animation CSS classes using $animate service.
<!DOCTYPE html> <html ng-app="myApp"> <head> <meta charset="utf-8"> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular-animate.min.js"></script> <title>AngularJS Animation Example</title> <style> h1 { display: inline-block; } @-webkit-keyframes turnAnimation { to { transform: rotate(1turn); } } .turn { -webkit-animation: turnAnimation 2s infinite; } </style> </head> <body> <text-animation mytext="Sandeep"> </text-animation> <script> var myApp = angular.module("myApp", [ "ngAnimate" ]); myApp.directive("animChar", ["$log", "$animate", function($log, $animate) { return { restrict: "E", replace: true, scope: { mychar: "@" }, template: "<h1>{{mychar}}</h1>", link: function(scope, element, attr) { $animate.addClass(element, 'turn') } }; } ]); myApp.directive("textAnimation", ["$log", "$animate", function($log) { return { restrict: "E", replace: true, scope: { mytext: "@" }, template: "<anim-char ng-repeat='aText in textArray track by $index' mychar='{{aText}}'></anim-char>", link: function(scope, element, attr) { scope.textArray = scope.mytext.split(""); } }; } ]); </script> </body> </html>
- The output of the demo can be found in the below embedded JSBIN link.