2 * @license AngularJS v1.4.3
3 * (c) 2010-2015 Google, Inc. http://angularjs.org
6 (function(window, angular, undefined) {'use strict';
8 /* jshint ignore:start */
9 var noop = angular.noop;
10 var extend = angular.extend;
11 var jqLite = angular.element;
12 var forEach = angular.forEach;
13 var isArray = angular.isArray;
14 var isString = angular.isString;
15 var isObject = angular.isObject;
16 var isUndefined = angular.isUndefined;
17 var isDefined = angular.isDefined;
18 var isFunction = angular.isFunction;
19 var isElement = angular.isElement;
24 var NG_ANIMATE_CLASSNAME = 'ng-animate';
25 var NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren';
27 var isPromiseLike = function(p) {
28 return p && p.then ? true : false;
31 function assertArg(arg, name, reason) {
33 throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
38 function mergeClasses(a,b) {
39 if (!a && !b) return '';
42 if (isArray(a)) a = a.join(' ');
43 if (isArray(b)) b = b.join(' ');
47 function packageStyles(options) {
49 if (options && (options.to || options.from)) {
50 styles.to = options.to;
51 styles.from = options.from;
56 function pendClasses(classes, fix, isPrefix) {
58 classes = isArray(classes)
60 : classes && isString(classes) && classes.length
61 ? classes.split(/\s+/)
63 forEach(classes, function(klass, i) {
64 if (klass && klass.length > 0) {
65 className += (i > 0) ? ' ' : '';
66 className += isPrefix ? fix + klass
73 function removeFromArray(arr, val) {
74 var index = arr.indexOf(val);
80 function stripCommentsFromElement(element) {
81 if (element instanceof jqLite) {
82 switch (element.length) {
88 // there is no point of stripping anything if the element
89 // is the only element within the jqLite wrapper.
90 // (it's important that we retain the element instance.)
91 if (element[0].nodeType === ELEMENT_NODE) {
97 return jqLite(extractElementNode(element));
102 if (element.nodeType === ELEMENT_NODE) {
103 return jqLite(element);
107 function extractElementNode(element) {
108 if (!element[0]) return element;
109 for (var i = 0; i < element.length; i++) {
110 var elm = element[i];
111 if (elm.nodeType == ELEMENT_NODE) {
117 function $$addClass($$jqLite, element, className) {
118 forEach(element, function(elm) {
119 $$jqLite.addClass(elm, className);
123 function $$removeClass($$jqLite, element, className) {
124 forEach(element, function(elm) {
125 $$jqLite.removeClass(elm, className);
129 function applyAnimationClassesFactory($$jqLite) {
130 return function(element, options) {
131 if (options.addClass) {
132 $$addClass($$jqLite, element, options.addClass);
133 options.addClass = null;
135 if (options.removeClass) {
136 $$removeClass($$jqLite, element, options.removeClass);
137 options.removeClass = null;
142 function prepareAnimationOptions(options) {
143 options = options || {};
144 if (!options.$$prepared) {
145 var domOperation = options.domOperation || noop;
146 options.domOperation = function() {
147 options.$$domOperationFired = true;
151 options.$$prepared = true;
156 function applyAnimationStyles(element, options) {
157 applyAnimationFromStyles(element, options);
158 applyAnimationToStyles(element, options);
161 function applyAnimationFromStyles(element, options) {
163 element.css(options.from);
168 function applyAnimationToStyles(element, options) {
170 element.css(options.to);
175 function mergeAnimationOptions(element, target, newOptions) {
176 var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || '');
177 var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || '');
178 var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove);
180 extend(target, newOptions);
182 if (classes.addClass) {
183 target.addClass = classes.addClass;
185 target.addClass = null;
188 if (classes.removeClass) {
189 target.removeClass = classes.removeClass;
191 target.removeClass = null;
197 function resolveElementClasses(existing, toAdd, toRemove) {
199 var REMOVE_CLASS = -1;
202 existing = splitClassesToLookup(existing);
204 toAdd = splitClassesToLookup(toAdd);
205 forEach(toAdd, function(value, key) {
206 flags[key] = ADD_CLASS;
209 toRemove = splitClassesToLookup(toRemove);
210 forEach(toRemove, function(value, key) {
211 flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS;
219 forEach(flags, function(val, klass) {
221 if (val === ADD_CLASS) {
223 allow = !existing[klass];
224 } else if (val === REMOVE_CLASS) {
225 prop = 'removeClass';
226 allow = existing[klass];
229 if (classes[prop].length) {
230 classes[prop] += ' ';
232 classes[prop] += klass;
236 function splitClassesToLookup(classes) {
237 if (isString(classes)) {
238 classes = classes.split(' ');
242 forEach(classes, function(klass) {
243 // sometimes the split leaves empty string values
244 // incase extra spaces were applied to the options
255 function getDomNode(element) {
256 return (element instanceof angular.element) ? element[0] : element;
259 var $$rAFSchedulerFactory = ['$$rAF', function($$rAF) {
263 function scheduler(tasks) {
264 // we make a copy since RAFScheduler mutates the state
265 // of the passed in array variable and this would be difficult
266 // to track down on the outside code
267 tickQueue.push([].concat(tasks));
271 /* waitUntilQuiet does two things:
272 * 1. It will run the FINAL `fn` value only when an uncancelled RAF has passed through
273 * 2. It will delay the next wave of tasks from running until the quiet `fn` has run.
275 * The motivation here is that animation code can request more time from the scheduler
276 * before the next wave runs. This allows for certain DOM properties such as classes to
277 * be resolved in time for the next animation to run.
279 scheduler.waitUntilQuiet = function(fn) {
280 if (cancelFn) cancelFn();
282 cancelFn = $$rAF(function() {
291 function nextTick() {
292 if (!tickQueue.length) return;
294 var updatedQueue = [];
295 for (var i = 0; i < tickQueue.length; i++) {
296 var innerQueue = tickQueue[i];
297 runNextTask(innerQueue);
298 if (innerQueue.length) {
299 updatedQueue.push(innerQueue);
302 tickQueue = updatedQueue;
306 if (!cancelFn) nextTick();
311 function runNextTask(tasks) {
312 var nextTask = tasks.shift();
317 var $$AnimateChildrenDirective = [function() {
318 return function(scope, element, attrs) {
319 var val = attrs.ngAnimateChildren;
320 if (angular.isString(val) && val.length === 0) { //empty attribute
321 element.data(NG_ANIMATE_CHILDREN_DATA, true);
323 attrs.$observe('ngAnimateChildren', function(value) {
324 value = value === 'on' || value === 'true';
325 element.data(NG_ANIMATE_CHILDREN_DATA, value);
337 * The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes
338 * from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT
339 * to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or
340 * directives to create more complex animations that can be purely driven using CSS code.
342 * Note that only browsers that support CSS transitions and/or keyframe animations are capable of
343 * rendering animations triggered via `$animateCss` (bad news for IE9 and lower).
346 * Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that
347 * is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however,
348 * any automatic control over cancelling animations and/or preventing animations from being run on
349 * child elements will not be handled by Angular. For this to work as expected, please use `$animate` to
350 * trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger
353 * The example below shows how we can create a folding animation on an element using `ng-if`:
356 * <!-- notice the `fold-animation` CSS class -->
357 * <div ng-if="onOff" class="fold-animation">
358 * This element will go BOOM
360 * <button ng-click="onOff=true">Fold In</button>
363 * Now we create the **JavaScript animation** that will trigger the CSS transition:
366 * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
368 * enter: function(element, doneFn) {
369 * var height = element[0].offsetHeight;
370 * return $animateCss(element, {
371 * from: { height:'0px' },
372 * to: { height:height + 'px' },
373 * duration: 1 // one second
380 * ## More Advanced Uses
382 * `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks
383 * like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code.
385 * This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation,
386 * applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with
387 * `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order
388 * to provide a working animation that will run in CSS.
390 * The example below showcases a more advanced version of the `.fold-animation` from the example above:
393 * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
395 * enter: function(element, doneFn) {
396 * var height = element[0].offsetHeight;
397 * return $animateCss(element, {
398 * addClass: 'red large-text pulse-twice',
399 * easing: 'ease-out',
400 * from: { height:'0px' },
401 * to: { height:height + 'px' },
402 * duration: 1 // one second
409 * Since we're adding/removing CSS classes then the CSS transition will also pick those up:
412 * /* since a hardcoded duration value of 1 was provided in the JavaScript animation code,
413 * the CSS classes below will be transitioned despite them being defined as regular CSS classes */
414 * .red { background:red; }
415 * .large-text { font-size:20px; }
417 * /* we can also use a keyframe animation and $animateCss will make it work alongside the transition */
419 * animation: 0.5s pulse linear 2;
420 * -webkit-animation: 0.5s pulse linear 2;
424 * from { transform: scale(0.5); }
425 * to { transform: scale(1.5); }
428 * @-webkit-keyframes pulse {
429 * from { -webkit-transform: scale(0.5); }
430 * to { -webkit-transform: scale(1.5); }
434 * Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen.
436 * ## How the Options are handled
438 * `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation
439 * works with the options provided. Say for example we were adding a class that contained a keyframe value and we wanted to also animate some inline
440 * styles using the `from` and `to` properties.
443 * var animator = $animateCss(element, {
444 * from: { background:'red' },
445 * to: { background:'blue' }
451 * .rotating-animation {
452 * animation:0.5s rotate linear;
453 * -webkit-animation:0.5s rotate linear;
456 * @keyframes rotate {
457 * from { transform: rotate(0deg); }
458 * to { transform: rotate(360deg); }
461 * @-webkit-keyframes rotate {
462 * from { -webkit-transform: rotate(0deg); }
463 * to { -webkit-transform: rotate(360deg); }
467 * The missing pieces here are that we do not have a transition set (within the CSS code nor within the `$animateCss` options) and the duration of the animation is
468 * going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition
469 * style matching the duration detected from the keyframe style (which is present in the CSS class that is being added) and then prepare both the transition
470 * and keyframe animations to run in parallel on the element. Then when the animation is underway the provided `from` and `to` CSS styles will be applied
471 * and spread across the transition and keyframe animation.
473 * ## What is returned
475 * `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually
476 * start the animation. All that is going on here is that the element is being prepared for the animation (which means that the generated CSS classes are
477 * added and removed on the element). Once `$animateCss` is called it will return an object with the following properties:
480 * var animator = $animateCss(element, { ... });
483 * Now what do the contents of our `animator` variable look like:
487 * // starts the animation
490 * // ends (aborts) the animation
495 * To actually start the animation we need to run `animation.start()` which will then return a promise that we can hook into to detect when the animation ends.
496 * If we choose not to run the animation then we MUST run `animation.end()` to perform a cleanup on the element (since some CSS classes and stlyes may have been
497 * applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties
498 * and that changing them will not reconfigure the parameters of the animation.
500 * ### runner.done() vs runner.then()
501 * It is documented that `animation.start()` will return a promise object and this is true, however, there is also an additional method available on the
502 * runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**.
503 * Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()`
504 * unless you really need a digest to kick off afterwards.
506 * Keep in mind that, to make this easier, ngAnimate has tweaked the JS animations API to recognize when a runner instance is returned from $animateCss
507 * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code).
508 * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works.
510 * @param {DOMElement} element the element that will be animated
511 * @param {object} options the animation-related options that will be applied during the animation
513 * * `event` - The DOM event (e.g. enter, leave, move). When used, a generated CSS class of `ng-EVENT` and `ng-EVENT-active` will be applied
514 * to the element during the animation. Multiple events can be provided when spaces are used as a separator. (Note that this will not perform any DOM operation.)
515 * * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both).
516 * * `transition` - The raw CSS transition style that will be used (e.g. `1s linear all`).
517 * * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`).
518 * * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation.
519 * * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.
520 * * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation.
521 * * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation.
522 * * `duration` - A number value representing the total duration of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `0`
523 * is provided then the animation will be skipped entirely.
524 * * `delay` - A number value representing the total delay of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `true` is
525 * used then whatever delay value is detected from the CSS classes will be mirrored on the elements styles (e.g. by setting delay true then the style value
526 * of the element will be `transition-delay: DETECTED_VALUE`). Using `true` is useful when you want the CSS classes and inline styles to all share the same
528 * * `stagger` - A numeric time value representing the delay between successively animated elements
529 * ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.})
530 * * `staggerIndex` - The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item in the stagger; therefore when a
531 * `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`)
532 * `applyClassesEarly` - Whether or not the classes being added or removed will be used when detecting the animation. This is set by `$animate` when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time. (Note that this will prevent any transitions from occuring on the classes being added and removed.)
534 * @return {object} an object with start and end methods and details about the animation.
536 * * `start` - The method to start the animation. This will return a `Promise` when called.
537 * * `end` - This method will cancel the animation and remove all applied CSS classes and styles.
540 // Detect proper transitionend/animationend event names.
541 var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;
543 // If unprefixed events are not supported but webkit-prefixed are, use the latter.
544 // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.
545 // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`
546 // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.
547 // Register both events in case `window.onanimationend` is not supported because of that,
548 // do the same for `transitionend` as Safari is likely to exhibit similar behavior.
549 // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit
550 // therefore there is no reason to test anymore for other vendor prefixes:
551 // http://caniuse.com/#search=transition
552 if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) {
553 CSS_PREFIX = '-webkit-';
554 TRANSITION_PROP = 'WebkitTransition';
555 TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
557 TRANSITION_PROP = 'transition';
558 TRANSITIONEND_EVENT = 'transitionend';
561 if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) {
562 CSS_PREFIX = '-webkit-';
563 ANIMATION_PROP = 'WebkitAnimation';
564 ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';
566 ANIMATION_PROP = 'animation';
567 ANIMATIONEND_EVENT = 'animationend';
570 var DURATION_KEY = 'Duration';
571 var PROPERTY_KEY = 'Property';
572 var DELAY_KEY = 'Delay';
573 var TIMING_KEY = 'TimingFunction';
574 var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';
575 var ANIMATION_PLAYSTATE_KEY = 'PlayState';
576 var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
577 var CLOSING_TIME_BUFFER = 1.5;
578 var ONE_SECOND = 1000;
581 var SAFE_FAST_FORWARD_DURATION_VALUE = 9999;
583 var ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY;
584 var ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY;
586 var TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY;
587 var TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY;
589 var DETECT_CSS_PROPERTIES = {
590 transitionDuration: TRANSITION_DURATION_PROP,
591 transitionDelay: TRANSITION_DELAY_PROP,
592 transitionProperty: TRANSITION_PROP + PROPERTY_KEY,
593 animationDuration: ANIMATION_DURATION_PROP,
594 animationDelay: ANIMATION_DELAY_PROP,
595 animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY
598 var DETECT_STAGGER_CSS_PROPERTIES = {
599 transitionDuration: TRANSITION_DURATION_PROP,
600 transitionDelay: TRANSITION_DELAY_PROP,
601 animationDuration: ANIMATION_DURATION_PROP,
602 animationDelay: ANIMATION_DELAY_PROP
605 function computeCssStyles($window, element, properties) {
606 var styles = Object.create(null);
607 var detectedStyles = $window.getComputedStyle(element) || {};
608 forEach(properties, function(formalStyleName, actualStyleName) {
609 var val = detectedStyles[formalStyleName];
611 var c = val.charAt(0);
613 // only numerical-based values have a negative sign or digit as the first value
614 if (c === '-' || c === '+' || c >= 0) {
615 val = parseMaxTime(val);
618 // by setting this to null in the event that the delay is not set or is set directly as 0
619 // then we can still allow for zegative values to be used later on and not mistake this
620 // value for being greater than any other negative value.
624 styles[actualStyleName] = val;
631 function parseMaxTime(str) {
633 var values = str.split(/\s*,\s*/);
634 forEach(values, function(value) {
635 // it's always safe to consider only second values and omit `ms` values since
636 // getComputedStyle will always handle the conversion for us
637 if (value.charAt(value.length - 1) == 's') {
638 value = value.substring(0, value.length - 1);
640 value = parseFloat(value) || 0;
641 maxValue = maxValue ? Math.max(value, maxValue) : value;
646 function truthyTimingValue(val) {
647 return val === 0 || val != null;
650 function getCssTransitionDurationStyle(duration, applyOnlyDuration) {
651 var style = TRANSITION_PROP;
652 var value = duration + 's';
653 if (applyOnlyDuration) {
654 style += DURATION_KEY;
656 value += ' linear all';
658 return [style, value];
661 function getCssKeyframeDurationStyle(duration) {
662 return [ANIMATION_DURATION_PROP, duration + 's'];
665 function getCssDelayStyle(delay, isKeyframeAnimation) {
666 var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP;
667 return [prop, delay + 's'];
670 function blockTransitions(node, duration) {
671 // we use a negative delay value since it performs blocking
672 // yet it doesn't kill any existing transitions running on the
673 // same element which makes this safe for class-based animations
674 var value = duration ? '-' + duration + 's' : '';
675 applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]);
676 return [TRANSITION_DELAY_PROP, value];
679 function blockKeyframeAnimations(node, applyBlock) {
680 var value = applyBlock ? 'paused' : '';
681 var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY;
682 applyInlineStyle(node, [key, value]);
686 function applyInlineStyle(node, styleTuple) {
687 var prop = styleTuple[0];
688 var value = styleTuple[1];
689 node.style[prop] = value;
692 function createLocalCacheLookup() {
693 var cache = Object.create(null);
696 cache = Object.create(null);
699 count: function(key) {
700 var entry = cache[key];
701 return entry ? entry.total : 0;
705 var entry = cache[key];
706 return entry && entry.value;
709 put: function(key, value) {
711 cache[key] = { total: 1, value: value };
719 var $AnimateCssProvider = ['$animateProvider', function($animateProvider) {
720 var gcsLookup = createLocalCacheLookup();
721 var gcsStaggerLookup = createLocalCacheLookup();
723 this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout',
724 '$document', '$sniffer', '$$rAFScheduler',
725 function($window, $$jqLite, $$AnimateRunner, $timeout,
726 $document, $sniffer, $$rAFScheduler) {
728 var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
730 var parentCounter = 0;
731 function gcsHashFn(node, extraClasses) {
732 var KEY = "$$ngAnimateParentKey";
733 var parentNode = node.parentNode;
734 var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter);
735 return parentID + '-' + node.getAttribute('class') + '-' + extraClasses;
738 function computeCachedCssStyles(node, className, cacheKey, properties) {
739 var timings = gcsLookup.get(cacheKey);
742 timings = computeCssStyles($window, node, properties);
743 if (timings.animationIterationCount === 'infinite') {
744 timings.animationIterationCount = 1;
748 // we keep putting this in multiple times even though the value and the cacheKey are the same
749 // because we're keeping an interal tally of how many duplicate animations are detected.
750 gcsLookup.put(cacheKey, timings);
754 function computeCachedCssStaggerStyles(node, className, cacheKey, properties) {
757 // if we have one or more existing matches of matching elements
758 // containing the same parent + CSS styles (which is how cacheKey works)
759 // then staggering is possible
760 if (gcsLookup.count(cacheKey) > 0) {
761 stagger = gcsStaggerLookup.get(cacheKey);
764 var staggerClassName = pendClasses(className, '-stagger');
766 $$jqLite.addClass(node, staggerClassName);
768 stagger = computeCssStyles($window, node, properties);
770 // force the conversion of a null value to zero incase not set
771 stagger.animationDuration = Math.max(stagger.animationDuration, 0);
772 stagger.transitionDuration = Math.max(stagger.transitionDuration, 0);
774 $$jqLite.removeClass(node, staggerClassName);
776 gcsStaggerLookup.put(cacheKey, stagger);
780 return stagger || {};
783 var bod = getDomNode($document).body;
784 var rafWaitQueue = [];
785 function waitUntilQuiet(callback) {
786 rafWaitQueue.push(callback);
787 $$rAFScheduler.waitUntilQuiet(function() {
789 gcsStaggerLookup.flush();
791 //the line below will force the browser to perform a repaint so
792 //that all the animated elements within the animation frame will
793 //be properly updated and drawn on screen. This is required to
794 //ensure that the preparation animation is properly flushed so that
795 //the active state picks up from there. DO NOT REMOVE THIS LINE.
796 //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
797 //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
798 //WILL TAKE YEARS AWAY FROM YOUR LIFE.
799 var width = bod.offsetWidth + 1;
801 // we use a for loop to ensure that if the queue is changed
802 // during this looping then it will consider new requests
803 for (var i = 0; i < rafWaitQueue.length; i++) {
804 rafWaitQueue[i](width);
806 rafWaitQueue.length = 0;
812 function computeTimings(node, className, cacheKey) {
813 var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES);
814 var aD = timings.animationDelay;
815 var tD = timings.transitionDelay;
816 timings.maxDelay = aD && tD
819 timings.maxDuration = Math.max(
820 timings.animationDuration * timings.animationIterationCount,
821 timings.transitionDuration);
826 function init(element, options) {
827 var node = getDomNode(element);
828 if (!node || !node.parentNode) {
829 return closeAndReturnNoopAnimator();
832 options = prepareAnimationOptions(options);
834 var temporaryStyles = [];
835 var classes = element.attr('class');
836 var styles = packageStyles(options);
839 var animationCompleted;
847 if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) {
848 return closeAndReturnNoopAnimator();
851 var method = options.event && isArray(options.event)
852 ? options.event.join(' ')
855 var isStructural = method && options.structural;
856 var structuralClassName = '';
857 var addRemoveClassName = '';
860 structuralClassName = pendClasses(method, 'ng-', true);
862 structuralClassName = method;
865 if (options.addClass) {
866 addRemoveClassName += pendClasses(options.addClass, '-add');
869 if (options.removeClass) {
870 if (addRemoveClassName.length) {
871 addRemoveClassName += ' ';
873 addRemoveClassName += pendClasses(options.removeClass, '-remove');
876 // there may be a situation where a structural animation is combined together
877 // with CSS classes that need to resolve before the animation is computed.
878 // However this means that there is no explicit CSS code to block the animation
879 // from happening (by setting 0s none in the class name). If this is the case
880 // we need to apply the classes before the first rAF so we know to continue if
881 // there actually is a detected transition or keyframe animation
882 if (options.applyClassesEarly && addRemoveClassName.length) {
883 applyAnimationClasses(element, options);
884 addRemoveClassName = '';
887 var setupClasses = [structuralClassName, addRemoveClassName].join(' ').trim();
888 var fullClassName = classes + ' ' + setupClasses;
889 var activeClasses = pendClasses(setupClasses, '-active');
890 var hasToStyles = styles.to && Object.keys(styles.to).length > 0;
891 var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0;
893 // there is no way we can trigger an animation if no styles and
894 // no classes are being applied which would then trigger a transition,
895 // unless there a is raw keyframe value that is applied to the element.
896 if (!containsKeyframeAnimation
899 return closeAndReturnNoopAnimator();
902 var cacheKey, stagger;
903 if (options.stagger > 0) {
904 var staggerVal = parseFloat(options.stagger);
906 transitionDelay: staggerVal,
907 animationDelay: staggerVal,
908 transitionDuration: 0,
912 cacheKey = gcsHashFn(node, fullClassName);
913 stagger = computeCachedCssStaggerStyles(node, setupClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES);
916 $$jqLite.addClass(element, setupClasses);
918 var applyOnlyDuration;
920 if (options.transitionStyle) {
921 var transitionStyle = [TRANSITION_PROP, options.transitionStyle];
922 applyInlineStyle(node, transitionStyle);
923 temporaryStyles.push(transitionStyle);
926 if (options.duration >= 0) {
927 applyOnlyDuration = node.style[TRANSITION_PROP].length > 0;
928 var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration);
930 // we set the duration so that it will be picked up by getComputedStyle later
931 applyInlineStyle(node, durationStyle);
932 temporaryStyles.push(durationStyle);
935 if (options.keyframeStyle) {
936 var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle];
937 applyInlineStyle(node, keyframeStyle);
938 temporaryStyles.push(keyframeStyle);
941 var itemIndex = stagger
942 ? options.staggerIndex >= 0
943 ? options.staggerIndex
944 : gcsLookup.count(cacheKey)
947 var isFirst = itemIndex === 0;
949 // this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY
950 // without causing any combination of transitions to kick in. By adding a negative delay value
951 // it forces the setup class' transition to end immediately. We later then remove the negative
952 // transition delay to allow for the transition to naturally do it's thing. The beauty here is
953 // that if there is no transition defined then nothing will happen and this will also allow
954 // other transitions to be stacked on top of each other without any chopping them out.
956 blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE);
959 var timings = computeTimings(node, fullClassName, cacheKey);
960 var relativeDelay = timings.maxDelay;
961 maxDelay = Math.max(relativeDelay, 0);
962 maxDuration = timings.maxDuration;
965 flags.hasTransitions = timings.transitionDuration > 0;
966 flags.hasAnimations = timings.animationDuration > 0;
967 flags.hasTransitionAll = flags.hasTransitions && timings.transitionProperty == 'all';
968 flags.applyTransitionDuration = hasToStyles && (
969 (flags.hasTransitions && !flags.hasTransitionAll)
970 || (flags.hasAnimations && !flags.hasTransitions));
971 flags.applyAnimationDuration = options.duration && flags.hasAnimations;
972 flags.applyTransitionDelay = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions);
973 flags.applyAnimationDelay = truthyTimingValue(options.delay) && flags.hasAnimations;
974 flags.recalculateTimingStyles = addRemoveClassName.length > 0;
976 if (flags.applyTransitionDuration || flags.applyAnimationDuration) {
977 maxDuration = options.duration ? parseFloat(options.duration) : maxDuration;
979 if (flags.applyTransitionDuration) {
980 flags.hasTransitions = true;
981 timings.transitionDuration = maxDuration;
982 applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0;
983 temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration));
986 if (flags.applyAnimationDuration) {
987 flags.hasAnimations = true;
988 timings.animationDuration = maxDuration;
989 temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration));
993 if (maxDuration === 0 && !flags.recalculateTimingStyles) {
994 return closeAndReturnNoopAnimator();
997 // we need to recalculate the delay value since we used a pre-emptive negative
998 // delay value and the delay value is required for the final event checking. This
999 // property will ensure that this will happen after the RAF phase has passed.
1000 if (options.duration == null && timings.transitionDuration > 0) {
1001 flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst;
1004 maxDelayTime = maxDelay * ONE_SECOND;
1005 maxDurationTime = maxDuration * ONE_SECOND;
1006 if (!options.skipBlocking) {
1007 flags.blockTransition = timings.transitionDuration > 0;
1008 flags.blockKeyframeAnimation = timings.animationDuration > 0 &&
1009 stagger.animationDelay > 0 &&
1010 stagger.animationDuration === 0;
1013 applyAnimationFromStyles(element, options);
1014 if (!flags.blockTransition) {
1015 blockTransitions(node, false);
1018 applyBlocking(maxDuration);
1020 // TODO(matsko): for 1.5 change this code to have an animator object for better debugging
1022 $$willAnimate: true,
1025 if (animationClosed) return;
1030 resume: null, //this will be set during the start() phase
1034 runner = new $$AnimateRunner(runnerHost);
1036 waitUntilQuiet(start);
1038 // we don't have access to pause/resume the animation
1039 // since it hasn't run yet. AnimateRunner will therefore
1040 // set noop functions for resume and pause and they will
1041 // later be overridden once the animation is triggered
1050 function cancelFn() {
1054 function close(rejected) { // jshint ignore:line
1055 // if the promise has been called already then we shouldn't close
1056 // the animation again
1057 if (animationClosed || (animationCompleted && animationPaused)) return;
1058 animationClosed = true;
1059 animationPaused = false;
1061 $$jqLite.removeClass(element, setupClasses);
1062 $$jqLite.removeClass(element, activeClasses);
1064 blockKeyframeAnimations(node, false);
1065 blockTransitions(node, false);
1067 forEach(temporaryStyles, function(entry) {
1068 // There is only one way to remove inline style properties entirely from elements.
1069 // By using `removeProperty` this works, but we need to convert camel-cased CSS
1070 // styles down to hyphenated values.
1071 node.style[entry[0]] = '';
1074 applyAnimationClasses(element, options);
1075 applyAnimationStyles(element, options);
1077 // the reason why we have this option is to allow a synchronous closing callback
1078 // that is fired as SOON as the animation ends (when the CSS is removed) or if
1079 // the animation never takes off at all. A good example is a leave animation since
1080 // the element must be removed just after the animation is over or else the element
1081 // will appear on screen for one animation frame causing an overbearing flicker.
1082 if (options.onDone) {
1086 // if the preparation function fails then the promise is not setup
1088 runner.complete(!rejected);
1092 function applyBlocking(duration) {
1093 if (flags.blockTransition) {
1094 blockTransitions(node, duration);
1097 if (flags.blockKeyframeAnimation) {
1098 blockKeyframeAnimations(node, !!duration);
1102 function closeAndReturnNoopAnimator() {
1103 runner = new $$AnimateRunner({
1111 $$willAnimate: false,
1120 if (animationClosed) return;
1121 if (!node.parentNode) {
1126 var startTime, events = [];
1128 // even though we only pause keyframe animations here the pause flag
1129 // will still happen when transitions are used. Only the transition will
1130 // not be paused since that is not possible. If the animation ends when
1131 // paused then it will not complete until unpaused or cancelled.
1132 var playPause = function(playAnimation) {
1133 if (!animationCompleted) {
1134 animationPaused = !playAnimation;
1135 if (timings.animationDuration) {
1136 var value = blockKeyframeAnimations(node, animationPaused);
1138 ? temporaryStyles.push(value)
1139 : removeFromArray(temporaryStyles, value);
1141 } else if (animationPaused && playAnimation) {
1142 animationPaused = false;
1147 // checking the stagger duration prevents an accidently cascade of the CSS delay style
1148 // being inherited from the parent. If the transition duration is zero then we can safely
1149 // rely that the delay value is an intential stagger delay style.
1150 var maxStagger = itemIndex > 0
1151 && ((timings.transitionDuration && stagger.transitionDuration === 0) ||
1152 (timings.animationDuration && stagger.animationDuration === 0))
1153 && Math.max(stagger.animationDelay, stagger.transitionDelay);
1155 $timeout(triggerAnimationStart,
1156 Math.floor(maxStagger * itemIndex * ONE_SECOND),
1159 triggerAnimationStart();
1162 // this will decorate the existing promise runner with pause/resume methods
1163 runnerHost.resume = function() {
1167 runnerHost.pause = function() {
1171 function triggerAnimationStart() {
1172 // just incase a stagger animation kicks in when the animation
1173 // itself was cancelled entirely
1174 if (animationClosed) return;
1176 applyBlocking(false);
1178 forEach(temporaryStyles, function(entry) {
1180 var value = entry[1];
1181 node.style[key] = value;
1184 applyAnimationClasses(element, options);
1185 $$jqLite.addClass(element, activeClasses);
1187 if (flags.recalculateTimingStyles) {
1188 fullClassName = node.className + ' ' + setupClasses;
1189 cacheKey = gcsHashFn(node, fullClassName);
1191 timings = computeTimings(node, fullClassName, cacheKey);
1192 relativeDelay = timings.maxDelay;
1193 maxDelay = Math.max(relativeDelay, 0);
1194 maxDuration = timings.maxDuration;
1196 if (maxDuration === 0) {
1201 flags.hasTransitions = timings.transitionDuration > 0;
1202 flags.hasAnimations = timings.animationDuration > 0;
1205 if (flags.applyTransitionDelay || flags.applyAnimationDelay) {
1206 relativeDelay = typeof options.delay !== "boolean" && truthyTimingValue(options.delay)
1207 ? parseFloat(options.delay)
1210 maxDelay = Math.max(relativeDelay, 0);
1213 if (flags.applyTransitionDelay) {
1214 timings.transitionDelay = relativeDelay;
1215 delayStyle = getCssDelayStyle(relativeDelay);
1216 temporaryStyles.push(delayStyle);
1217 node.style[delayStyle[0]] = delayStyle[1];
1220 if (flags.applyAnimationDelay) {
1221 timings.animationDelay = relativeDelay;
1222 delayStyle = getCssDelayStyle(relativeDelay, true);
1223 temporaryStyles.push(delayStyle);
1224 node.style[delayStyle[0]] = delayStyle[1];
1228 maxDelayTime = maxDelay * ONE_SECOND;
1229 maxDurationTime = maxDuration * ONE_SECOND;
1231 if (options.easing) {
1232 var easeProp, easeVal = options.easing;
1233 if (flags.hasTransitions) {
1234 easeProp = TRANSITION_PROP + TIMING_KEY;
1235 temporaryStyles.push([easeProp, easeVal]);
1236 node.style[easeProp] = easeVal;
1238 if (flags.hasAnimations) {
1239 easeProp = ANIMATION_PROP + TIMING_KEY;
1240 temporaryStyles.push([easeProp, easeVal]);
1241 node.style[easeProp] = easeVal;
1245 if (timings.transitionDuration) {
1246 events.push(TRANSITIONEND_EVENT);
1249 if (timings.animationDuration) {
1250 events.push(ANIMATIONEND_EVENT);
1253 startTime = Date.now();
1254 element.on(events.join(' '), onAnimationProgress);
1255 $timeout(onAnimationExpired, maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime);
1257 applyAnimationToStyles(element, options);
1260 function onAnimationExpired() {
1261 // although an expired animation is a failed animation, getting to
1262 // this outcome is very easy if the CSS code screws up. Therefore we
1263 // should still continue normally as if the animation completed correctly.
1267 function onAnimationProgress(event) {
1268 event.stopPropagation();
1269 var ev = event.originalEvent || event;
1270 var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now();
1272 /* Firefox (or possibly just Gecko) likes to not round values up
1273 * when a ms measurement is used for the animation */
1274 var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));
1276 /* $manualTimeStamp is a mocked timeStamp value which is set
1277 * within browserTrigger(). This is only here so that tests can
1278 * mock animations properly. Real events fallback to event.timeStamp,
1279 * or, if they don't, then a timeStamp is automatically created for them.
1280 * We're checking to see if the timeStamp surpasses the expected delay,
1281 * but we're using elapsedTime instead of the timeStamp on the 2nd
1282 * pre-condition since animations sometimes close off early */
1283 if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
1284 // we set this flag to ensure that if the transition is paused then, when resumed,
1285 // the animation will automatically close itself since transitions cannot be paused.
1286 animationCompleted = true;
1295 var $$AnimateCssDriverProvider = ['$$animationProvider', function($$animationProvider) {
1296 $$animationProvider.drivers.push('$$animateCssDriver');
1298 var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim';
1299 var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor';
1301 var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out';
1302 var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in';
1304 this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$document', '$sniffer',
1305 function($animateCss, $rootScope, $$AnimateRunner, $rootElement, $document, $sniffer) {
1307 // only browsers that support these properties can render animations
1308 if (!$sniffer.animations && !$sniffer.transitions) return noop;
1310 var bodyNode = getDomNode($document).body;
1311 var rootNode = getDomNode($rootElement);
1313 var rootBodyElement = jqLite(bodyNode.parentNode === rootNode ? bodyNode : rootNode);
1315 return function initDriverFn(animationDetails) {
1316 return animationDetails.from && animationDetails.to
1317 ? prepareFromToAnchorAnimation(animationDetails.from,
1318 animationDetails.to,
1319 animationDetails.classes,
1320 animationDetails.anchors)
1321 : prepareRegularAnimation(animationDetails);
1324 function filterCssClasses(classes) {
1325 //remove all the `ng-` stuff
1326 return classes.replace(/\bng-\S+\b/g, '');
1329 function getUniqueValues(a, b) {
1330 if (isString(a)) a = a.split(' ');
1331 if (isString(b)) b = b.split(' ');
1332 return a.filter(function(val) {
1333 return b.indexOf(val) === -1;
1337 function prepareAnchoredAnimation(classes, outAnchor, inAnchor) {
1338 var clone = jqLite(getDomNode(outAnchor).cloneNode(true));
1339 var startingClasses = filterCssClasses(getClassVal(clone));
1341 outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
1342 inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
1344 clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME);
1346 rootBodyElement.append(clone);
1348 var animatorIn, animatorOut = prepareOutAnimation();
1350 // the user may not end up using the `out` animation and
1351 // only making use of the `in` animation or vice-versa.
1352 // In either case we should allow this and not assume the
1353 // animation is over unless both animations are not used.
1355 animatorIn = prepareInAnimation();
1361 var startingAnimator = animatorOut || animatorIn;
1367 var currentAnimation = startingAnimator.start();
1368 currentAnimation.done(function() {
1369 currentAnimation = null;
1371 animatorIn = prepareInAnimation();
1373 currentAnimation = animatorIn.start();
1374 currentAnimation.done(function() {
1375 currentAnimation = null;
1379 return currentAnimation;
1382 // in the event that there is no `in` animation
1387 runner = new $$AnimateRunner({
1395 if (currentAnimation) {
1396 currentAnimation.end();
1402 function calculateAnchorStyles(anchor) {
1405 var coords = getDomNode(anchor).getBoundingClientRect();
1407 // we iterate directly since safari messes up and doesn't return
1408 // all the keys for the coods object when iterated
1409 forEach(['width','height','top','left'], function(key) {
1410 var value = coords[key];
1413 value += bodyNode.scrollTop;
1416 value += bodyNode.scrollLeft;
1419 styles[key] = Math.floor(value) + 'px';
1424 function prepareOutAnimation() {
1425 var animator = $animateCss(clone, {
1426 addClass: NG_OUT_ANCHOR_CLASS_NAME,
1428 from: calculateAnchorStyles(outAnchor)
1431 // read the comment within `prepareRegularAnimation` to understand
1432 // why this check is necessary
1433 return animator.$$willAnimate ? animator : null;
1436 function getClassVal(element) {
1437 return element.attr('class') || '';
1440 function prepareInAnimation() {
1441 var endingClasses = filterCssClasses(getClassVal(inAnchor));
1442 var toAdd = getUniqueValues(endingClasses, startingClasses);
1443 var toRemove = getUniqueValues(startingClasses, endingClasses);
1445 var animator = $animateCss(clone, {
1446 to: calculateAnchorStyles(inAnchor),
1447 addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd,
1448 removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove,
1452 // read the comment within `prepareRegularAnimation` to understand
1453 // why this check is necessary
1454 return animator.$$willAnimate ? animator : null;
1459 outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
1460 inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
1464 function prepareFromToAnchorAnimation(from, to, classes, anchors) {
1465 var fromAnimation = prepareRegularAnimation(from);
1466 var toAnimation = prepareRegularAnimation(to);
1468 var anchorAnimations = [];
1469 forEach(anchors, function(anchor) {
1470 var outElement = anchor['out'];
1471 var inElement = anchor['in'];
1472 var animator = prepareAnchoredAnimation(classes, outElement, inElement);
1474 anchorAnimations.push(animator);
1478 // no point in doing anything when there are no elements to animate
1479 if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return;
1483 var animationRunners = [];
1485 if (fromAnimation) {
1486 animationRunners.push(fromAnimation.start());
1490 animationRunners.push(toAnimation.start());
1493 forEach(anchorAnimations, function(animation) {
1494 animationRunners.push(animation.start());
1497 var runner = new $$AnimateRunner({
1499 cancel: endFn // CSS-driven animations cannot be cancelled, only ended
1502 $$AnimateRunner.all(animationRunners, function(status) {
1503 runner.complete(status);
1509 forEach(animationRunners, function(runner) {
1517 function prepareRegularAnimation(animationDetails) {
1518 var element = animationDetails.element;
1519 var options = animationDetails.options || {};
1521 if (animationDetails.structural) {
1522 // structural animations ensure that the CSS classes are always applied
1523 // before the detection starts.
1524 options.structural = options.applyClassesEarly = true;
1526 // we special case the leave animation since we want to ensure that
1527 // the element is removed as soon as the animation is over. Otherwise
1528 // a flicker might appear or the element may not be removed at all
1529 options.event = animationDetails.event;
1530 if (options.event === 'leave') {
1531 options.onDone = options.domOperation;
1534 options.event = null;
1537 var animator = $animateCss(element, options);
1539 // the driver lookup code inside of $$animation attempts to spawn a
1540 // driver one by one until a driver returns a.$$willAnimate animator object.
1541 // $animateCss will always return an object, however, it will pass in
1542 // a flag as a hint as to whether an animation was detected or not
1543 return animator.$$willAnimate ? animator : null;
1548 // TODO(matsko): use caching here to speed things up for detection
1549 // TODO(matsko): add documentation
1552 var $$AnimateJsProvider = ['$animateProvider', function($animateProvider) {
1553 this.$get = ['$injector', '$$AnimateRunner', '$$rAFMutex', '$$jqLite',
1554 function($injector, $$AnimateRunner, $$rAFMutex, $$jqLite) {
1556 var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
1557 // $animateJs(element, 'enter');
1558 return function(element, event, classes, options) {
1559 // the `classes` argument is optional and if it is not used
1560 // then the classes will be resolved from the element's className
1561 // property as well as options.addClass/options.removeClass.
1562 if (arguments.length === 3 && isObject(classes)) {
1567 options = prepareAnimationOptions(options);
1569 classes = element.attr('class') || '';
1570 if (options.addClass) {
1571 classes += ' ' + options.addClass;
1573 if (options.removeClass) {
1574 classes += ' ' + options.removeClass;
1578 var classesToAdd = options.addClass;
1579 var classesToRemove = options.removeClass;
1581 // the lookupAnimations function returns a series of animation objects that are
1582 // matched up with one or more of the CSS classes. These animation objects are
1583 // defined via the module.animation factory function. If nothing is detected then
1584 // we don't return anything which then makes $animation query the next driver.
1585 var animations = lookupAnimations(classes);
1587 if (animations.length) {
1588 var afterFn, beforeFn;
1589 if (event == 'leave') {
1591 afterFn = 'afterLeave'; // TODO(matsko): get rid of this
1593 beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1);
1597 if (event !== 'enter' && event !== 'move') {
1598 before = packageAnimations(element, event, options, animations, beforeFn);
1600 after = packageAnimations(element, event, options, animations, afterFn);
1603 // no matching animations
1604 if (!before && !after) return;
1606 function applyOptions() {
1607 options.domOperation();
1608 applyAnimationClasses(element, options);
1613 var closeActiveAnimations;
1617 chain.push(function(fn) {
1618 closeActiveAnimations = before(fn);
1623 chain.push(function(fn) {
1632 chain.push(function(fn) {
1633 closeActiveAnimations = after(fn);
1637 var animationClosed = false;
1638 var runner = new $$AnimateRunner({
1642 cancel: function() {
1643 endAnimations(true);
1647 $$AnimateRunner.chain(chain, onComplete);
1650 function onComplete(success) {
1651 animationClosed = true;
1653 applyAnimationStyles(element, options);
1654 runner.complete(success);
1657 function endAnimations(cancelled) {
1658 if (!animationClosed) {
1659 (closeActiveAnimations || noop)(cancelled);
1660 onComplete(cancelled);
1666 function executeAnimationFn(fn, element, event, options, onDone) {
1670 args = [element, options.from, options.to, onDone];
1674 args = [element, classesToAdd, classesToRemove, onDone];
1678 args = [element, classesToAdd, onDone];
1682 args = [element, classesToRemove, onDone];
1686 args = [element, onDone];
1692 var value = fn.apply(fn, args);
1694 if (isFunction(value.start)) {
1695 value = value.start();
1698 if (value instanceof $$AnimateRunner) {
1700 } else if (isFunction(value)) {
1701 // optional onEnd / onCancel callback
1709 function groupEventedAnimations(element, event, options, animations, fnName) {
1710 var operations = [];
1711 forEach(animations, function(ani) {
1712 var animation = ani[fnName];
1713 if (!animation) return;
1715 // note that all of these animations will run in parallel
1716 operations.push(function() {
1720 var resolved = false;
1721 var onAnimationComplete = function(rejected) {
1724 (endProgressCb || noop)(rejected);
1725 runner.complete(!rejected);
1729 runner = new $$AnimateRunner({
1731 onAnimationComplete();
1733 cancel: function() {
1734 onAnimationComplete(true);
1738 endProgressCb = executeAnimationFn(animation, element, event, options, function(result) {
1739 var cancelled = result === false;
1740 onAnimationComplete(cancelled);
1750 function packageAnimations(element, event, options, animations, fnName) {
1751 var operations = groupEventedAnimations(element, event, options, animations, fnName);
1752 if (operations.length === 0) {
1754 if (fnName === 'beforeSetClass') {
1755 a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass');
1756 b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass');
1757 } else if (fnName === 'setClass') {
1758 a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass');
1759 b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass');
1763 operations = operations.concat(a);
1766 operations = operations.concat(b);
1770 if (operations.length === 0) return;
1772 // TODO(matsko): add documentation
1773 return function startAnimation(callback) {
1775 if (operations.length) {
1776 forEach(operations, function(animateFn) {
1777 runners.push(animateFn());
1781 runners.length ? $$AnimateRunner.all(runners, callback) : callback();
1783 return function endFn(reject) {
1784 forEach(runners, function(runner) {
1785 reject ? runner.cancel() : runner.end();
1792 function lookupAnimations(classes) {
1793 classes = isArray(classes) ? classes : classes.split(' ');
1794 var matches = [], flagMap = {};
1795 for (var i=0; i < classes.length; i++) {
1796 var klass = classes[i],
1797 animationFactory = $animateProvider.$$registeredAnimations[klass];
1798 if (animationFactory && !flagMap[klass]) {
1799 matches.push($injector.get(animationFactory));
1800 flagMap[klass] = true;
1808 var $$AnimateJsDriverProvider = ['$$animationProvider', function($$animationProvider) {
1809 $$animationProvider.drivers.push('$$animateJsDriver');
1810 this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) {
1811 return function initDriverFn(animationDetails) {
1812 if (animationDetails.from && animationDetails.to) {
1813 var fromAnimation = prepareAnimation(animationDetails.from);
1814 var toAnimation = prepareAnimation(animationDetails.to);
1815 if (!fromAnimation && !toAnimation) return;
1819 var animationRunners = [];
1821 if (fromAnimation) {
1822 animationRunners.push(fromAnimation.start());
1826 animationRunners.push(toAnimation.start());
1829 $$AnimateRunner.all(animationRunners, done);
1831 var runner = new $$AnimateRunner({
1832 end: endFnFactory(),
1833 cancel: endFnFactory()
1838 function endFnFactory() {
1840 forEach(animationRunners, function(runner) {
1841 // at this point we cannot cancel animations for groups just yet. 1.5+
1847 function done(status) {
1848 runner.complete(status);
1853 return prepareAnimation(animationDetails);
1857 function prepareAnimation(animationDetails) {
1858 // TODO(matsko): make sure to check for grouped animations and delegate down to normal animations
1859 var element = animationDetails.element;
1860 var event = animationDetails.event;
1861 var options = animationDetails.options;
1862 var classes = animationDetails.classes;
1863 return $$animateJs(element, event, classes, options);
1868 var NG_ANIMATE_ATTR_NAME = 'data-ng-animate';
1869 var NG_ANIMATE_PIN_DATA = '$ngAnimatePin';
1870 var $$AnimateQueueProvider = ['$animateProvider', function($animateProvider) {
1871 var PRE_DIGEST_STATE = 1;
1872 var RUNNING_STATE = 2;
1874 var rules = this.rules = {
1880 function isAllowed(ruleType, element, currentAnimation, previousAnimation) {
1881 return rules[ruleType].some(function(fn) {
1882 return fn(element, currentAnimation, previousAnimation);
1886 function hasAnimationClasses(options, and) {
1887 options = options || {};
1888 var a = (options.addClass || '').length > 0;
1889 var b = (options.removeClass || '').length > 0;
1890 return and ? a && b : a || b;
1893 rules.join.push(function(element, newAnimation, currentAnimation) {
1894 // if the new animation is class-based then we can just tack that on
1895 return !newAnimation.structural && hasAnimationClasses(newAnimation.options);
1898 rules.skip.push(function(element, newAnimation, currentAnimation) {
1899 // there is no need to animate anything if no classes are being added and
1900 // there is no structural animation that will be triggered
1901 return !newAnimation.structural && !hasAnimationClasses(newAnimation.options);
1904 rules.skip.push(function(element, newAnimation, currentAnimation) {
1905 // why should we trigger a new structural animation if the element will
1906 // be removed from the DOM anyway?
1907 return currentAnimation.event == 'leave' && newAnimation.structural;
1910 rules.skip.push(function(element, newAnimation, currentAnimation) {
1911 // if there is a current animation then skip the class-based animation
1912 return currentAnimation.structural && !newAnimation.structural;
1915 rules.cancel.push(function(element, newAnimation, currentAnimation) {
1916 // there can never be two structural animations running at the same time
1917 return currentAnimation.structural && newAnimation.structural;
1920 rules.cancel.push(function(element, newAnimation, currentAnimation) {
1921 // if the previous animation is already running, but the new animation will
1922 // be triggered, but the new animation is structural
1923 return currentAnimation.state === RUNNING_STATE && newAnimation.structural;
1926 rules.cancel.push(function(element, newAnimation, currentAnimation) {
1927 var nO = newAnimation.options;
1928 var cO = currentAnimation.options;
1930 // if the exact same CSS class is added/removed then it's safe to cancel it
1931 return (nO.addClass && nO.addClass === cO.removeClass) || (nO.removeClass && nO.removeClass === cO.addClass);
1934 this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$HashMap',
1935 '$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite',
1936 function($$rAF, $rootScope, $rootElement, $document, $$HashMap,
1937 $$animation, $$AnimateRunner, $templateRequest, $$jqLite) {
1939 var activeAnimationsLookup = new $$HashMap();
1940 var disabledElementsLookup = new $$HashMap();
1942 var animationsEnabled = null;
1944 // Wait until all directive and route-related templates are downloaded and
1945 // compiled. The $templateRequest.totalPendingRequests variable keeps track of
1946 // all of the remote templates being currently downloaded. If there are no
1947 // templates currently downloading then the watcher will still fire anyway.
1948 var deregisterWatch = $rootScope.$watch(
1949 function() { return $templateRequest.totalPendingRequests === 0; },
1951 if (!isEmpty) return;
1954 // Now that all templates have been downloaded, $animate will wait until
1955 // the post digest queue is empty before enabling animations. By having two
1956 // calls to $postDigest calls we can ensure that the flag is enabled at the
1957 // very end of the post digest queue. Since all of the animations in $animate
1958 // use $postDigest, it's important that the code below executes at the end.
1959 // This basically means that the page is fully downloaded and compiled before
1960 // any animations are triggered.
1961 $rootScope.$$postDigest(function() {
1962 $rootScope.$$postDigest(function() {
1963 // we check for null directly in the event that the application already called
1964 // .enabled() with whatever arguments that it provided it with
1965 if (animationsEnabled === null) {
1966 animationsEnabled = true;
1973 var bodyElement = jqLite($document[0].body);
1975 var callbackRegistry = {};
1977 // remember that the classNameFilter is set during the provider/config
1978 // stage therefore we can optimize here and setup a helper function
1979 var classNameFilter = $animateProvider.classNameFilter();
1980 var isAnimatableClassName = !classNameFilter
1981 ? function() { return true; }
1982 : function(className) {
1983 return classNameFilter.test(className);
1986 var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
1988 function normalizeAnimationOptions(element, options) {
1989 return mergeAnimationOptions(element, options, {});
1992 function findCallbacks(element, event) {
1993 var targetNode = getDomNode(element);
1996 var entries = callbackRegistry[event];
1998 forEach(entries, function(entry) {
1999 if (entry.node.contains(targetNode)) {
2000 matches.push(entry.callback);
2008 function triggerCallback(event, element, phase, data) {
2010 forEach(findCallbacks(element, event), function(callback) {
2011 callback(element, phase, data);
2017 on: function(event, container, callback) {
2018 var node = extractElementNode(container);
2019 callbackRegistry[event] = callbackRegistry[event] || [];
2020 callbackRegistry[event].push({
2026 off: function(event, container, callback) {
2027 var entries = callbackRegistry[event];
2028 if (!entries) return;
2030 callbackRegistry[event] = arguments.length === 1
2032 : filterFromRegistry(entries, container, callback);
2034 function filterFromRegistry(list, matchContainer, matchCallback) {
2035 var containerNode = extractElementNode(matchContainer);
2036 return list.filter(function(entry) {
2037 var isMatch = entry.node === containerNode &&
2038 (!matchCallback || entry.callback === matchCallback);
2044 pin: function(element, parentElement) {
2045 assertArg(isElement(element), 'element', 'not an element');
2046 assertArg(isElement(parentElement), 'parentElement', 'not an element');
2047 element.data(NG_ANIMATE_PIN_DATA, parentElement);
2050 push: function(element, event, options, domOperation) {
2051 options = options || {};
2052 options.domOperation = domOperation;
2053 return queueAnimation(element, event, options);
2056 // this method has four signatures:
2057 // () - global getter
2058 // (bool) - global setter
2059 // (element) - element getter
2060 // (element, bool) - element setter<F37>
2061 enabled: function(element, bool) {
2062 var argCount = arguments.length;
2064 if (argCount === 0) {
2065 // () - Global getter
2066 bool = !!animationsEnabled;
2068 var hasElement = isElement(element);
2071 // (bool) - Global setter
2072 bool = animationsEnabled = !!element;
2074 var node = getDomNode(element);
2075 var recordExists = disabledElementsLookup.get(node);
2077 if (argCount === 1) {
2078 // (element) - Element getter
2079 bool = !recordExists;
2081 // (element, bool) - Element setter
2084 disabledElementsLookup.put(node, true);
2085 } else if (recordExists) {
2086 disabledElementsLookup.remove(node);
2096 function queueAnimation(element, event, options) {
2098 element = stripCommentsFromElement(element);
2100 node = getDomNode(element);
2101 parent = element.parent();
2104 options = prepareAnimationOptions(options);
2106 // we create a fake runner with a working promise.
2107 // These methods will become available after the digest has passed
2108 var runner = new $$AnimateRunner();
2110 // there are situations where a directive issues an animation for
2111 // a jqLite wrapper that contains only comment nodes... If this
2112 // happens then there is no way we can perform an animation
2118 if (isArray(options.addClass)) {
2119 options.addClass = options.addClass.join(' ');
2122 if (isArray(options.removeClass)) {
2123 options.removeClass = options.removeClass.join(' ');
2126 if (options.from && !isObject(options.from)) {
2127 options.from = null;
2130 if (options.to && !isObject(options.to)) {
2134 var className = [node.className, options.addClass, options.removeClass].join(' ');
2135 if (!isAnimatableClassName(className)) {
2140 var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
2142 // this is a hard disable of all animations for the application or on
2143 // the element itself, therefore there is no need to continue further
2144 // past this point if not enabled
2145 var skipAnimations = !animationsEnabled || disabledElementsLookup.get(node);
2146 var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {};
2147 var hasExistingAnimation = !!existingAnimation.state;
2149 // there is no point in traversing the same collection of parent ancestors if a followup
2150 // animation will be run on the same element that already did all that checking work
2151 if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state != PRE_DIGEST_STATE)) {
2152 skipAnimations = !areAnimationsAllowed(element, parent, event);
2155 if (skipAnimations) {
2161 closeChildAnimations(element);
2164 var newAnimation = {
2165 structural: isStructural,
2173 if (hasExistingAnimation) {
2174 var skipAnimationFlag = isAllowed('skip', element, newAnimation, existingAnimation);
2175 if (skipAnimationFlag) {
2176 if (existingAnimation.state === RUNNING_STATE) {
2180 mergeAnimationOptions(element, existingAnimation.options, options);
2181 return existingAnimation.runner;
2185 var cancelAnimationFlag = isAllowed('cancel', element, newAnimation, existingAnimation);
2186 if (cancelAnimationFlag) {
2187 if (existingAnimation.state === RUNNING_STATE) {
2188 // this will end the animation right away and it is safe
2189 // to do so since the animation is already running and the
2190 // runner callback code will run in async
2191 existingAnimation.runner.end();
2192 } else if (existingAnimation.structural) {
2193 // this means that the animation is queued into a digest, but
2194 // hasn't started yet. Therefore it is safe to run the close
2195 // method which will call the runner methods in async.
2196 existingAnimation.close();
2198 // this will merge the existing animation options into this new follow-up animation
2199 mergeAnimationOptions(element, newAnimation.options, existingAnimation.options);
2202 // a joined animation means that this animation will take over the existing one
2203 // so an example would involve a leave animation taking over an enter. Then when
2204 // the postDigest kicks in the enter will be ignored.
2205 var joinAnimationFlag = isAllowed('join', element, newAnimation, existingAnimation);
2206 if (joinAnimationFlag) {
2207 if (existingAnimation.state === RUNNING_STATE) {
2208 normalizeAnimationOptions(element, options);
2210 event = newAnimation.event = existingAnimation.event;
2211 options = mergeAnimationOptions(element, existingAnimation.options, newAnimation.options);
2217 // normalization in this case means that it removes redundant CSS classes that
2218 // already exist (addClass) or do not exist (removeClass) on the element
2219 normalizeAnimationOptions(element, options);
2222 // when the options are merged and cleaned up we may end up not having to do
2223 // an animation at all, therefore we should check this before issuing a post
2224 // digest callback. Structural animations will always run no matter what.
2225 var isValidAnimation = newAnimation.structural;
2226 if (!isValidAnimation) {
2227 // animate (from/to) can be quickly checked first, otherwise we check if any classes are present
2228 isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0)
2229 || hasAnimationClasses(newAnimation.options);
2232 if (!isValidAnimation) {
2234 clearElementAnimationState(element);
2239 closeParentClassBasedAnimations(parent);
2242 // the counter keeps track of cancelled animations
2243 var counter = (existingAnimation.counter || 0) + 1;
2244 newAnimation.counter = counter;
2246 markElementAnimationState(element, PRE_DIGEST_STATE, newAnimation);
2248 $rootScope.$$postDigest(function() {
2249 var animationDetails = activeAnimationsLookup.get(node);
2250 var animationCancelled = !animationDetails;
2251 animationDetails = animationDetails || {};
2253 // if addClass/removeClass is called before something like enter then the
2254 // registered parent element may not be present. The code below will ensure
2255 // that a final value for parent element is obtained
2256 var parentElement = element.parent() || [];
2258 // animate/structural/class-based animations all have requirements. Otherwise there
2259 // is no point in performing an animation. The parent node must also be set.
2260 var isValidAnimation = parentElement.length > 0
2261 && (animationDetails.event === 'animate'
2262 || animationDetails.structural
2263 || hasAnimationClasses(animationDetails.options));
2265 // this means that the previous animation was cancelled
2266 // even if the follow-up animation is the same event
2267 if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) {
2268 // if another animation did not take over then we need
2269 // to make sure that the domOperation and options are
2270 // handled accordingly
2271 if (animationCancelled) {
2272 applyAnimationClasses(element, options);
2273 applyAnimationStyles(element, options);
2276 // if the event changed from something like enter to leave then we do
2277 // it, otherwise if it's the same then the end result will be the same too
2278 if (animationCancelled || (isStructural && animationDetails.event !== event)) {
2279 options.domOperation();
2283 // in the event that the element animation was not cancelled or a follow-up animation
2284 // isn't allowed to animate from here then we need to clear the state of the element
2285 // so that any future animations won't read the expired animation data.
2286 if (!isValidAnimation) {
2287 clearElementAnimationState(element);
2293 // this combined multiple class to addClass / removeClass into a setClass event
2294 // so long as a structural event did not take over the animation
2295 event = !animationDetails.structural && hasAnimationClasses(animationDetails.options, true)
2297 : animationDetails.event;
2299 if (animationDetails.structural) {
2300 closeParentClassBasedAnimations(parentElement);
2303 markElementAnimationState(element, RUNNING_STATE);
2304 var realRunner = $$animation(element, event, animationDetails.options);
2305 realRunner.done(function(status) {
2307 var animationDetails = activeAnimationsLookup.get(node);
2308 if (animationDetails && animationDetails.counter === counter) {
2309 clearElementAnimationState(getDomNode(element));
2311 notifyProgress(runner, event, 'close', {});
2314 // this will update the runner's flow-control events based on
2315 // the `realRunner` object.
2316 runner.setHost(realRunner);
2317 notifyProgress(runner, event, 'start', {});
2322 function notifyProgress(runner, event, phase, data) {
2323 triggerCallback(event, element, phase, data);
2324 runner.progress(event, phase, data);
2327 function close(reject) { // jshint ignore:line
2328 applyAnimationClasses(element, options);
2329 applyAnimationStyles(element, options);
2330 options.domOperation();
2331 runner.complete(!reject);
2335 function closeChildAnimations(element) {
2336 var node = getDomNode(element);
2337 var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']');
2338 forEach(children, function(child) {
2339 var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME));
2340 var animationDetails = activeAnimationsLookup.get(child);
2343 animationDetails.runner.end();
2345 case PRE_DIGEST_STATE:
2346 if (animationDetails) {
2347 activeAnimationsLookup.remove(child);
2354 function clearElementAnimationState(element) {
2355 var node = getDomNode(element);
2356 node.removeAttribute(NG_ANIMATE_ATTR_NAME);
2357 activeAnimationsLookup.remove(node);
2360 function isMatchingElement(nodeOrElmA, nodeOrElmB) {
2361 return getDomNode(nodeOrElmA) === getDomNode(nodeOrElmB);
2364 function closeParentClassBasedAnimations(startingElement) {
2365 var parentNode = getDomNode(startingElement);
2367 if (!parentNode || parentNode.nodeType !== ELEMENT_NODE) break;
2369 var animationDetails = activeAnimationsLookup.get(parentNode);
2370 if (animationDetails) {
2371 examineParentAnimation(parentNode, animationDetails);
2374 parentNode = parentNode.parentNode;
2377 // since animations are detected from CSS classes, we need to flush all parent
2378 // class-based animations so that the parent classes are all present for child
2379 // animations to properly function (otherwise any CSS selectors may not work)
2380 function examineParentAnimation(node, animationDetails) {
2381 // enter/leave/move always have priority
2382 if (animationDetails.structural || !hasAnimationClasses(animationDetails.options)) return;
2384 if (animationDetails.state === RUNNING_STATE) {
2385 animationDetails.runner.end();
2387 clearElementAnimationState(node);
2391 function areAnimationsAllowed(element, parentElement, event) {
2392 var bodyElementDetected = false;
2393 var rootElementDetected = false;
2394 var parentAnimationDetected = false;
2395 var animateChildren;
2397 var parentHost = element.data(NG_ANIMATE_PIN_DATA);
2399 parentElement = parentHost;
2402 while (parentElement && parentElement.length) {
2403 if (!rootElementDetected) {
2404 // angular doesn't want to attempt to animate elements outside of the application
2405 // therefore we need to ensure that the rootElement is an ancestor of the current element
2406 rootElementDetected = isMatchingElement(parentElement, $rootElement);
2409 var parentNode = parentElement[0];
2410 if (parentNode.nodeType !== ELEMENT_NODE) {
2411 // no point in inspecting the #document element
2415 var details = activeAnimationsLookup.get(parentNode) || {};
2416 // either an enter, leave or move animation will commence
2417 // therefore we can't allow any animations to take place
2418 // but if a parent animation is class-based then that's ok
2419 if (!parentAnimationDetected) {
2420 parentAnimationDetected = details.structural || disabledElementsLookup.get(parentNode);
2423 if (isUndefined(animateChildren) || animateChildren === true) {
2424 var value = parentElement.data(NG_ANIMATE_CHILDREN_DATA);
2425 if (isDefined(value)) {
2426 animateChildren = value;
2430 // there is no need to continue traversing at this point
2431 if (parentAnimationDetected && animateChildren === false) break;
2433 if (!rootElementDetected) {
2434 // angular doesn't want to attempt to animate elements outside of the application
2435 // therefore we need to ensure that the rootElement is an ancestor of the current element
2436 rootElementDetected = isMatchingElement(parentElement, $rootElement);
2437 if (!rootElementDetected) {
2438 parentHost = parentElement.data(NG_ANIMATE_PIN_DATA);
2440 parentElement = parentHost;
2445 if (!bodyElementDetected) {
2446 // we also need to ensure that the element is or will be apart of the body element
2447 // otherwise it is pointless to even issue an animation to be rendered
2448 bodyElementDetected = isMatchingElement(parentElement, bodyElement);
2451 parentElement = parentElement.parent();
2454 var allowAnimation = !parentAnimationDetected || animateChildren;
2455 return allowAnimation && rootElementDetected && bodyElementDetected;
2458 function markElementAnimationState(element, state, details) {
2459 details = details || {};
2460 details.state = state;
2462 var node = getDomNode(element);
2463 node.setAttribute(NG_ANIMATE_ATTR_NAME, state);
2465 var oldValue = activeAnimationsLookup.get(node);
2466 var newValue = oldValue
2467 ? extend(oldValue, details)
2469 activeAnimationsLookup.put(node, newValue);
2474 var $$rAFMutexFactory = ['$$rAF', function($$rAF) {
2480 return function(fn) {
2481 passed ? fn() : $$rAF(fn);
2486 var $$AnimateRunnerFactory = ['$q', '$$rAFMutex', function($q, $$rAFMutex) {
2487 var INITIAL_STATE = 0;
2488 var DONE_PENDING_STATE = 1;
2489 var DONE_COMPLETE_STATE = 2;
2491 AnimateRunner.chain = function(chain, callback) {
2496 if (index === chain.length) {
2501 chain[index](function(response) {
2502 if (response === false) {
2512 AnimateRunner.all = function(runners, callback) {
2515 forEach(runners, function(runner) {
2516 runner.done(onProgress);
2519 function onProgress(response) {
2520 status = status && response;
2521 if (++count === runners.length) {
2527 function AnimateRunner(host) {
2530 this._doneCallbacks = [];
2531 this._runInAnimationFrame = $$rAFMutex();
2535 AnimateRunner.prototype = {
2536 setHost: function(host) {
2537 this.host = host || {};
2540 done: function(fn) {
2541 if (this._state === DONE_COMPLETE_STATE) {
2544 this._doneCallbacks.push(fn);
2550 getPromise: function() {
2551 if (!this.promise) {
2553 this.promise = $q(function(resolve, reject) {
2554 self.done(function(status) {
2555 status === false ? reject() : resolve();
2559 return this.promise;
2562 then: function(resolveHandler, rejectHandler) {
2563 return this.getPromise().then(resolveHandler, rejectHandler);
2566 'catch': function(handler) {
2567 return this.getPromise()['catch'](handler);
2570 'finally': function(handler) {
2571 return this.getPromise()['finally'](handler);
2575 if (this.host.pause) {
2580 resume: function() {
2581 if (this.host.resume) {
2587 if (this.host.end) {
2590 this._resolve(true);
2593 cancel: function() {
2594 if (this.host.cancel) {
2597 this._resolve(false);
2600 complete: function(response) {
2602 if (self._state === INITIAL_STATE) {
2603 self._state = DONE_PENDING_STATE;
2604 self._runInAnimationFrame(function() {
2605 self._resolve(response);
2610 _resolve: function(response) {
2611 if (this._state !== DONE_COMPLETE_STATE) {
2612 forEach(this._doneCallbacks, function(fn) {
2615 this._doneCallbacks.length = 0;
2616 this._state = DONE_COMPLETE_STATE;
2621 return AnimateRunner;
2624 var $$AnimationProvider = ['$animateProvider', function($animateProvider) {
2625 var NG_ANIMATE_REF_ATTR = 'ng-animate-ref';
2627 var drivers = this.drivers = [];
2629 var RUNNER_STORAGE_KEY = '$$animationRunner';
2631 function setRunner(element, runner) {
2632 element.data(RUNNER_STORAGE_KEY, runner);
2635 function removeRunner(element) {
2636 element.removeData(RUNNER_STORAGE_KEY);
2639 function getRunner(element) {
2640 return element.data(RUNNER_STORAGE_KEY);
2643 this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$rAFScheduler',
2644 function($$jqLite, $rootScope, $injector, $$AnimateRunner, $$rAFScheduler) {
2646 var animationQueue = [];
2647 var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
2649 var totalPendingClassBasedAnimations = 0;
2650 var totalActiveClassBasedAnimations = 0;
2651 var classBasedAnimationsQueue = [];
2653 // TODO(matsko): document the signature in a better way
2654 return function(element, event, options) {
2655 options = prepareAnimationOptions(options);
2656 var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
2658 // there is no animation at the current moment, however
2659 // these runner methods will get later updated with the
2660 // methods leading into the driver's end/cancel methods
2661 // for now they just stop the animation from starting
2662 var runner = new $$AnimateRunner({
2663 end: function() { close(); },
2664 cancel: function() { close(true); }
2667 if (!drivers.length) {
2672 setRunner(element, runner);
2674 var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass));
2675 var tempClasses = options.tempClasses;
2677 classes += ' ' + tempClasses;
2678 options.tempClasses = null;
2681 var classBasedIndex;
2682 if (!isStructural) {
2683 classBasedIndex = totalPendingClassBasedAnimations;
2684 totalPendingClassBasedAnimations += 1;
2687 animationQueue.push({
2688 // this data is used by the postDigest code and passed into
2689 // the driver step function
2693 classBasedIndex: classBasedIndex,
2694 structural: isStructural,
2696 beforeStart: beforeStart,
2700 element.on('$destroy', handleDestroyedElement);
2702 // we only want there to be one function called within the post digest
2703 // block. This way we can group animations for all the animations that
2704 // were apart of the same postDigest flush call.
2705 if (animationQueue.length > 1) return runner;
2707 $rootScope.$$postDigest(function() {
2708 totalActiveClassBasedAnimations = totalPendingClassBasedAnimations;
2709 totalPendingClassBasedAnimations = 0;
2710 classBasedAnimationsQueue.length = 0;
2712 var animations = [];
2713 forEach(animationQueue, function(entry) {
2714 // the element was destroyed early on which removed the runner
2715 // form its storage. This means we can't animate this element
2716 // at all and it already has been closed due to destruction.
2717 if (getRunner(entry.element)) {
2718 animations.push(entry);
2722 // now any future animations will be in another postDigest
2723 animationQueue.length = 0;
2725 forEach(groupAnimations(animations), function(animationEntry) {
2726 if (animationEntry.structural) {
2727 triggerAnimationStart();
2729 classBasedAnimationsQueue.push({
2730 node: getDomNode(animationEntry.element),
2731 fn: triggerAnimationStart
2734 if (animationEntry.classBasedIndex === totalActiveClassBasedAnimations - 1) {
2735 // we need to sort each of the animations in order of parent to child
2736 // relationships. This ensures that the child classes are applied at the
2738 classBasedAnimationsQueue = classBasedAnimationsQueue.sort(function(a,b) {
2739 return b.node.contains(a.node);
2740 }).map(function(entry) {
2744 $$rAFScheduler(classBasedAnimationsQueue);
2748 function triggerAnimationStart() {
2749 // it's important that we apply the `ng-animate` CSS class and the
2750 // temporary classes before we do any driver invoking since these
2751 // CSS classes may be required for proper CSS detection.
2752 animationEntry.beforeStart();
2754 var startAnimationFn, closeFn = animationEntry.close;
2756 // in the event that the element was removed before the digest runs or
2757 // during the RAF sequencing then we should not trigger the animation.
2758 var targetElement = animationEntry.anchors
2759 ? (animationEntry.from.element || animationEntry.to.element)
2760 : animationEntry.element;
2762 if (getRunner(targetElement) && getDomNode(targetElement).parentNode) {
2763 var operation = invokeFirstDriver(animationEntry);
2765 startAnimationFn = operation.start;
2769 if (!startAnimationFn) {
2772 var animationRunner = startAnimationFn();
2773 animationRunner.done(function(status) {
2776 updateAnimationRunners(animationEntry, animationRunner);
2784 // TODO(matsko): change to reference nodes
2785 function getAnchorNodes(node) {
2786 var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']';
2787 var items = node.hasAttribute(NG_ANIMATE_REF_ATTR)
2789 : node.querySelectorAll(SELECTOR);
2791 forEach(items, function(node) {
2792 var attr = node.getAttribute(NG_ANIMATE_REF_ATTR);
2793 if (attr && attr.length) {
2800 function groupAnimations(animations) {
2801 var preparedAnimations = [];
2803 forEach(animations, function(animation, index) {
2804 var element = animation.element;
2805 var node = getDomNode(element);
2806 var event = animation.event;
2807 var enterOrMove = ['enter', 'move'].indexOf(event) >= 0;
2808 var anchorNodes = animation.structural ? getAnchorNodes(node) : [];
2810 if (anchorNodes.length) {
2811 var direction = enterOrMove ? 'to' : 'from';
2813 forEach(anchorNodes, function(anchor) {
2814 var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR);
2815 refLookup[key] = refLookup[key] || {};
2816 refLookup[key][direction] = {
2818 element: jqLite(anchor)
2822 preparedAnimations.push(animation);
2826 var usedIndicesLookup = {};
2827 var anchorGroups = {};
2828 forEach(refLookup, function(operations, key) {
2829 var from = operations.from;
2830 var to = operations.to;
2833 // only one of these is set therefore we can't have an
2834 // anchor animation since all three pieces are required
2835 var index = from ? from.animationID : to.animationID;
2836 var indexKey = index.toString();
2837 if (!usedIndicesLookup[indexKey]) {
2838 usedIndicesLookup[indexKey] = true;
2839 preparedAnimations.push(animations[index]);
2844 var fromAnimation = animations[from.animationID];
2845 var toAnimation = animations[to.animationID];
2846 var lookupKey = from.animationID.toString();
2847 if (!anchorGroups[lookupKey]) {
2848 var group = anchorGroups[lookupKey] = {
2850 beforeStart: function() {
2851 fromAnimation.beforeStart();
2852 toAnimation.beforeStart();
2855 fromAnimation.close();
2856 toAnimation.close();
2858 classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes),
2859 from: fromAnimation,
2861 anchors: [] // TODO(matsko): change to reference nodes
2864 // the anchor animations require that the from and to elements both have at least
2865 // one shared CSS class which effictively marries the two elements together to use
2866 // the same animation driver and to properly sequence the anchor animation.
2867 if (group.classes.length) {
2868 preparedAnimations.push(group);
2870 preparedAnimations.push(fromAnimation);
2871 preparedAnimations.push(toAnimation);
2875 anchorGroups[lookupKey].anchors.push({
2876 'out': from.element, 'in': to.element
2880 return preparedAnimations;
2883 function cssClassesIntersection(a,b) {
2888 for (var i = 0; i < a.length; i++) {
2890 if (aa.substring(0,3) === 'ng-') continue;
2892 for (var j = 0; j < b.length; j++) {
2900 return matches.join(' ');
2903 function invokeFirstDriver(animationDetails) {
2904 // we loop in reverse order since the more general drivers (like CSS and JS)
2905 // may attempt more elements, but custom drivers are more particular
2906 for (var i = drivers.length - 1; i >= 0; i--) {
2907 var driverName = drivers[i];
2908 if (!$injector.has(driverName)) continue; // TODO(matsko): remove this check
2910 var factory = $injector.get(driverName);
2911 var driver = factory(animationDetails);
2918 function beforeStart() {
2919 element.addClass(NG_ANIMATE_CLASSNAME);
2921 $$jqLite.addClass(element, tempClasses);
2925 function updateAnimationRunners(animation, newRunner) {
2926 if (animation.from && animation.to) {
2927 update(animation.from.element);
2928 update(animation.to.element);
2930 update(animation.element);
2933 function update(element) {
2934 getRunner(element).setHost(newRunner);
2938 function handleDestroyedElement() {
2939 var runner = getRunner(element);
2940 if (runner && (event !== 'leave' || !options.$$domOperationFired)) {
2945 function close(rejected) { // jshint ignore:line
2946 element.off('$destroy', handleDestroyedElement);
2947 removeRunner(element);
2949 applyAnimationClasses(element, options);
2950 applyAnimationStyles(element, options);
2951 options.domOperation();
2954 $$jqLite.removeClass(element, tempClasses);
2957 element.removeClass(NG_ANIMATE_CLASSNAME);
2958 runner.complete(!rejected);
2964 /* global angularAnimateModule: true,
2967 $$rAFSchedulerFactory,
2968 $$AnimateChildrenDirective,
2969 $$AnimateRunnerFactory,
2970 $$AnimateQueueProvider,
2971 $$AnimationProvider,
2972 $AnimateCssProvider,
2973 $$AnimateCssDriverProvider,
2974 $$AnimateJsProvider,
2975 $$AnimateJsDriverProvider,
2983 * The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via
2984 * callback hooks. Animations are not enabled by default, however, by including `ngAnimate` then the animation hooks are enabled for an Angular app.
2986 * <div doc-module-components="ngAnimate"></div>
2989 * Simply put, there are two ways to make use of animations when ngAnimate is used: by using **CSS** and **JavaScript**. The former works purely based
2990 * using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For
2991 * both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within
2992 * the HTML element that the animation will be triggered on.
2994 * ## Directive Support
2995 * The following directives are "animation aware":
2997 * | Directive | Supported Animations |
2998 * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|
2999 * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move |
3000 * | {@link ngRoute.directive:ngView#animations ngView} | enter and leave |
3001 * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave |
3002 * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave |
3003 * | {@link ng.directive:ngIf#animations ngIf} | enter and leave |
3004 * | {@link ng.directive:ngClass#animations ngClass} | add and remove (the CSS class(es) present) |
3005 * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide} | add and remove (the ng-hide class value) |
3006 * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) |
3007 * | {@link module:ngMessages#animations ngMessages} | add and remove (ng-active & ng-inactive) |
3008 * | {@link module:ngMessages#animations ngMessage} | enter and leave |
3010 * (More information can be found by visiting each the documentation associated with each directive.)
3012 * ## CSS-based Animations
3014 * CSS-based animations with ngAnimate are unique since they require no JavaScript code at all. By using a CSS class that we reference between our HTML
3015 * and CSS code we can create an animation that will be picked up by Angular when an the underlying directive performs an operation.
3017 * The example below shows how an `enter` animation can be made possible on a element using `ng-if`:
3020 * <div ng-if="bool" class="fade">
3023 * <button ng-click="bool=true">Fade In!</button>
3024 * <button ng-click="bool=false">Fade Out!</button>
3027 * Notice the CSS class **fade**? We can now create the CSS transition code that references this class:
3030 * /* The starting CSS styles for the enter animation */
3032 * transition:0.5s linear all;
3036 * /* The finishing CSS styles for the enter animation */
3037 * .fade.ng-enter.ng-enter-active {
3042 * The key thing to remember here is that, depending on the animation event (which each of the directives above trigger depending on what's going on) two
3043 * generated CSS classes will be applied to the element; in the example above we have `.ng-enter` and `.ng-enter-active`. For CSS transitions, the transition
3044 * code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards.
3046 * If for example we wanted to create animations for `leave` and `move` (ngRepeat triggers move) then we can do so using the same CSS naming conventions:
3049 * /* now the element will fade out before it is removed from the DOM */
3051 * transition:0.5s linear all;
3054 * .fade.ng-leave.ng-leave-active {
3059 * We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class:
3062 * /* there is no need to define anything inside of the destination
3063 * CSS class since the keyframe will take charge of the animation */
3065 * animation: my_fade_animation 0.5s linear;
3066 * -webkit-animation: my_fade_animation 0.5s linear;
3069 * @keyframes my_fade_animation {
3070 * from { opacity:1; }
3074 * @-webkit-keyframes my_fade_animation {
3075 * from { opacity:1; }
3080 * Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element.
3082 * ### CSS Class-based Animations
3084 * Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different
3085 * naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added
3088 * For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class:
3091 * <div ng-show="bool" class="fade">
3094 * <button ng-click="bool=true">Toggle</button>
3098 * transition:0.5s linear all;
3104 * All that is going on here with ngShow/ngHide behind the scenes is the `.ng-hide` class is added/removed (when the hidden state is valid). Since
3105 * ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest.
3107 * In addition the addition and removal of the CSS class, ngAnimate also provides two helper methods that we can use to further decorate the animation
3111 * <div ng-class="{on:onOff}" class="highlight">
3112 * Highlight this box
3114 * <button ng-click="onOff=!onOff">Toggle</button>
3118 * transition:0.5s linear all;
3120 * .highlight.on-add {
3124 * background:yellow;
3126 * .highlight.on-remove {
3132 * We can also make use of CSS keyframes by placing them within the CSS classes.
3135 * ### CSS Staggering Animations
3136 * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a
3137 * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be
3138 * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for
3139 * the animation. The style property expected within the stagger class can either be a **transition-delay** or an
3140 * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).
3143 * .my-animation.ng-enter {
3144 * /* standard transition code */
3145 * transition: 1s linear all;
3148 * .my-animation.ng-enter-stagger {
3149 * /* this will have a 100ms delay between each successive leave animation */
3150 * transition-delay: 0.1s;
3152 * /* in case the stagger doesn't work then the duration value
3153 * must be set to 0 to avoid an accidental CSS inheritance */
3154 * transition-duration: 0s;
3156 * .my-animation.ng-enter.ng-enter-active {
3157 * /* standard transition styles */
3162 * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations
3163 * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this
3164 * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation
3165 * will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired.
3167 * The following code will issue the **ng-leave-stagger** event on the element provided:
3170 * var kids = parent.children();
3172 * $animate.leave(kids[0]); //stagger index=0
3173 * $animate.leave(kids[1]); //stagger index=1
3174 * $animate.leave(kids[2]); //stagger index=2
3175 * $animate.leave(kids[3]); //stagger index=3
3176 * $animate.leave(kids[4]); //stagger index=4
3178 * window.requestAnimationFrame(function() {
3179 * //stagger has reset itself
3180 * $animate.leave(kids[5]); //stagger index=0
3181 * $animate.leave(kids[6]); //stagger index=1
3187 * Stagger animations are currently only supported within CSS-defined animations.
3189 * ### The `ng-animate` CSS class
3191 * When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation.
3192 * This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations).
3194 * Therefore, animations can be applied to an element using this temporary class directly via CSS.
3197 * .zipper.ng-animate {
3198 * transition:0.5s linear all;
3200 * .zipper.ng-enter {
3203 * .zipper.ng-enter.ng-enter-active {
3206 * .zipper.ng-leave {
3209 * .zipper.ng-leave.ng-leave-active {
3214 * (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove
3215 * the CSS class once an animation has completed.)
3218 * ## JavaScript-based Animations
3220 * ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared
3221 * CSS class that is referenced in our HTML code) but in addition we need to register the JavaScript animation on the module. By making use of the
3222 * `module.animation()` module function we can register the ainmation.
3224 * Let's see an example of a enter/leave animation using `ngRepeat`:
3227 * <div ng-repeat="item in items" class="slide">
3232 * See the **slide** CSS class? Let's use that class to define an animation that we'll structure in our module code by using `module.animation`:
3235 * myModule.animation('.slide', [function() {
3237 * // make note that other events (like addClass/removeClass)
3238 * // have different function input parameters
3239 * enter: function(element, doneFn) {
3240 * jQuery(element).fadeIn(1000, doneFn);
3242 * // remember to call doneFn so that angular
3243 * // knows that the animation has concluded
3246 * move: function(element, doneFn) {
3247 * jQuery(element).fadeIn(1000, doneFn);
3250 * leave: function(element, doneFn) {
3251 * jQuery(element).fadeOut(1000, doneFn);
3257 * The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as
3258 * greensock.js and velocity.js.
3260 * If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define
3261 * our animations inside of the same registered animation, however, the function input arguments are a bit different:
3264 * <div ng-class="color" class="colorful">
3267 * <button ng-click="color='red'">Change to red</button>
3268 * <button ng-click="color='blue'">Change to blue</button>
3269 * <button ng-click="color='green'">Change to green</button>
3273 * myModule.animation('.colorful', [function() {
3275 * addClass: function(element, className, doneFn) {
3276 * // do some cool animation and call the doneFn
3278 * removeClass: function(element, className, doneFn) {
3279 * // do some cool animation and call the doneFn
3281 * setClass: function(element, addedClass, removedClass, doneFn) {
3282 * // do some cool animation and call the doneFn
3288 * ## CSS + JS Animations Together
3290 * AngularJS 1.4 and higher has taken steps to make the amalgamation of CSS and JS animations more flexible. However, unlike earlier versions of Angular,
3291 * defining CSS and JS animations to work off of the same CSS class will not work anymore. Therefore the example below will only result in **JS animations taking
3292 * charge of the animation**:
3295 * <div ng-if="bool" class="slide">
3301 * myModule.animation('.slide', [function() {
3303 * enter: function(element, doneFn) {
3304 * jQuery(element).slideIn(1000, doneFn);
3312 * transition:0.5s linear all;
3313 * transform:translateY(-100px);
3315 * .slide.ng-enter.ng-enter-active {
3316 * transform:translateY(0);
3320 * Does this mean that CSS and JS animations cannot be used together? Do JS-based animations always have higher priority? We can make up for the
3321 * lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from
3322 * our own JS-based animation code:
3325 * myModule.animation('.slide', ['$animateCss', function($animateCss) {
3327 * enter: function(element, doneFn) {
3328 * // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`.
3329 * var runner = $animateCss(element, {
3333 * runner.done(doneFn);
3339 * The nice thing here is that we can save bandwidth by sticking to our CSS-based animation code and we don't need to rely on a 3rd-party animation framework.
3341 * The `$animateCss` service is very powerful since we can feed in all kinds of extra properties that will be evaluated and fed into a CSS transition or
3342 * keyframe animation. For example if we wanted to animate the height of an element while adding and removing classes then we can do so by providing that
3343 * data into `$animateCss` directly:
3346 * myModule.animation('.slide', ['$animateCss', function($animateCss) {
3348 * enter: function(element, doneFn) {
3349 * var runner = $animateCss(element, {
3351 * addClass: 'maroon-setting',
3352 * from: { height:0 },
3353 * to: { height: 200 }
3356 * runner.done(doneFn);
3362 * Now we can fill in the rest via our transition CSS code:
3365 * /* the transition tells ngAnimate to make the animation happen */
3366 * .slide.ng-enter { transition:0.5s linear all; }
3368 * /* this extra CSS class will be absorbed into the transition
3369 * since the $animateCss code is adding the class */
3370 * .maroon-setting { background:red; }
3373 * And `$animateCss` will figure out the rest. Just make sure to have the `done()` callback fire the `doneFn` function to signal when the animation is over.
3375 * To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}.
3377 * ## Animation Anchoring (via `ng-animate-ref`)
3379 * ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between
3380 * structural areas of an application (like views) by pairing up elements using an attribute
3381 * called `ng-animate-ref`.
3383 * Let's say for example we have two views that are managed by `ng-view` and we want to show
3384 * that there is a relationship between two components situated in within these views. By using the
3385 * `ng-animate-ref` attribute we can identify that the two components are paired together and we
3386 * can then attach an animation, which is triggered when the view changes.
3388 * Say for example we have the following template code:
3391 * <!-- index.html -->
3392 * <div ng-view class="view-animation">
3395 * <!-- home.html -->
3396 * <a href="#/banner-page">
3397 * <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
3400 * <!-- banner-page.html -->
3401 * <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
3404 * Now, when the view changes (once the link is clicked), ngAnimate will examine the
3405 * HTML contents to see if there is a match reference between any components in the view
3406 * that is leaving and the view that is entering. It will scan both the view which is being
3407 * removed (leave) and inserted (enter) to see if there are any paired DOM elements that
3408 * contain a matching ref value.
3410 * The two images match since they share the same ref value. ngAnimate will now create a
3411 * transport element (which is a clone of the first image element) and it will then attempt
3412 * to animate to the position of the second image element in the next view. For the animation to
3413 * work a special CSS class called `ng-anchor` will be added to the transported element.
3415 * We can now attach a transition onto the `.banner.ng-anchor` CSS class and then
3416 * ngAnimate will handle the entire transition for us as well as the addition and removal of
3417 * any changes of CSS classes between the elements:
3420 * .banner.ng-anchor {
3421 * /* this animation will last for 1 second since there are
3422 * two phases to the animation (an `in` and an `out` phase) */
3423 * transition:0.5s linear all;
3427 * We also **must** include animations for the views that are being entered and removed
3428 * (otherwise anchoring wouldn't be possible since the new view would be inserted right away).
3431 * .view-animation.ng-enter, .view-animation.ng-leave {
3432 * transition:0.5s linear all;
3438 * .view-animation.ng-enter {
3439 * transform:translateX(100%);
3441 * .view-animation.ng-leave,
3442 * .view-animation.ng-enter.ng-enter-active {
3443 * transform:translateX(0%);
3445 * .view-animation.ng-leave.ng-leave-active {
3446 * transform:translateX(-100%);
3450 * Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur:
3451 * an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away
3452 * from its origin. Once that animation is over then the `in` stage occurs which animates the
3453 * element to its destination. The reason why there are two animations is to give enough time
3454 * for the enter animation on the new element to be ready.
3456 * The example above sets up a transition for both the in and out phases, but we can also target the out or
3457 * in phases directly via `ng-anchor-out` and `ng-anchor-in`.
3460 * .banner.ng-anchor-out {
3461 * transition: 0.5s linear all;
3463 * /* the scale will be applied during the out animation,
3464 * but will be animated away when the in animation runs */
3465 * transform: scale(1.2);
3468 * .banner.ng-anchor-in {
3469 * transition: 1s linear all;
3476 * ### Anchoring Demo
3478 <example module="anchoringExample"
3479 name="anchoringExample"
3480 id="anchoringExample"
3481 deps="angular-animate.js;angular-route.js"
3483 <file name="index.html">
3484 <a href="#/">Home</a>
3486 <div class="view-container">
3487 <div ng-view class="view"></div>
3490 <file name="script.js">
3491 angular.module('anchoringExample', ['ngAnimate', 'ngRoute'])
3492 .config(['$routeProvider', function($routeProvider) {
3493 $routeProvider.when('/', {
3494 templateUrl: 'home.html',
3495 controller: 'HomeController as home'
3497 $routeProvider.when('/profile/:id', {
3498 templateUrl: 'profile.html',
3499 controller: 'ProfileController as profile'
3502 .run(['$rootScope', function($rootScope) {
3503 $rootScope.records = [
3504 { id:1, title: "Miss Beulah Roob" },
3505 { id:2, title: "Trent Morissette" },
3506 { id:3, title: "Miss Ava Pouros" },
3507 { id:4, title: "Rod Pouros" },
3508 { id:5, title: "Abdul Rice" },
3509 { id:6, title: "Laurie Rutherford Sr." },
3510 { id:7, title: "Nakia McLaughlin" },
3511 { id:8, title: "Jordon Blanda DVM" },
3512 { id:9, title: "Rhoda Hand" },
3513 { id:10, title: "Alexandrea Sauer" }
3516 .controller('HomeController', [function() {
3519 .controller('ProfileController', ['$rootScope', '$routeParams', function($rootScope, $routeParams) {
3520 var index = parseInt($routeParams.id, 10);
3521 var record = $rootScope.records[index - 1];
3523 this.title = record.title;
3524 this.id = record.id;
3527 <file name="home.html">
3528 <h2>Welcome to the home page</h1>
3529 <p>Please click on an element</p>
3531 ng-href="#/profile/{{ record.id }}"
3532 ng-animate-ref="{{ record.id }}"
3533 ng-repeat="record in records">
3537 <file name="profile.html">
3538 <div class="profile record" ng-animate-ref="{{ profile.id }}">
3542 <file name="animations.css">
3555 .view-container > .view.ng-animate {
3562 .view.ng-enter, .view.ng-leave,
3564 transition:0.5s linear all;
3567 transform:translateX(100%);
3569 .view.ng-enter.ng-enter-active, .view.ng-leave {
3570 transform:translateX(0%);
3572 .view.ng-leave.ng-leave-active {
3573 transform:translateX(-100%);
3575 .record.ng-anchor-out {
3581 * ### How is the element transported?
3583 * When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting
3584 * element is located on screen via absolute positioning. The cloned element will be placed inside of the root element
3585 * of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The
3586 * element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match
3587 * the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied
3588 * to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class
3589 * is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element
3590 * will become visible since the shim class will be removed.
3592 * ### How is the morphing handled?
3594 * CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out
3595 * what CSS classes differ between the starting element and the destination element. These different CSS classes
3596 * will be added/removed on the anchor element and a transition will be applied (the transition that is provided
3597 * in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will
3598 * make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that
3599 * do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since
3600 * the cloned element is placed inside of root element which is likely close to the body element).
3602 * Note that if the root element is on the `<html>` element then the cloned node will be placed inside of body.
3605 * ## Using $animate in your directive code
3607 * So far we've explored how to feed in animations into an Angular application, but how do we trigger animations within our own directives in our application?
3608 * By injecting the `$animate` service into our directive code, we can trigger structural and class-based hooks which can then be consumed by animations. Let's
3609 * imagine we have a greeting box that shows and hides itself when the data changes
3612 * <greeting-box active="onOrOff">Hi there</greeting-box>
3616 * ngModule.directive('greetingBox', ['$animate', function($animate) {
3617 * return function(scope, element, attrs) {
3618 * attrs.$observe('active', function(value) {
3619 * value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on');
3625 * Now the `on` CSS class is added and removed on the greeting box component. Now if we add a CSS class on top of the greeting box element
3626 * in our HTML code then we can trigger a CSS or JS animation to happen.
3629 * /* normally we would create a CSS class to reference on the element */
3630 * greeting-box.on { transition:0.5s linear all; background:green; color:white; }
3633 * The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's
3634 * possible be sure to visit the {@link ng.$animate $animate service API page}.
3637 * ### Preventing Collisions With Third Party Libraries
3639 * Some third-party frameworks place animation duration defaults across many element or className
3640 * selectors in order to make their code small and reuseable. This can lead to issues with ngAnimate, which
3641 * is expecting actual animations on these elements and has to wait for their completion.
3643 * You can prevent this unwanted behavior by using a prefix on all your animation classes:
3646 * /* prefixed with animate- */
3647 * .animate-fade-add.animate-fade-add-active {
3648 * transition:1s linear all;
3653 * You then configure `$animate` to enforce this prefix:
3656 * $animateProvider.classNameFilter(/animate-/);
3659 * This also may provide your application with a speed boost since only specific elements containing CSS class prefix
3660 * will be evaluated for animation when any DOM changes occur in the application.
3662 * ## Callbacks and Promises
3664 * When `$animate` is called it returns a promise that can be used to capture when the animation has ended. Therefore if we were to trigger
3665 * an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has
3666 * ended by chaining onto the returned promise that animation method returns.
3669 * // somewhere within the depths of the directive
3670 * $animate.enter(element, parent).then(function() {
3671 * //the animation has completed
3675 * (Note that earlier versions of Angular prior to v1.4 required the promise code to be wrapped using `$scope.$apply(...)`. This is not the case
3678 * In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering
3679 * an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view
3680 * routing controller to hook into that:
3683 * ngModule.controller('HomePageController', ['$animate', function($animate) {
3684 * $animate.on('enter', ngViewElement, function(element) {
3685 * // the animation for this route has completed
3690 * (Note that you will need to trigger a digest within the callback to get angular to notice any scope-related changes.)
3699 * The ngAnimate `$animate` service documentation is the same for the core `$animate` service.
3701 * Click here {@link ng.$animate $animate to learn more about animations with `$animate`}.
3703 angular.module('ngAnimate', [])
3704 .directive('ngAnimateChildren', $$AnimateChildrenDirective)
3706 .factory('$$rAFMutex', $$rAFMutexFactory)
3707 .factory('$$rAFScheduler', $$rAFSchedulerFactory)
3709 .factory('$$AnimateRunner', $$AnimateRunnerFactory)
3711 .provider('$$animateQueue', $$AnimateQueueProvider)
3712 .provider('$$animation', $$AnimationProvider)
3714 .provider('$animateCss', $AnimateCssProvider)
3715 .provider('$$animateCssDriver', $$AnimateCssDriverProvider)
3717 .provider('$$animateJs', $$AnimateJsProvider)
3718 .provider('$$animateJsDriver', $$AnimateJsDriverProvider);
3721 })(window, window.angular);