webogram-i2p/app/vendor/angular/test-bundles/angular-route.js

9336 lines
323 KiB
JavaScript
Raw Normal View History

2019-05-09 19:56:23 +00:00
/**
* @license AngularJS v1.7.8
* (c) 2010-2018 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular) {'use strict';
/**
* @license AngularJS v1.7.8
* (c) 2010-2018 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular) {
var ELEMENT_NODE = 1;
var COMMENT_NODE = 8;
var ADD_CLASS_SUFFIX = '-add';
var REMOVE_CLASS_SUFFIX = '-remove';
var EVENT_CLASS_PREFIX = 'ng-';
var ACTIVE_CLASS_SUFFIX = '-active';
var PREPARE_CLASS_SUFFIX = '-prepare';
var NG_ANIMATE_CLASSNAME = 'ng-animate';
var NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren';
// Detect proper transitionend/animationend event names.
var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;
// If unprefixed events are not supported but webkit-prefixed are, use the latter.
// Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.
// Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`
// but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.
// Register both events in case `window.onanimationend` is not supported because of that,
// do the same for `transitionend` as Safari is likely to exhibit similar behavior.
// Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit
// therefore there is no reason to test anymore for other vendor prefixes:
// http://caniuse.com/#search=transition
if ((window.ontransitionend === undefined) && (window.onwebkittransitionend !== undefined)) {
CSS_PREFIX = '-webkit-';
TRANSITION_PROP = 'WebkitTransition';
TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
} else {
TRANSITION_PROP = 'transition';
TRANSITIONEND_EVENT = 'transitionend';
}
if ((window.onanimationend === undefined) && (window.onwebkitanimationend !== undefined)) {
CSS_PREFIX = '-webkit-';
ANIMATION_PROP = 'WebkitAnimation';
ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';
} else {
ANIMATION_PROP = 'animation';
ANIMATIONEND_EVENT = 'animationend';
}
var DURATION_KEY = 'Duration';
var PROPERTY_KEY = 'Property';
var DELAY_KEY = 'Delay';
var TIMING_KEY = 'TimingFunction';
var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';
var ANIMATION_PLAYSTATE_KEY = 'PlayState';
var SAFE_FAST_FORWARD_DURATION_VALUE = 9999;
var ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY;
var ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY;
var TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY;
var TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY;
var ngMinErr = angular.$$minErr('ng');
function assertArg(arg, name, reason) {
if (!arg) {
throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
}
return arg;
}
function mergeClasses(a,b) {
if (!a && !b) return '';
if (!a) return b;
if (!b) return a;
if (isArray(a)) a = a.join(' ');
if (isArray(b)) b = b.join(' ');
return a + ' ' + b;
}
function packageStyles(options) {
var styles = {};
if (options && (options.to || options.from)) {
styles.to = options.to;
styles.from = options.from;
}
return styles;
}
function pendClasses(classes, fix, isPrefix) {
var className = '';
classes = isArray(classes)
? classes
: classes && isString(classes) && classes.length
? classes.split(/\s+/)
: [];
forEach(classes, function(klass, i) {
if (klass && klass.length > 0) {
className += (i > 0) ? ' ' : '';
className += isPrefix ? fix + klass
: klass + fix;
}
});
return className;
}
function removeFromArray(arr, val) {
var index = arr.indexOf(val);
if (val >= 0) {
arr.splice(index, 1);
}
}
function stripCommentsFromElement(element) {
if (element instanceof jqLite) {
switch (element.length) {
case 0:
return element;
case 1:
// there is no point of stripping anything if the element
// is the only element within the jqLite wrapper.
// (it's important that we retain the element instance.)
if (element[0].nodeType === ELEMENT_NODE) {
return element;
}
break;
default:
return jqLite(extractElementNode(element));
}
}
if (element.nodeType === ELEMENT_NODE) {
return jqLite(element);
}
}
function extractElementNode(element) {
if (!element[0]) return element;
for (var i = 0; i < element.length; i++) {
var elm = element[i];
if (elm.nodeType === ELEMENT_NODE) {
return elm;
}
}
}
function $$addClass($$jqLite, element, className) {
forEach(element, function(elm) {
$$jqLite.addClass(elm, className);
});
}
function $$removeClass($$jqLite, element, className) {
forEach(element, function(elm) {
$$jqLite.removeClass(elm, className);
});
}
function applyAnimationClassesFactory($$jqLite) {
return function(element, options) {
if (options.addClass) {
$$addClass($$jqLite, element, options.addClass);
options.addClass = null;
}
if (options.removeClass) {
$$removeClass($$jqLite, element, options.removeClass);
options.removeClass = null;
}
};
}
function prepareAnimationOptions(options) {
options = options || {};
if (!options.$$prepared) {
var domOperation = options.domOperation || noop;
options.domOperation = function() {
options.$$domOperationFired = true;
domOperation();
domOperation = noop;
};
options.$$prepared = true;
}
return options;
}
function applyAnimationStyles(element, options) {
applyAnimationFromStyles(element, options);
applyAnimationToStyles(element, options);
}
function applyAnimationFromStyles(element, options) {
if (options.from) {
element.css(options.from);
options.from = null;
}
}
function applyAnimationToStyles(element, options) {
if (options.to) {
element.css(options.to);
options.to = null;
}
}
function mergeAnimationDetails(element, oldAnimation, newAnimation) {
var target = oldAnimation.options || {};
var newOptions = newAnimation.options || {};
var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || '');
var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || '');
var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove);
if (newOptions.preparationClasses) {
target.preparationClasses = concatWithSpace(newOptions.preparationClasses, target.preparationClasses);
delete newOptions.preparationClasses;
}
// noop is basically when there is no callback; otherwise something has been set
var realDomOperation = target.domOperation !== noop ? target.domOperation : null;
extend(target, newOptions);
// TODO(matsko or sreeramu): proper fix is to maintain all animation callback in array and call at last,but now only leave has the callback so no issue with this.
if (realDomOperation) {
target.domOperation = realDomOperation;
}
if (classes.addClass) {
target.addClass = classes.addClass;
} else {
target.addClass = null;
}
if (classes.removeClass) {
target.removeClass = classes.removeClass;
} else {
target.removeClass = null;
}
oldAnimation.addClass = target.addClass;
oldAnimation.removeClass = target.removeClass;
return target;
}
function resolveElementClasses(existing, toAdd, toRemove) {
var ADD_CLASS = 1;
var REMOVE_CLASS = -1;
var flags = {};
existing = splitClassesToLookup(existing);
toAdd = splitClassesToLookup(toAdd);
forEach(toAdd, function(value, key) {
flags[key] = ADD_CLASS;
});
toRemove = splitClassesToLookup(toRemove);
forEach(toRemove, function(value, key) {
flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS;
});
var classes = {
addClass: '',
removeClass: ''
};
forEach(flags, function(val, klass) {
var prop, allow;
if (val === ADD_CLASS) {
prop = 'addClass';
allow = !existing[klass] || existing[klass + REMOVE_CLASS_SUFFIX];
} else if (val === REMOVE_CLASS) {
prop = 'removeClass';
allow = existing[klass] || existing[klass + ADD_CLASS_SUFFIX];
}
if (allow) {
if (classes[prop].length) {
classes[prop] += ' ';
}
classes[prop] += klass;
}
});
function splitClassesToLookup(classes) {
if (isString(classes)) {
classes = classes.split(' ');
}
var obj = {};
forEach(classes, function(klass) {
// sometimes the split leaves empty string values
// incase extra spaces were applied to the options
if (klass.length) {
obj[klass] = true;
}
});
return obj;
}
return classes;
}
function getDomNode(element) {
return (element instanceof jqLite) ? element[0] : element;
}
function applyGeneratedPreparationClasses($$jqLite, element, event, options) {
var classes = '';
if (event) {
classes = pendClasses(event, EVENT_CLASS_PREFIX, true);
}
if (options.addClass) {
classes = concatWithSpace(classes, pendClasses(options.addClass, ADD_CLASS_SUFFIX));
}
if (options.removeClass) {
classes = concatWithSpace(classes, pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX));
}
if (classes.length) {
options.preparationClasses = classes;
element.addClass(classes);
}
}
function clearGeneratedClasses(element, options) {
if (options.preparationClasses) {
element.removeClass(options.preparationClasses);
options.preparationClasses = null;
}
if (options.activeClasses) {
element.removeClass(options.activeClasses);
options.activeClasses = null;
}
}
function blockKeyframeAnimations(node, applyBlock) {
var value = applyBlock ? 'paused' : '';
var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY;
applyInlineStyle(node, [key, value]);
return [key, value];
}
function applyInlineStyle(node, styleTuple) {
var prop = styleTuple[0];
var value = styleTuple[1];
node.style[prop] = value;
}
function concatWithSpace(a,b) {
if (!a) return b;
if (!b) return a;
return a + ' ' + b;
}
var helpers = {
blockTransitions: function(node, duration) {
// we use a negative delay value since it performs blocking
// yet it doesn't kill any existing transitions running on the
// same element which makes this safe for class-based animations
var value = duration ? '-' + duration + 's' : '';
applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]);
return [TRANSITION_DELAY_PROP, value];
}
};
var $$rAFSchedulerFactory = ['$$rAF', function($$rAF) {
var queue, cancelFn;
function scheduler(tasks) {
// we make a copy since RAFScheduler mutates the state
// of the passed in array variable and this would be difficult
// to track down on the outside code
queue = queue.concat(tasks);
nextTick();
}
queue = scheduler.queue = [];
/* waitUntilQuiet does two things:
* 1. It will run the FINAL `fn` value only when an uncanceled RAF has passed through
* 2. It will delay the next wave of tasks from running until the quiet `fn` has run.
*
* The motivation here is that animation code can request more time from the scheduler
* before the next wave runs. This allows for certain DOM properties such as classes to
* be resolved in time for the next animation to run.
*/
scheduler.waitUntilQuiet = function(fn) {
if (cancelFn) cancelFn();
cancelFn = $$rAF(function() {
cancelFn = null;
fn();
nextTick();
});
};
return scheduler;
function nextTick() {
if (!queue.length) return;
var items = queue.shift();
for (var i = 0; i < items.length; i++) {
items[i]();
}
if (!cancelFn) {
$$rAF(function() {
if (!cancelFn) nextTick();
});
}
}
}];
/**
* @ngdoc directive
* @name ngAnimateChildren
* @restrict AE
* @element ANY
*
* @description
*
* ngAnimateChildren allows you to specify that children of this element should animate even if any
* of the children's parents are currently animating. By default, when an element has an active `enter`, `leave`, or `move`
* (structural) animation, child elements that also have an active structural animation are not animated.
*
* Note that even if `ngAnimateChildren` is set, no child animations will run when the parent element is removed from the DOM (`leave` animation).
*
*
* @param {string} ngAnimateChildren If the value is empty, `true` or `on`,
* then child animations are allowed. If the value is `false`, child animations are not allowed.
*
* @example
* <example module="ngAnimateChildren" name="ngAnimateChildren" deps="angular-animate.js" animations="true">
<file name="index.html">
<div ng-controller="MainController as main">
<label>Show container? <input type="checkbox" ng-model="main.enterElement" /></label>
<label>Animate children? <input type="checkbox" ng-model="main.animateChildren" /></label>
<hr>
<div ng-animate-children="{{main.animateChildren}}">
<div ng-if="main.enterElement" class="container">
List of items:
<div ng-repeat="item in [0, 1, 2, 3]" class="item">Item {{item}}</div>
</div>
</div>
</div>
</file>
<file name="animations.css">
.container.ng-enter,
.container.ng-leave {
transition: all ease 1.5s;
}
.container.ng-enter,
.container.ng-leave-active {
opacity: 0;
}
.container.ng-leave,
.container.ng-enter-active {
opacity: 1;
}
.item {
background: firebrick;
color: #FFF;
margin-bottom: 10px;
}
.item.ng-enter,
.item.ng-leave {
transition: transform 1.5s ease;
}
.item.ng-enter {
transform: translateX(50px);
}
.item.ng-enter-active {
transform: translateX(0);
}
</file>
<file name="script.js">
angular.module('ngAnimateChildren', ['ngAnimate'])
.controller('MainController', function MainController() {
this.animateChildren = false;
this.enterElement = false;
});
</file>
</example>
*/
var $$AnimateChildrenDirective = ['$interpolate', function($interpolate) {
return {
link: function(scope, element, attrs) {
var val = attrs.ngAnimateChildren;
if (isString(val) && val.length === 0) { //empty attribute
element.data(NG_ANIMATE_CHILDREN_DATA, true);
} else {
// Interpolate and set the value, so that it is available to
// animations that run right after compilation
setData($interpolate(val)(scope));
attrs.$observe('ngAnimateChildren', setData);
}
function setData(value) {
value = value === 'on' || value === 'true';
element.data(NG_ANIMATE_CHILDREN_DATA, value);
}
}
};
}];
/* exported $AnimateCssProvider */
var ANIMATE_TIMER_KEY = '$$animateCss';
/**
* @ngdoc service
* @name $animateCss
* @kind object
*
* @description
* The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes
* from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT
* to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or
* directives to create more complex animations that can be purely driven using CSS code.
*
* Note that only browsers that support CSS transitions and/or keyframe animations are capable of
* rendering animations triggered via `$animateCss` (bad news for IE9 and lower).
*
* ## General Use
* Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that
* is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however,
* any automatic control over cancelling animations and/or preventing animations from being run on
* child elements will not be handled by AngularJS. For this to work as expected, please use `$animate` to
* trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger
* the CSS animation.
*
* The example below shows how we can create a folding animation on an element using `ng-if`:
*
* ```html
* <!-- notice the `fold-animation` CSS class -->
* <div ng-if="onOff" class="fold-animation">
* This element will go BOOM
* </div>
* <button ng-click="onOff=true">Fold In</button>
* ```
*
* Now we create the **JavaScript animation** that will trigger the CSS transition:
*
* ```js
* ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
* return {
* enter: function(element, doneFn) {
* var height = element[0].offsetHeight;
* return $animateCss(element, {
* from: { height:'0px' },
* to: { height:height + 'px' },
* duration: 1 // one second
* });
* }
* }
* }]);
* ```
*
* ## More Advanced Uses
*
* `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks
* like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code.
*
* This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation,
* applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with
* `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order
* to provide a working animation that will run in CSS.
*
* The example below showcases a more advanced version of the `.fold-animation` from the example above:
*
* ```js
* ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
* return {
* enter: function(element, doneFn) {
* var height = element[0].offsetHeight;
* return $animateCss(element, {
* addClass: 'red large-text pulse-twice',
* easing: 'ease-out',
* from: { height:'0px' },
* to: { height:height + 'px' },
* duration: 1 // one second
* });
* }
* }
* }]);
* ```
*
* Since we're adding/removing CSS classes then the CSS transition will also pick those up:
*
* ```css
* /&#42; since a hardcoded duration value of 1 was provided in the JavaScript animation code,
* the CSS classes below will be transitioned despite them being defined as regular CSS classes &#42;/
* .red { background:red; }
* .large-text { font-size:20px; }
*
* /&#42; we can also use a keyframe animation and $animateCss will make it work alongside the transition &#42;/
* .pulse-twice {
* animation: 0.5s pulse linear 2;
* -webkit-animation: 0.5s pulse linear 2;
* }
*
* @keyframes pulse {
* from { transform: scale(0.5); }
* to { transform: scale(1.5); }
* }
*
* @-webkit-keyframes pulse {
* from { -webkit-transform: scale(0.5); }
* to { -webkit-transform: scale(1.5); }
* }
* ```
*
* Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen.
*
* ## How the Options are handled
*
* `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation
* 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
* styles using the `from` and `to` properties.
*
* ```js
* var animator = $animateCss(element, {
* from: { background:'red' },
* to: { background:'blue' }
* });
* animator.start();
* ```
*
* ```css
* .rotating-animation {
* animation:0.5s rotate linear;
* -webkit-animation:0.5s rotate linear;
* }
*
* @keyframes rotate {
* from { transform: rotate(0deg); }
* to { transform: rotate(360deg); }
* }
*
* @-webkit-keyframes rotate {
* from { -webkit-transform: rotate(0deg); }
* to { -webkit-transform: rotate(360deg); }
* }
* ```
*
* 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
* going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition
* 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
* 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
* and spread across the transition and keyframe animation.
*
* ## What is returned
*
* `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually
* 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
* added and removed on the element). Once `$animateCss` is called it will return an object with the following properties:
*
* ```js
* var animator = $animateCss(element, { ... });
* ```
*
* Now what do the contents of our `animator` variable look like:
*
* ```js
* {
* // starts the animation
* start: Function,
*
* // ends (aborts) the animation
* end: Function
* }
* ```
*
* 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.
* 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 styles may have been
* applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties
* and that changing them will not reconfigure the parameters of the animation.
*
* ### runner.done() vs runner.then()
* 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
* runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**.
* Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()`
* unless you really need a digest to kick off afterwards.
*
* 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
* (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code).
* Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works.
*
* @param {DOMElement} element the element that will be animated
* @param {object} options the animation-related options that will be applied during the animation
*
* * `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
* 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.)
* * `structural` - Indicates that the `ng-` prefix will be added to the event class. Setting to `false` or omitting will turn `ng-EVENT` and
* `ng-EVENT-active` in `EVENT` and `EVENT-active`. Unused if `event` is omitted.
* * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both).
* * `transitionStyle` - The raw CSS transition style that will be used (e.g. `1s linear all`).
* * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`).
* * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation.
* * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.
* * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation.
* * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation.
* * `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`
* is provided then the animation will be skipped entirely.
* * `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
* 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
* 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
* CSS delay value.
* * `stagger` - A numeric time value representing the delay between successively animated elements
* ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.})
* * `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
* `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`)
* * `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 occurring on the classes being added and removed.)
* * `cleanupStyles` - Whether or not the provided `from` and `to` styles will be removed once
* the animation is closed. This is useful for when the styles are used purely for the sake of
* the animation and do not have a lasting visual effect on the element (e.g. a collapse and open animation).
* By default this value is set to `false`.
*
* @return {object} an object with start and end methods and details about the animation.
*
* * `start` - The method to start the animation. This will return a `Promise` when called.
* * `end` - This method will cancel the animation and remove all applied CSS classes and styles.
*/
var ONE_SECOND = 1000;
var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
var CLOSING_TIME_BUFFER = 1.5;
var DETECT_CSS_PROPERTIES = {
transitionDuration: TRANSITION_DURATION_PROP,
transitionDelay: TRANSITION_DELAY_PROP,
transitionProperty: TRANSITION_PROP + PROPERTY_KEY,
animationDuration: ANIMATION_DURATION_PROP,
animationDelay: ANIMATION_DELAY_PROP,
animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY
};
var DETECT_STAGGER_CSS_PROPERTIES = {
transitionDuration: TRANSITION_DURATION_PROP,
transitionDelay: TRANSITION_DELAY_PROP,
animationDuration: ANIMATION_DURATION_PROP,
animationDelay: ANIMATION_DELAY_PROP
};
function getCssKeyframeDurationStyle(duration) {
return [ANIMATION_DURATION_PROP, duration + 's'];
}
function getCssDelayStyle(delay, isKeyframeAnimation) {
var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP;
return [prop, delay + 's'];
}
function computeCssStyles($window, element, properties) {
var styles = Object.create(null);
var detectedStyles = $window.getComputedStyle(element) || {};
forEach(properties, function(formalStyleName, actualStyleName) {
var val = detectedStyles[formalStyleName];
if (val) {
var c = val.charAt(0);
// only numerical-based values have a negative sign or digit as the first value
if (c === '-' || c === '+' || c >= 0) {
val = parseMaxTime(val);
}
// by setting this to null in the event that the delay is not set or is set directly as 0
// then we can still allow for negative values to be used later on and not mistake this
// value for being greater than any other negative value.
if (val === 0) {
val = null;
}
styles[actualStyleName] = val;
}
});
return styles;
}
function parseMaxTime(str) {
var maxValue = 0;
var values = str.split(/\s*,\s*/);
forEach(values, function(value) {
// it's always safe to consider only second values and omit `ms` values since
// getComputedStyle will always handle the conversion for us
if (value.charAt(value.length - 1) === 's') {
value = value.substring(0, value.length - 1);
}
value = parseFloat(value) || 0;
maxValue = maxValue ? Math.max(value, maxValue) : value;
});
return maxValue;
}
function truthyTimingValue(val) {
return val === 0 || val != null;
}
function getCssTransitionDurationStyle(duration, applyOnlyDuration) {
var style = TRANSITION_PROP;
var value = duration + 's';
if (applyOnlyDuration) {
style += DURATION_KEY;
} else {
value += ' linear all';
}
return [style, value];
}
// we do not reassign an already present style value since
// if we detect the style property value again we may be
// detecting styles that were added via the `from` styles.
// We make use of `isDefined` here since an empty string
// or null value (which is what getPropertyValue will return
// for a non-existing style) will still be marked as a valid
// value for the style (a falsy value implies that the style
// is to be removed at the end of the animation). If we had a simple
// "OR" statement then it would not be enough to catch that.
function registerRestorableStyles(backup, node, properties) {
forEach(properties, function(prop) {
backup[prop] = isDefined(backup[prop])
? backup[prop]
: node.style.getPropertyValue(prop);
});
}
var $AnimateCssProvider = ['$animateProvider', /** @this */ function($animateProvider) {
this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout', '$$animateCache',
'$$forceReflow', '$sniffer', '$$rAFScheduler', '$$animateQueue',
function($window, $$jqLite, $$AnimateRunner, $timeout, $$animateCache,
$$forceReflow, $sniffer, $$rAFScheduler, $$animateQueue) {
var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
function computeCachedCssStyles(node, className, cacheKey, allowNoDuration, properties) {
var timings = $$animateCache.get(cacheKey);
if (!timings) {
timings = computeCssStyles($window, node, properties);
if (timings.animationIterationCount === 'infinite') {
timings.animationIterationCount = 1;
}
}
// if a css animation has no duration we
// should mark that so that repeated addClass/removeClass calls are skipped
var hasDuration = allowNoDuration || (timings.transitionDuration > 0 || timings.animationDuration > 0);
// we keep putting this in multiple times even though the value and the cacheKey are the same
// because we're keeping an internal tally of how many duplicate animations are detected.
$$animateCache.put(cacheKey, timings, hasDuration);
return timings;
}
function computeCachedCssStaggerStyles(node, className, cacheKey, properties) {
var stagger;
var staggerCacheKey = 'stagger-' + cacheKey;
// if we have one or more existing matches of matching elements
// containing the same parent + CSS styles (which is how cacheKey works)
// then staggering is possible
if ($$animateCache.count(cacheKey) > 0) {
stagger = $$animateCache.get(staggerCacheKey);
if (!stagger) {
var staggerClassName = pendClasses(className, '-stagger');
$$jqLite.addClass(node, staggerClassName);
stagger = computeCssStyles($window, node, properties);
// force the conversion of a null value to zero incase not set
stagger.animationDuration = Math.max(stagger.animationDuration, 0);
stagger.transitionDuration = Math.max(stagger.transitionDuration, 0);
$$jqLite.removeClass(node, staggerClassName);
$$animateCache.put(staggerCacheKey, stagger, true);
}
}
return stagger || {};
}
var rafWaitQueue = [];
function waitUntilQuiet(callback) {
rafWaitQueue.push(callback);
$$rAFScheduler.waitUntilQuiet(function() {
$$animateCache.flush();
// DO NOT REMOVE THIS LINE OR REFACTOR OUT THE `pageWidth` variable.
// PLEASE EXAMINE THE `$$forceReflow` service to understand why.
var pageWidth = $$forceReflow();
// we use a for loop to ensure that if the queue is changed
// during this looping then it will consider new requests
for (var i = 0; i < rafWaitQueue.length; i++) {
rafWaitQueue[i](pageWidth);
}
rafWaitQueue.length = 0;
});
}
function computeTimings(node, className, cacheKey, allowNoDuration) {
var timings = computeCachedCssStyles(node, className, cacheKey, allowNoDuration, DETECT_CSS_PROPERTIES);
var aD = timings.animationDelay;
var tD = timings.transitionDelay;
timings.maxDelay = aD && tD
? Math.max(aD, tD)
: (aD || tD);
timings.maxDuration = Math.max(
timings.animationDuration * timings.animationIterationCount,
timings.transitionDuration);
return timings;
}
return function init(element, initialOptions) {
// all of the animation functions should create
// a copy of the options data, however, if a
// parent service has already created a copy then
// we should stick to using that
var options = initialOptions || {};
if (!options.$$prepared) {
options = prepareAnimationOptions(copy(options));
}
var restoreStyles = {};
var node = getDomNode(element);
if (!node
|| !node.parentNode
|| !$$animateQueue.enabled()) {
return closeAndReturnNoopAnimator();
}
var temporaryStyles = [];
var classes = element.attr('class');
var styles = packageStyles(options);
var animationClosed;
var animationPaused;
var animationCompleted;
var runner;
var runnerHost;
var maxDelay;
var maxDelayTime;
var maxDuration;
var maxDurationTime;
var startTime;
var events = [];
if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) {
return closeAndReturnNoopAnimator();
}
var method = options.event && isArray(options.event)
? options.event.join(' ')
: options.event;
var isStructural = method && options.structural;
var structuralClassName = '';
var addRemoveClassName = '';
if (isStructural) {
structuralClassName = pendClasses(method, EVENT_CLASS_PREFIX, true);
} else if (method) {
structuralClassName = method;
}
if (options.addClass) {
addRemoveClassName += pendClasses(options.addClass, ADD_CLASS_SUFFIX);
}
if (options.removeClass) {
if (addRemoveClassName.length) {
addRemoveClassName += ' ';
}
addRemoveClassName += pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX);
}
// there may be a situation where a structural animation is combined together
// with CSS classes that need to resolve before the animation is computed.
// However this means that there is no explicit CSS code to block the animation
// from happening (by setting 0s none in the class name). If this is the case
// we need to apply the classes before the first rAF so we know to continue if
// there actually is a detected transition or keyframe animation
if (options.applyClassesEarly && addRemoveClassName.length) {
applyAnimationClasses(element, options);
}
var preparationClasses = [structuralClassName, addRemoveClassName].join(' ').trim();
var fullClassName = classes + ' ' + preparationClasses;
var hasToStyles = styles.to && Object.keys(styles.to).length > 0;
var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0;
// there is no way we can trigger an animation if no styles and
// no classes are being applied which would then trigger a transition,
// unless there a is raw keyframe value that is applied to the element.
if (!containsKeyframeAnimation
&& !hasToStyles
&& !preparationClasses) {
return closeAndReturnNoopAnimator();
}
var stagger, cacheKey = $$animateCache.cacheKey(node, method, options.addClass, options.removeClass);
if ($$animateCache.containsCachedAnimationWithoutDuration(cacheKey)) {
preparationClasses = null;
return closeAndReturnNoopAnimator();
}
if (options.stagger > 0) {
var staggerVal = parseFloat(options.stagger);
stagger = {
transitionDelay: staggerVal,
animationDelay: staggerVal,
transitionDuration: 0,
animationDuration: 0
};
} else {
stagger = computeCachedCssStaggerStyles(node, preparationClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES);
}
if (!options.$$skipPreparationClasses) {
$$jqLite.addClass(element, preparationClasses);
}
var applyOnlyDuration;
if (options.transitionStyle) {
var transitionStyle = [TRANSITION_PROP, options.transitionStyle];
applyInlineStyle(node, transitionStyle);
temporaryStyles.push(transitionStyle);
}
if (options.duration >= 0) {
applyOnlyDuration = node.style[TRANSITION_PROP].length > 0;
var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration);
// we set the duration so that it will be picked up by getComputedStyle later
applyInlineStyle(node, durationStyle);
temporaryStyles.push(durationStyle);
}
if (options.keyframeStyle) {
var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle];
applyInlineStyle(node, keyframeStyle);
temporaryStyles.push(keyframeStyle);
}
var itemIndex = stagger
? options.staggerIndex >= 0
? options.staggerIndex
: $$animateCache.count(cacheKey)
: 0;
var isFirst = itemIndex === 0;
// this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY
// without causing any combination of transitions to kick in. By adding a negative delay value
// it forces the setup class' transition to end immediately. We later then remove the negative
// transition delay to allow for the transition to naturally do it's thing. The beauty here is
// that if there is no transition defined then nothing will happen and this will also allow
// other transitions to be stacked on top of each other without any chopping them out.
if (isFirst && !options.skipBlocking) {
helpers.blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE);
}
var timings = computeTimings(node, fullClassName, cacheKey, !isStructural);
var relativeDelay = timings.maxDelay;
maxDelay = Math.max(relativeDelay, 0);
maxDuration = timings.maxDuration;
var flags = {};
flags.hasTransitions = timings.transitionDuration > 0;
flags.hasAnimations = timings.animationDuration > 0;
flags.hasTransitionAll = flags.hasTransitions && timings.transitionProperty === 'all';
flags.applyTransitionDuration = hasToStyles && (
(flags.hasTransitions && !flags.hasTransitionAll)
|| (flags.hasAnimations && !flags.hasTransitions));
flags.applyAnimationDuration = options.duration && flags.hasAnimations;
flags.applyTransitionDelay = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions);
flags.applyAnimationDelay = truthyTimingValue(options.delay) && flags.hasAnimations;
flags.recalculateTimingStyles = addRemoveClassName.length > 0;
if (flags.applyTransitionDuration || flags.applyAnimationDuration) {
maxDuration = options.duration ? parseFloat(options.duration) : maxDuration;
if (flags.applyTransitionDuration) {
flags.hasTransitions = true;
timings.transitionDuration = maxDuration;
applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0;
temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration));
}
if (flags.applyAnimationDuration) {
flags.hasAnimations = true;
timings.animationDuration = maxDuration;
temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration));
}
}
if (maxDuration === 0 && !flags.recalculateTimingStyles) {
return closeAndReturnNoopAnimator();
}
var activeClasses = pendClasses(preparationClasses, ACTIVE_CLASS_SUFFIX);
if (options.delay != null) {
var delayStyle;
if (typeof options.delay !== 'boolean') {
delayStyle = parseFloat(options.delay);
// number in options.delay means we have to recalculate the delay for the closing timeout
maxDelay = Math.max(delayStyle, 0);
}
if (flags.applyTransitionDelay) {
temporaryStyles.push(getCssDelayStyle(delayStyle));
}
if (flags.applyAnimationDelay) {
temporaryStyles.push(getCssDelayStyle(delayStyle, true));
}
}
// we need to recalculate the delay value since we used a pre-emptive negative
// delay value and the delay value is required for the final event checking. This
// property will ensure that this will happen after the RAF phase has passed.
if (options.duration == null && timings.transitionDuration > 0) {
flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst;
}
maxDelayTime = maxDelay * ONE_SECOND;
maxDurationTime = maxDuration * ONE_SECOND;
if (!options.skipBlocking) {
flags.blockTransition = timings.transitionDuration > 0;
flags.blockKeyframeAnimation = timings.animationDuration > 0 &&
stagger.animationDelay > 0 &&
stagger.animationDuration === 0;
}
if (options.from) {
if (options.cleanupStyles) {
registerRestorableStyles(restoreStyles, node, Object.keys(options.from));
}
applyAnimationFromStyles(element, options);
}
if (flags.blockTransition || flags.blockKeyframeAnimation) {
applyBlocking(maxDuration);
} else if (!options.skipBlocking) {
helpers.blockTransitions(node, false);
}
// TODO(matsko): for 1.5 change this code to have an animator object for better debugging
return {
$$willAnimate: true,
end: endFn,
start: function() {
if (animationClosed) return;
runnerHost = {
end: endFn,
cancel: cancelFn,
resume: null, //this will be set during the start() phase
pause: null
};
runner = new $$AnimateRunner(runnerHost);
waitUntilQuiet(start);
// we don't have access to pause/resume the animation
// since it hasn't run yet. AnimateRunner will therefore
// set noop functions for resume and pause and they will
// later be overridden once the animation is triggered
return runner;
}
};
function endFn() {
close();
}
function cancelFn() {
close(true);
}
function close(rejected) {
// if the promise has been called already then we shouldn't close
// the animation again
if (animationClosed || (animationCompleted && animationPaused)) return;
animationClosed = true;
animationPaused = false;
if (preparationClasses && !options.$$skipPreparationClasses) {
$$jqLite.removeClass(element, preparationClasses);
}
if (activeClasses) {
$$jqLite.removeClass(element, activeClasses);
}
blockKeyframeAnimations(node, false);
helpers.blockTransitions(node, false);
forEach(temporaryStyles, function(entry) {
// There is only one way to remove inline style properties entirely from elements.
// By using `removeProperty` this works, but we need to convert camel-cased CSS
// styles down to hyphenated values.
node.style[entry[0]] = '';
});
applyAnimationClasses(element, options);
applyAnimationStyles(element, options);
if (Object.keys(restoreStyles).length) {
forEach(restoreStyles, function(value, prop) {
if (value) {
node.style.setProperty(prop, value);
} else {
node.style.removeProperty(prop);
}
});
}
// the reason why we have this option is to allow a synchronous closing callback
// that is fired as SOON as the animation ends (when the CSS is removed) or if
// the animation never takes off at all. A good example is a leave animation since
// the element must be removed just after the animation is over or else the element
// will appear on screen for one animation frame causing an overbearing flicker.
if (options.onDone) {
options.onDone();
}
if (events && events.length) {
// Remove the transitionend / animationend listener(s)
element.off(events.join(' '), onAnimationProgress);
}
//Cancel the fallback closing timeout and remove the timer data
var animationTimerData = element.data(ANIMATE_TIMER_KEY);
if (animationTimerData) {
$timeout.cancel(animationTimerData[0].timer);
element.removeData(ANIMATE_TIMER_KEY);
}
// if the preparation function fails then the promise is not setup
if (runner) {
runner.complete(!rejected);
}
}
function applyBlocking(duration) {
if (flags.blockTransition) {
helpers.blockTransitions(node, duration);
}
if (flags.blockKeyframeAnimation) {
blockKeyframeAnimations(node, !!duration);
}
}
function closeAndReturnNoopAnimator() {
runner = new $$AnimateRunner({
end: endFn,
cancel: cancelFn
});
// should flush the cache animation
waitUntilQuiet(noop);
close();
return {
$$willAnimate: false,
start: function() {
return runner;
},
end: endFn
};
}
function onAnimationProgress(event) {
event.stopPropagation();
var ev = event.originalEvent || event;
if (ev.target !== node) {
// Since TransitionEvent / AnimationEvent bubble up,
// we have to ignore events by finished child animations
return;
}
// we now always use `Date.now()` due to the recent changes with
// event.timeStamp in Firefox, Webkit and Chrome (see #13494 for more info)
var timeStamp = ev.$manualTimeStamp || Date.now();
/* Firefox (or possibly just Gecko) likes to not round values up
* when a ms measurement is used for the animation */
var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));
/* $manualTimeStamp is a mocked timeStamp value which is set
* within browserTrigger(). This is only here so that tests can
* mock animations properly. Real events fallback to event.timeStamp,
* or, if they don't, then a timeStamp is automatically created for them.
* We're checking to see if the timeStamp surpasses the expected delay,
* but we're using elapsedTime instead of the timeStamp on the 2nd
* pre-condition since animationPauseds sometimes close off early */
if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
// we set this flag to ensure that if the transition is paused then, when resumed,
// the animation will automatically close itself since transitions cannot be paused.
animationCompleted = true;
close();
}
}
function start() {
if (animationClosed) return;
if (!node.parentNode) {
close();
return;
}
// even though we only pause keyframe animations here the pause flag
// will still happen when transitions are used. Only the transition will
// not be paused since that is not possible. If the animation ends when
// paused then it will not complete until unpaused or cancelled.
var playPause = function(playAnimation) {
if (!animationCompleted) {
animationPaused = !playAnimation;
if (timings.animationDuration) {
var value = blockKeyframeAnimations(node, animationPaused);
if (animationPaused) {
temporaryStyles.push(value);
} else {
removeFromArray(temporaryStyles, value);
}
}
} else if (animationPaused && playAnimation) {
animationPaused = false;
close();
}
};
// checking the stagger duration prevents an accidentally cascade of the CSS delay style
// being inherited from the parent. If the transition duration is zero then we can safely
// rely that the delay value is an intentional stagger delay style.
var maxStagger = itemIndex > 0
&& ((timings.transitionDuration && stagger.transitionDuration === 0) ||
(timings.animationDuration && stagger.animationDuration === 0))
&& Math.max(stagger.animationDelay, stagger.transitionDelay);
if (maxStagger) {
$timeout(triggerAnimationStart,
Math.floor(maxStagger * itemIndex * ONE_SECOND),
false);
} else {
triggerAnimationStart();
}
// this will decorate the existing promise runner with pause/resume methods
runnerHost.resume = function() {
playPause(true);
};
runnerHost.pause = function() {
playPause(false);
};
function triggerAnimationStart() {
// just incase a stagger animation kicks in when the animation
// itself was cancelled entirely
if (animationClosed) return;
applyBlocking(false);
forEach(temporaryStyles, function(entry) {
var key = entry[0];
var value = entry[1];
node.style[key] = value;
});
applyAnimationClasses(element, options);
$$jqLite.addClass(element, activeClasses);
if (flags.recalculateTimingStyles) {
fullClassName = node.getAttribute('class') + ' ' + preparationClasses;
cacheKey = $$animateCache.cacheKey(node, method, options.addClass, options.removeClass);
timings = computeTimings(node, fullClassName, cacheKey, false);
relativeDelay = timings.maxDelay;
maxDelay = Math.max(relativeDelay, 0);
maxDuration = timings.maxDuration;
if (maxDuration === 0) {
close();
return;
}
flags.hasTransitions = timings.transitionDuration > 0;
flags.hasAnimations = timings.animationDuration > 0;
}
if (flags.applyAnimationDelay) {
relativeDelay = typeof options.delay !== 'boolean' && truthyTimingValue(options.delay)
? parseFloat(options.delay)
: relativeDelay;
maxDelay = Math.max(relativeDelay, 0);
timings.animationDelay = relativeDelay;
delayStyle = getCssDelayStyle(relativeDelay, true);
temporaryStyles.push(delayStyle);
node.style[delayStyle[0]] = delayStyle[1];
}
maxDelayTime = maxDelay * ONE_SECOND;
maxDurationTime = maxDuration * ONE_SECOND;
if (options.easing) {
var easeProp, easeVal = options.easing;
if (flags.hasTransitions) {
easeProp = TRANSITION_PROP + TIMING_KEY;
temporaryStyles.push([easeProp, easeVal]);
node.style[easeProp] = easeVal;
}
if (flags.hasAnimations) {
easeProp = ANIMATION_PROP + TIMING_KEY;
temporaryStyles.push([easeProp, easeVal]);
node.style[easeProp] = easeVal;
}
}
if (timings.transitionDuration) {
events.push(TRANSITIONEND_EVENT);
}
if (timings.animationDuration) {
events.push(ANIMATIONEND_EVENT);
}
startTime = Date.now();
var timerTime = maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime;
var endTime = startTime + timerTime;
var animationsData = element.data(ANIMATE_TIMER_KEY) || [];
var setupFallbackTimer = true;
if (animationsData.length) {
var currentTimerData = animationsData[0];
setupFallbackTimer = endTime > currentTimerData.expectedEndTime;
if (setupFallbackTimer) {
$timeout.cancel(currentTimerData.timer);
} else {
animationsData.push(close);
}
}
if (setupFallbackTimer) {
var timer = $timeout(onAnimationExpired, timerTime, false);
animationsData[0] = {
timer: timer,
expectedEndTime: endTime
};
animationsData.push(close);
element.data(ANIMATE_TIMER_KEY, animationsData);
}
if (events.length) {
element.on(events.join(' '), onAnimationProgress);
}
if (options.to) {
if (options.cleanupStyles) {
registerRestorableStyles(restoreStyles, node, Object.keys(options.to));
}
applyAnimationToStyles(element, options);
}
}
function onAnimationExpired() {
var animationsData = element.data(ANIMATE_TIMER_KEY);
// this will be false in the event that the element was
// removed from the DOM (via a leave animation or something
// similar)
if (animationsData) {
for (var i = 1; i < animationsData.length; i++) {
animationsData[i]();
}
element.removeData(ANIMATE_TIMER_KEY);
}
}
}
};
}];
}];
var $$AnimateCssDriverProvider = ['$$animationProvider', /** @this */ function($$animationProvider) {
$$animationProvider.drivers.push('$$animateCssDriver');
var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim';
var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor';
var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out';
var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in';
function isDocumentFragment(node) {
return node.parentNode && node.parentNode.nodeType === 11;
}
this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$sniffer', '$$jqLite', '$document',
function($animateCss, $rootScope, $$AnimateRunner, $rootElement, $sniffer, $$jqLite, $document) {
// only browsers that support these properties can render animations
if (!$sniffer.animations && !$sniffer.transitions) return noop;
var bodyNode = $document[0].body;
var rootNode = getDomNode($rootElement);
var rootBodyElement = jqLite(
// this is to avoid using something that exists outside of the body
// we also special case the doc fragment case because our unit test code
// appends the $rootElement to the body after the app has been bootstrapped
isDocumentFragment(rootNode) || bodyNode.contains(rootNode) ? rootNode : bodyNode
);
return function initDriverFn(animationDetails) {
return animationDetails.from && animationDetails.to
? prepareFromToAnchorAnimation(animationDetails.from,
animationDetails.to,
animationDetails.classes,
animationDetails.anchors)
: prepareRegularAnimation(animationDetails);
};
function filterCssClasses(classes) {
//remove all the `ng-` stuff
return classes.replace(/\bng-\S+\b/g, '');
}
function getUniqueValues(a, b) {
if (isString(a)) a = a.split(' ');
if (isString(b)) b = b.split(' ');
return a.filter(function(val) {
return b.indexOf(val) === -1;
}).join(' ');
}
function prepareAnchoredAnimation(classes, outAnchor, inAnchor) {
var clone = jqLite(getDomNode(outAnchor).cloneNode(true));
var startingClasses = filterCssClasses(getClassVal(clone));
outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME);
rootBodyElement.append(clone);
var animatorIn, animatorOut = prepareOutAnimation();
// the user may not end up using the `out` animation and
// only making use of the `in` animation or vice-versa.
// In either case we should allow this and not assume the
// animation is over unless both animations are not used.
if (!animatorOut) {
animatorIn = prepareInAnimation();
if (!animatorIn) {
return end();
}
}
var startingAnimator = animatorOut || animatorIn;
return {
start: function() {
var runner;
var currentAnimation = startingAnimator.start();
currentAnimation.done(function() {
currentAnimation = null;
if (!animatorIn) {
animatorIn = prepareInAnimation();
if (animatorIn) {
currentAnimation = animatorIn.start();
currentAnimation.done(function() {
currentAnimation = null;
end();
runner.complete();
});
return currentAnimation;
}
}
// in the event that there is no `in` animation
end();
runner.complete();
});
runner = new $$AnimateRunner({
end: endFn,
cancel: endFn
});
return runner;
function endFn() {
if (currentAnimation) {
currentAnimation.end();
}
}
}
};
function calculateAnchorStyles(anchor) {
var styles = {};
var coords = getDomNode(anchor).getBoundingClientRect();
// we iterate directly since safari messes up and doesn't return
// all the keys for the coords object when iterated
forEach(['width','height','top','left'], function(key) {
var value = coords[key];
switch (key) {
case 'top':
value += bodyNode.scrollTop;
break;
case 'left':
value += bodyNode.scrollLeft;
break;
}
styles[key] = Math.floor(value) + 'px';
});
return styles;
}
function prepareOutAnimation() {
var animator = $animateCss(clone, {
addClass: NG_OUT_ANCHOR_CLASS_NAME,
delay: true,
from: calculateAnchorStyles(outAnchor)
});
// read the comment within `prepareRegularAnimation` to understand
// why this check is necessary
return animator.$$willAnimate ? animator : null;
}
function getClassVal(element) {
return element.attr('class') || '';
}
function prepareInAnimation() {
var endingClasses = filterCssClasses(getClassVal(inAnchor));
var toAdd = getUniqueValues(endingClasses, startingClasses);
var toRemove = getUniqueValues(startingClasses, endingClasses);
var animator = $animateCss(clone, {
to: calculateAnchorStyles(inAnchor),
addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd,
removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove,
delay: true
});
// read the comment within `prepareRegularAnimation` to understand
// why this check is necessary
return animator.$$willAnimate ? animator : null;
}
function end() {
clone.remove();
outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
}
}
function prepareFromToAnchorAnimation(from, to, classes, anchors) {
var fromAnimation = prepareRegularAnimation(from, noop);
var toAnimation = prepareRegularAnimation(to, noop);
var anchorAnimations = [];
forEach(anchors, function(anchor) {
var outElement = anchor['out'];
var inElement = anchor['in'];
var animator = prepareAnchoredAnimation(classes, outElement, inElement);
if (animator) {
anchorAnimations.push(animator);
}
});
// no point in doing anything when there are no elements to animate
if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return;
return {
start: function() {
var animationRunners = [];
if (fromAnimation) {
animationRunners.push(fromAnimation.start());
}
if (toAnimation) {
animationRunners.push(toAnimation.start());
}
forEach(anchorAnimations, function(animation) {
animationRunners.push(animation.start());
});
var runner = new $$AnimateRunner({
end: endFn,
cancel: endFn // CSS-driven animations cannot be cancelled, only ended
});
$$AnimateRunner.all(animationRunners, function(status) {
runner.complete(status);
});
return runner;
function endFn() {
forEach(animationRunners, function(runner) {
runner.end();
});
}
}
};
}
function prepareRegularAnimation(animationDetails) {
var element = animationDetails.element;
var options = animationDetails.options || {};
if (animationDetails.structural) {
options.event = animationDetails.event;
options.structural = true;
options.applyClassesEarly = true;
// we special case the leave animation since we want to ensure that
// the element is removed as soon as the animation is over. Otherwise
// a flicker might appear or the element may not be removed at all
if (animationDetails.event === 'leave') {
options.onDone = options.domOperation;
}
}
// We assign the preparationClasses as the actual animation event since
// the internals of $animateCss will just suffix the event token values
// with `-active` to trigger the animation.
if (options.preparationClasses) {
options.event = concatWithSpace(options.event, options.preparationClasses);
}
var animator = $animateCss(element, options);
// the driver lookup code inside of $$animation attempts to spawn a
// driver one by one until a driver returns a.$$willAnimate animator object.
// $animateCss will always return an object, however, it will pass in
// a flag as a hint as to whether an animation was detected or not
return animator.$$willAnimate ? animator : null;
}
}];
}];
// TODO(matsko): use caching here to speed things up for detection
// TODO(matsko): add documentation
// by the time...
var $$AnimateJsProvider = ['$animateProvider', /** @this */ function($animateProvider) {
this.$get = ['$injector', '$$AnimateRunner', '$$jqLite',
function($injector, $$AnimateRunner, $$jqLite) {
var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
// $animateJs(element, 'enter');
return function(element, event, classes, options) {
var animationClosed = false;
// the `classes` argument is optional and if it is not used
// then the classes will be resolved from the element's className
// property as well as options.addClass/options.removeClass.
if (arguments.length === 3 && isObject(classes)) {
options = classes;
classes = null;
}
options = prepareAnimationOptions(options);
if (!classes) {
classes = element.attr('class') || '';
if (options.addClass) {
classes += ' ' + options.addClass;
}
if (options.removeClass) {
classes += ' ' + options.removeClass;
}
}
var classesToAdd = options.addClass;
var classesToRemove = options.removeClass;
// the lookupAnimations function returns a series of animation objects that are
// matched up with one or more of the CSS classes. These animation objects are
// defined via the module.animation factory function. If nothing is detected then
// we don't return anything which then makes $animation query the next driver.
var animations = lookupAnimations(classes);
var before, after;
if (animations.length) {
var afterFn, beforeFn;
if (event === 'leave') {
beforeFn = 'leave';
afterFn = 'afterLeave'; // TODO(matsko): get rid of this
} else {
beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1);
afterFn = event;
}
if (event !== 'enter' && event !== 'move') {
before = packageAnimations(element, event, options, animations, beforeFn);
}
after = packageAnimations(element, event, options, animations, afterFn);
}
// no matching animations
if (!before && !after) return;
function applyOptions() {
options.domOperation();
applyAnimationClasses(element, options);
}
function close() {
animationClosed = true;
applyOptions();
applyAnimationStyles(element, options);
}
var runner;
return {
$$willAnimate: true,
end: function() {
if (runner) {
runner.end();
} else {
close();
runner = new $$AnimateRunner();
runner.complete(true);
}
return runner;
},
start: function() {
if (runner) {
return runner;
}
runner = new $$AnimateRunner();
var closeActiveAnimations;
var chain = [];
if (before) {
chain.push(function(fn) {
closeActiveAnimations = before(fn);
});
}
if (chain.length) {
chain.push(function(fn) {
applyOptions();
fn(true);
});
} else {
applyOptions();
}
if (after) {
chain.push(function(fn) {
closeActiveAnimations = after(fn);
});
}
runner.setHost({
end: function() {
endAnimations();
},
cancel: function() {
endAnimations(true);
}
});
$$AnimateRunner.chain(chain, onComplete);
return runner;
function onComplete(success) {
close(success);
runner.complete(success);
}
function endAnimations(cancelled) {
if (!animationClosed) {
(closeActiveAnimations || noop)(cancelled);
onComplete(cancelled);
}
}
}
};
function executeAnimationFn(fn, element, event, options, onDone) {
var args;
switch (event) {
case 'animate':
args = [element, options.from, options.to, onDone];
break;
case 'setClass':
args = [element, classesToAdd, classesToRemove, onDone];
break;
case 'addClass':
args = [element, classesToAdd, onDone];
break;
case 'removeClass':
args = [element, classesToRemove, onDone];
break;
default:
args = [element, onDone];
break;
}
args.push(options);
var value = fn.apply(fn, args);
if (value) {
if (isFunction(value.start)) {
value = value.start();
}
if (value instanceof $$AnimateRunner) {
value.done(onDone);
} else if (isFunction(value)) {
// optional onEnd / onCancel callback
return value;
}
}
return noop;
}
function groupEventedAnimations(element, event, options, animations, fnName) {
var operations = [];
forEach(animations, function(ani) {
var animation = ani[fnName];
if (!animation) return;
// note that all of these animations will run in parallel
operations.push(function() {
var runner;
var endProgressCb;
var resolved = false;
var onAnimationComplete = function(rejected) {
if (!resolved) {
resolved = true;
(endProgressCb || noop)(rejected);
runner.complete(!rejected);
}
};
runner = new $$AnimateRunner({
end: function() {
onAnimationComplete();
},
cancel: function() {
onAnimationComplete(true);
}
});
endProgressCb = executeAnimationFn(animation, element, event, options, function(result) {
var cancelled = result === false;
onAnimationComplete(cancelled);
});
return runner;
});
});
return operations;
}
function packageAnimations(element, event, options, animations, fnName) {
var operations = groupEventedAnimations(element, event, options, animations, fnName);
if (operations.length === 0) {
var a, b;
if (fnName === 'beforeSetClass') {
a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass');
b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass');
} else if (fnName === 'setClass') {
a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass');
b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass');
}
if (a) {
operations = operations.concat(a);
}
if (b) {
operations = operations.concat(b);
}
}
if (operations.length === 0) return;
// TODO(matsko): add documentation
return function startAnimation(callback) {
var runners = [];
if (operations.length) {
forEach(operations, function(animateFn) {
runners.push(animateFn());
});
}
if (runners.length) {
$$AnimateRunner.all(runners, callback);
} else {
callback();
}
return function endFn(reject) {
forEach(runners, function(runner) {
if (reject) {
runner.cancel();
} else {
runner.end();
}
});
};
};
}
};
function lookupAnimations(classes) {
classes = isArray(classes) ? classes : classes.split(' ');
var matches = [], flagMap = {};
for (var i = 0; i < classes.length; i++) {
var klass = classes[i],
animationFactory = $animateProvider.$$registeredAnimations[klass];
if (animationFactory && !flagMap[klass]) {
matches.push($injector.get(animationFactory));
flagMap[klass] = true;
}
}
return matches;
}
}];
}];
var $$AnimateJsDriverProvider = ['$$animationProvider', /** @this */ function($$animationProvider) {
$$animationProvider.drivers.push('$$animateJsDriver');
this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) {
return function initDriverFn(animationDetails) {
if (animationDetails.from && animationDetails.to) {
var fromAnimation = prepareAnimation(animationDetails.from);
var toAnimation = prepareAnimation(animationDetails.to);
if (!fromAnimation && !toAnimation) return;
return {
start: function() {
var animationRunners = [];
if (fromAnimation) {
animationRunners.push(fromAnimation.start());
}
if (toAnimation) {
animationRunners.push(toAnimation.start());
}
$$AnimateRunner.all(animationRunners, done);
var runner = new $$AnimateRunner({
end: endFnFactory(),
cancel: endFnFactory()
});
return runner;
function endFnFactory() {
return function() {
forEach(animationRunners, function(runner) {
// at this point we cannot cancel animations for groups just yet. 1.5+
runner.end();
});
};
}
function done(status) {
runner.complete(status);
}
}
};
} else {
return prepareAnimation(animationDetails);
}
};
function prepareAnimation(animationDetails) {
// TODO(matsko): make sure to check for grouped animations and delegate down to normal animations
var element = animationDetails.element;
var event = animationDetails.event;
var options = animationDetails.options;
var classes = animationDetails.classes;
return $$animateJs(element, event, classes, options);
}
}];
}];
var NG_ANIMATE_ATTR_NAME = 'data-ng-animate';
var NG_ANIMATE_PIN_DATA = '$ngAnimatePin';
var $$AnimateQueueProvider = ['$animateProvider', /** @this */ function($animateProvider) {
var PRE_DIGEST_STATE = 1;
var RUNNING_STATE = 2;
var ONE_SPACE = ' ';
var rules = this.rules = {
skip: [],
cancel: [],
join: []
};
function getEventData(options) {
return {
addClass: options.addClass,
removeClass: options.removeClass,
from: options.from,
to: options.to
};
}
function makeTruthyCssClassMap(classString) {
if (!classString) {
return null;
}
var keys = classString.split(ONE_SPACE);
var map = Object.create(null);
forEach(keys, function(key) {
map[key] = true;
});
return map;
}
function hasMatchingClasses(newClassString, currentClassString) {
if (newClassString && currentClassString) {
var currentClassMap = makeTruthyCssClassMap(currentClassString);
return newClassString.split(ONE_SPACE).some(function(className) {
return currentClassMap[className];
});
}
}
function isAllowed(ruleType, currentAnimation, previousAnimation) {
return rules[ruleType].some(function(fn) {
return fn(currentAnimation, previousAnimation);
});
}
function hasAnimationClasses(animation, and) {
var a = (animation.addClass || '').length > 0;
var b = (animation.removeClass || '').length > 0;
return and ? a && b : a || b;
}
rules.join.push(function(newAnimation, currentAnimation) {
// if the new animation is class-based then we can just tack that on
return !newAnimation.structural && hasAnimationClasses(newAnimation);
});
rules.skip.push(function(newAnimation, currentAnimation) {
// there is no need to animate anything if no classes are being added and
// there is no structural animation that will be triggered
return !newAnimation.structural && !hasAnimationClasses(newAnimation);
});
rules.skip.push(function(newAnimation, currentAnimation) {
// why should we trigger a new structural animation if the element will
// be removed from the DOM anyway?
return currentAnimation.event === 'leave' && newAnimation.structural;
});
rules.skip.push(function(newAnimation, currentAnimation) {
// if there is an ongoing current animation then don't even bother running the class-based animation
return currentAnimation.structural && currentAnimation.state === RUNNING_STATE && !newAnimation.structural;
});
rules.cancel.push(function(newAnimation, currentAnimation) {
// there can never be two structural animations running at the same time
return currentAnimation.structural && newAnimation.structural;
});
rules.cancel.push(function(newAnimation, currentAnimation) {
// if the previous animation is already running, but the new animation will
// be triggered, but the new animation is structural
return currentAnimation.state === RUNNING_STATE && newAnimation.structural;
});
rules.cancel.push(function(newAnimation, currentAnimation) {
// cancel the animation if classes added / removed in both animation cancel each other out,
// but only if the current animation isn't structural
if (currentAnimation.structural) return false;
var nA = newAnimation.addClass;
var nR = newAnimation.removeClass;
var cA = currentAnimation.addClass;
var cR = currentAnimation.removeClass;
// early detection to save the global CPU shortage :)
if ((isUndefined(nA) && isUndefined(nR)) || (isUndefined(cA) && isUndefined(cR))) {
return false;
}
return hasMatchingClasses(nA, cR) || hasMatchingClasses(nR, cA);
});
this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$Map',
'$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite', '$$forceReflow',
'$$isDocumentHidden',
function($$rAF, $rootScope, $rootElement, $document, $$Map,
$$animation, $$AnimateRunner, $templateRequest, $$jqLite, $$forceReflow,
$$isDocumentHidden) {
var activeAnimationsLookup = new $$Map();
var disabledElementsLookup = new $$Map();
var animationsEnabled = null;
function removeFromDisabledElementsLookup(evt) {
disabledElementsLookup.delete(evt.target);
}
function postDigestTaskFactory() {
var postDigestCalled = false;
return function(fn) {
// we only issue a call to postDigest before
// it has first passed. This prevents any callbacks
// from not firing once the animation has completed
// since it will be out of the digest cycle.
if (postDigestCalled) {
fn();
} else {
$rootScope.$$postDigest(function() {
postDigestCalled = true;
fn();
});
}
};
}
// Wait until all directive and route-related templates are downloaded and
// compiled. The $templateRequest.totalPendingRequests variable keeps track of
// all of the remote templates being currently downloaded. If there are no
// templates currently downloading then the watcher will still fire anyway.
var deregisterWatch = $rootScope.$watch(
function() { return $templateRequest.totalPendingRequests === 0; },
function(isEmpty) {
if (!isEmpty) return;
deregisterWatch();
// Now that all templates have been downloaded, $animate will wait until
// the post digest queue is empty before enabling animations. By having two
// calls to $postDigest calls we can ensure that the flag is enabled at the
// very end of the post digest queue. Since all of the animations in $animate
// use $postDigest, it's important that the code below executes at the end.
// This basically means that the page is fully downloaded and compiled before
// any animations are triggered.
$rootScope.$$postDigest(function() {
$rootScope.$$postDigest(function() {
// we check for null directly in the event that the application already called
// .enabled() with whatever arguments that it provided it with
if (animationsEnabled === null) {
animationsEnabled = true;
}
});
});
}
);
var callbackRegistry = Object.create(null);
// remember that the `customFilter`/`classNameFilter` are set during the
// provider/config stage therefore we can optimize here and setup helper functions
var customFilter = $animateProvider.customFilter();
var classNameFilter = $animateProvider.classNameFilter();
var returnTrue = function() { return true; };
var isAnimatableByFilter = customFilter || returnTrue;
var isAnimatableClassName = !classNameFilter ? returnTrue : function(node, options) {
var className = [node.getAttribute('class'), options.addClass, options.removeClass].join(' ');
return classNameFilter.test(className);
};
var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
function normalizeAnimationDetails(element, animation) {
return mergeAnimationDetails(element, animation, {});
}
// IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
var contains = window.Node.prototype.contains || /** @this */ function(arg) {
// eslint-disable-next-line no-bitwise
return this === arg || !!(this.compareDocumentPosition(arg) & 16);
};
function findCallbacks(targetParentNode, targetNode, event) {
var matches = [];
var entries = callbackRegistry[event];
if (entries) {
forEach(entries, function(entry) {
if (contains.call(entry.node, targetNode)) {
matches.push(entry.callback);
} else if (event === 'leave' && contains.call(entry.node, targetParentNode)) {
matches.push(entry.callback);
}
});
}
return matches;
}
function filterFromRegistry(list, matchContainer, matchCallback) {
var containerNode = extractElementNode(matchContainer);
return list.filter(function(entry) {
var isMatch = entry.node === containerNode &&
(!matchCallback || entry.callback === matchCallback);
return !isMatch;
});
}
function cleanupEventListeners(phase, node) {
if (phase === 'close' && !node.parentNode) {
// If the element is not attached to a parentNode, it has been removed by
// the domOperation, and we can safely remove the event callbacks
$animate.off(node);
}
}
var $animate = {
on: function(event, container, callback) {
var node = extractElementNode(container);
callbackRegistry[event] = callbackRegistry[event] || [];
callbackRegistry[event].push({
node: node,
callback: callback
});
// Remove the callback when the element is removed from the DOM
jqLite(container).on('$destroy', function() {
var animationDetails = activeAnimationsLookup.get(node);
if (!animationDetails) {
// If there's an animation ongoing, the callback calling code will remove
// the event listeners. If we'd remove here, the callbacks would be removed
// before the animation ends
$animate.off(event, container, callback);
}
});
},
off: function(event, container, callback) {
if (arguments.length === 1 && !isString(arguments[0])) {
container = arguments[0];
for (var eventType in callbackRegistry) {
callbackRegistry[eventType] = filterFromRegistry(callbackRegistry[eventType], container);
}
return;
}
var entries = callbackRegistry[event];
if (!entries) return;
callbackRegistry[event] = arguments.length === 1
? null
: filterFromRegistry(entries, container, callback);
},
pin: function(element, parentElement) {
assertArg(isElement(element), 'element', 'not an element');
assertArg(isElement(parentElement), 'parentElement', 'not an element');
element.data(NG_ANIMATE_PIN_DATA, parentElement);
},
push: function(element, event, options, domOperation) {
options = options || {};
options.domOperation = domOperation;
return queueAnimation(element, event, options);
},
// this method has four signatures:
// () - global getter
// (bool) - global setter
// (element) - element getter
// (element, bool) - element setter<F37>
enabled: function(element, bool) {
var argCount = arguments.length;
if (argCount === 0) {
// () - Global getter
bool = !!animationsEnabled;
} else {
var hasElement = isElement(element);
if (!hasElement) {
// (bool) - Global setter
bool = animationsEnabled = !!element;
} else {
var node = getDomNode(element);
if (argCount === 1) {
// (element) - Element getter
bool = !disabledElementsLookup.get(node);
} else {
// (element, bool) - Element setter
if (!disabledElementsLookup.has(node)) {
// The element is added to the map for the first time.
// Create a listener to remove it on `$destroy` (to avoid memory leak).
jqLite(element).on('$destroy', removeFromDisabledElementsLookup);
}
disabledElementsLookup.set(node, !bool);
}
}
}
return bool;
}
};
return $animate;
function queueAnimation(originalElement, event, initialOptions) {
// we always make a copy of the options since
// there should never be any side effects on
// the input data when running `$animateCss`.
var options = copy(initialOptions);
var element = stripCommentsFromElement(originalElement);
var node = getDomNode(element);
var parentNode = node && node.parentNode;
options = prepareAnimationOptions(options);
// we create a fake runner with a working promise.
// These methods will become available after the digest has passed
var runner = new $$AnimateRunner();
// this is used to trigger callbacks in postDigest mode
var runInNextPostDigestOrNow = postDigestTaskFactory();
if (isArray(options.addClass)) {
options.addClass = options.addClass.join(' ');
}
if (options.addClass && !isString(options.addClass)) {
options.addClass = null;
}
if (isArray(options.removeClass)) {
options.removeClass = options.removeClass.join(' ');
}
if (options.removeClass && !isString(options.removeClass)) {
options.removeClass = null;
}
if (options.from && !isObject(options.from)) {
options.from = null;
}
if (options.to && !isObject(options.to)) {
options.to = null;
}
// If animations are hard-disabled for the whole application there is no need to continue.
// There are also situations where a directive issues an animation for a jqLite wrapper that
// contains only comment nodes. In this case, there is no way we can perform an animation.
if (!animationsEnabled ||
!node ||
!isAnimatableByFilter(node, event, initialOptions) ||
!isAnimatableClassName(node, options)) {
close();
return runner;
}
var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
var documentHidden = $$isDocumentHidden();
// This is a hard disable of all animations the element itself, therefore there is no need to
// continue further past this point if not enabled
// Animations are also disabled if the document is currently hidden (page is not visible
// to the user), because browsers slow down or do not flush calls to requestAnimationFrame
var skipAnimations = documentHidden || disabledElementsLookup.get(node);
var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {};
var hasExistingAnimation = !!existingAnimation.state;
// there is no point in traversing the same collection of parent ancestors if a followup
// animation will be run on the same element that already did all that checking work
if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state !== PRE_DIGEST_STATE)) {
skipAnimations = !areAnimationsAllowed(node, parentNode, event);
}
if (skipAnimations) {
// Callbacks should fire even if the document is hidden (regression fix for issue #14120)
if (documentHidden) notifyProgress(runner, event, 'start', getEventData(options));
close();
if (documentHidden) notifyProgress(runner, event, 'close', getEventData(options));
return runner;
}
if (isStructural) {
closeChildAnimations(node);
}
var newAnimation = {
structural: isStructural,
element: element,
event: event,
addClass: options.addClass,
removeClass: options.removeClass,
close: close,
options: options,
runner: runner
};
if (hasExistingAnimation) {
var skipAnimationFlag = isAllowed('skip', newAnimation, existingAnimation);
if (skipAnimationFlag) {
if (existingAnimation.state === RUNNING_STATE) {
close();
return runner;
} else {
mergeAnimationDetails(element, existingAnimation, newAnimation);
return existingAnimation.runner;
}
}
var cancelAnimationFlag = isAllowed('cancel', newAnimation, existingAnimation);
if (cancelAnimationFlag) {
if (existingAnimation.state === RUNNING_STATE) {
// this will end the animation right away and it is safe
// to do so since the animation is already running and the
// runner callback code will run in async
existingAnimation.runner.end();
} else if (existingAnimation.structural) {
// this means that the animation is queued into a digest, but
// hasn't started yet. Therefore it is safe to run the close
// method which will call the runner methods in async.
existingAnimation.close();
} else {
// this will merge the new animation options into existing animation options
mergeAnimationDetails(element, existingAnimation, newAnimation);
return existingAnimation.runner;
}
} else {
// a joined animation means that this animation will take over the existing one
// so an example would involve a leave animation taking over an enter. Then when
// the postDigest kicks in the enter will be ignored.
var joinAnimationFlag = isAllowed('join', newAnimation, existingAnimation);
if (joinAnimationFlag) {
if (existingAnimation.state === RUNNING_STATE) {
normalizeAnimationDetails(element, newAnimation);
} else {
applyGeneratedPreparationClasses($$jqLite, element, isStructural ? event : null, options);
event = newAnimation.event = existingAnimation.event;
options = mergeAnimationDetails(element, existingAnimation, newAnimation);
//we return the same runner since only the option values of this animation will
//be fed into the `existingAnimation`.
return existingAnimation.runner;
}
}
}
} else {
// normalization in this case means that it removes redundant CSS classes that
// already exist (addClass) or do not exist (removeClass) on the element
normalizeAnimationDetails(element, newAnimation);
}
// when the options are merged and cleaned up we may end up not having to do
// an animation at all, therefore we should check this before issuing a post
// digest callback. Structural animations will always run no matter what.
var isValidAnimation = newAnimation.structural;
if (!isValidAnimation) {
// animate (from/to) can be quickly checked first, otherwise we check if any classes are present
isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0)
|| hasAnimationClasses(newAnimation);
}
if (!isValidAnimation) {
close();
clearElementAnimationState(node);
return runner;
}
// the counter keeps track of cancelled animations
var counter = (existingAnimation.counter || 0) + 1;
newAnimation.counter = counter;
markElementAnimationState(node, PRE_DIGEST_STATE, newAnimation);
$rootScope.$$postDigest(function() {
// It is possible that the DOM nodes inside `originalElement` have been replaced. This can
// happen if the animated element is a transcluded clone and also has a `templateUrl`
// directive on it. Therefore, we must recreate `element` in order to interact with the
// actual DOM nodes.
// Note: We still need to use the old `node` for certain things, such as looking up in
// HashMaps where it was used as the key.
element = stripCommentsFromElement(originalElement);
var animationDetails = activeAnimationsLookup.get(node);
var animationCancelled = !animationDetails;
animationDetails = animationDetails || {};
// if addClass/removeClass is called before something like enter then the
// registered parent element may not be present. The code below will ensure
// that a final value for parent element is obtained
var parentElement = element.parent() || [];
// animate/structural/class-based animations all have requirements. Otherwise there
// is no point in performing an animation. The parent node must also be set.
var isValidAnimation = parentElement.length > 0
&& (animationDetails.event === 'animate'
|| animationDetails.structural
|| hasAnimationClasses(animationDetails));
// this means that the previous animation was cancelled
// even if the follow-up animation is the same event
if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) {
// if another animation did not take over then we need
// to make sure that the domOperation and options are
// handled accordingly
if (animationCancelled) {
applyAnimationClasses(element, options);
applyAnimationStyles(element, options);
}
// if the event changed from something like enter to leave then we do
// it, otherwise if it's the same then the end result will be the same too
if (animationCancelled || (isStructural && animationDetails.event !== event)) {
options.domOperation();
runner.end();
}
// in the event that the element animation was not cancelled or a follow-up animation
// isn't allowed to animate from here then we need to clear the state of the element
// so that any future animations won't read the expired animation data.
if (!isValidAnimation) {
clearElementAnimationState(node);
}
return;
}
// this combined multiple class to addClass / removeClass into a setClass event
// so long as a structural event did not take over the animation
event = !animationDetails.structural && hasAnimationClasses(animationDetails, true)
? 'setClass'
: animationDetails.event;
markElementAnimationState(node, RUNNING_STATE);
var realRunner = $$animation(element, event, animationDetails.options);
// this will update the runner's flow-control events based on
// the `realRunner` object.
runner.setHost(realRunner);
notifyProgress(runner, event, 'start', getEventData(options));
realRunner.done(function(status) {
close(!status);
var animationDetails = activeAnimationsLookup.get(node);
if (animationDetails && animationDetails.counter === counter) {
clearElementAnimationState(node);
}
notifyProgress(runner, event, 'close', getEventData(options));
});
});
return runner;
function notifyProgress(runner, event, phase, data) {
runInNextPostDigestOrNow(function() {
var callbacks = findCallbacks(parentNode, node, event);
if (callbacks.length) {
// do not optimize this call here to RAF because
// we don't know how heavy the callback code here will
// be and if this code is buffered then this can
// lead to a performance regression.
$$rAF(function() {
forEach(callbacks, function(callback) {
callback(element, phase, data);
});
cleanupEventListeners(phase, node);
});
} else {
cleanupEventListeners(phase, node);
}
});
runner.progress(event, phase, data);
}
function close(reject) {
clearGeneratedClasses(element, options);
applyAnimationClasses(element, options);
applyAnimationStyles(element, options);
options.domOperation();
runner.complete(!reject);
}
}
function closeChildAnimations(node) {
var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']');
forEach(children, function(child) {
var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME), 10);
var animationDetails = activeAnimationsLookup.get(child);
if (animationDetails) {
switch (state) {
case RUNNING_STATE:
animationDetails.runner.end();
/* falls through */
case PRE_DIGEST_STATE:
activeAnimationsLookup.delete(child);
break;
}
}
});
}
function clearElementAnimationState(node) {
node.removeAttribute(NG_ANIMATE_ATTR_NAME);
activeAnimationsLookup.delete(node);
}
/**
* This fn returns false if any of the following is true:
* a) animations on any parent element are disabled, and animations on the element aren't explicitly allowed
* b) a parent element has an ongoing structural animation, and animateChildren is false
* c) the element is not a child of the body
* d) the element is not a child of the $rootElement
*/
function areAnimationsAllowed(node, parentNode, event) {
var bodyNode = $document[0].body;
var rootNode = getDomNode($rootElement);
var bodyNodeDetected = (node === bodyNode) || node.nodeName === 'HTML';
var rootNodeDetected = (node === rootNode);
var parentAnimationDetected = false;
var elementDisabled = disabledElementsLookup.get(node);
var animateChildren;
var parentHost = jqLite.data(node, NG_ANIMATE_PIN_DATA);
if (parentHost) {
parentNode = getDomNode(parentHost);
}
while (parentNode) {
if (!rootNodeDetected) {
// AngularJS doesn't want to attempt to animate elements outside of the application
// therefore we need to ensure that the rootElement is an ancestor of the current element
rootNodeDetected = (parentNode === rootNode);
}
if (parentNode.nodeType !== ELEMENT_NODE) {
// no point in inspecting the #document element
break;
}
var details = activeAnimationsLookup.get(parentNode) || {};
// either an enter, leave or move animation will commence
// therefore we can't allow any animations to take place
// but if a parent animation is class-based then that's ok
if (!parentAnimationDetected) {
var parentNodeDisabled = disabledElementsLookup.get(parentNode);
if (parentNodeDisabled === true && elementDisabled !== false) {
// disable animations if the user hasn't explicitly enabled animations on the
// current element
elementDisabled = true;
// element is disabled via parent element, no need to check anything else
break;
} else if (parentNodeDisabled === false) {
elementDisabled = false;
}
parentAnimationDetected = details.structural;
}
if (isUndefined(animateChildren) || animateChildren === true) {
var value = jqLite.data(parentNode, NG_ANIMATE_CHILDREN_DATA);
if (isDefined(value)) {
animateChildren = value;
}
}
// there is no need to continue traversing at this point
if (parentAnimationDetected && animateChildren === false) break;
if (!bodyNodeDetected) {
// we also need to ensure that the element is or will be a part of the body element
// otherwise it is pointless to even issue an animation to be rendered
bodyNodeDetected = (parentNode === bodyNode);
}
if (bodyNodeDetected && rootNodeDetected) {
// If both body and root have been found, any other checks are pointless,
// as no animation data should live outside the application
break;
}
if (!rootNodeDetected) {
// If `rootNode` is not detected, check if `parentNode` is pinned to another element
parentHost = jqLite.data(parentNode, NG_ANIMATE_PIN_DATA);
if (parentHost) {
// The pin target element becomes the next parent element
parentNode = getDomNode(parentHost);
continue;
}
}
parentNode = parentNode.parentNode;
}
var allowAnimation = (!parentAnimationDetected || animateChildren) && elementDisabled !== true;
return allowAnimation && rootNodeDetected && bodyNodeDetected;
}
function markElementAnimationState(node, state, details) {
details = details || {};
details.state = state;
node.setAttribute(NG_ANIMATE_ATTR_NAME, state);
var oldValue = activeAnimationsLookup.get(node);
var newValue = oldValue
? extend(oldValue, details)
: details;
activeAnimationsLookup.set(node, newValue);
}
}];
}];
/** @this */
var $$AnimateCacheProvider = function() {
var KEY = '$$ngAnimateParentKey';
var parentCounter = 0;
var cache = Object.create(null);
this.$get = [function() {
return {
cacheKey: function(node, method, addClass, removeClass) {
var parentNode = node.parentNode;
var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter);
var parts = [parentID, method, node.getAttribute('class')];
if (addClass) {
parts.push(addClass);
}
if (removeClass) {
parts.push(removeClass);
}
return parts.join(' ');
},
containsCachedAnimationWithoutDuration: function(key) {
var entry = cache[key];
// nothing cached, so go ahead and animate
// otherwise it should be a valid animation
return (entry && !entry.isValid) || false;
},
flush: function() {
cache = Object.create(null);
},
count: function(key) {
var entry = cache[key];
return entry ? entry.total : 0;
},
get: function(key) {
var entry = cache[key];
return entry && entry.value;
},
put: function(key, value, isValid) {
if (!cache[key]) {
cache[key] = { total: 1, value: value, isValid: isValid };
} else {
cache[key].total++;
cache[key].value = value;
}
}
};
}];
};
/* exported $$AnimationProvider */
var $$AnimationProvider = ['$animateProvider', /** @this */ function($animateProvider) {
var NG_ANIMATE_REF_ATTR = 'ng-animate-ref';
var drivers = this.drivers = [];
var RUNNER_STORAGE_KEY = '$$animationRunner';
var PREPARE_CLASSES_KEY = '$$animatePrepareClasses';
function setRunner(element, runner) {
element.data(RUNNER_STORAGE_KEY, runner);
}
function removeRunner(element) {
element.removeData(RUNNER_STORAGE_KEY);
}
function getRunner(element) {
return element.data(RUNNER_STORAGE_KEY);
}
this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$Map', '$$rAFScheduler', '$$animateCache',
function($$jqLite, $rootScope, $injector, $$AnimateRunner, $$Map, $$rAFScheduler, $$animateCache) {
var animationQueue = [];
var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
function sortAnimations(animations) {
var tree = { children: [] };
var i, lookup = new $$Map();
// this is done first beforehand so that the map
// is filled with a list of the elements that will be animated
for (i = 0; i < animations.length; i++) {
var animation = animations[i];
lookup.set(animation.domNode, animations[i] = {
domNode: animation.domNode,
element: animation.element,
fn: animation.fn,
children: []
});
}
for (i = 0; i < animations.length; i++) {
processNode(animations[i]);
}
return flatten(tree);
function processNode(entry) {
if (entry.processed) return entry;
entry.processed = true;
var elementNode = entry.domNode;
var parentNode = elementNode.parentNode;
lookup.set(elementNode, entry);
var parentEntry;
while (parentNode) {
parentEntry = lookup.get(parentNode);
if (parentEntry) {
if (!parentEntry.processed) {
parentEntry = processNode(parentEntry);
}
break;
}
parentNode = parentNode.parentNode;
}
(parentEntry || tree).children.push(entry);
return entry;
}
function flatten(tree) {
var result = [];
var queue = [];
var i;
for (i = 0; i < tree.children.length; i++) {
queue.push(tree.children[i]);
}
var remainingLevelEntries = queue.length;
var nextLevelEntries = 0;
var row = [];
for (i = 0; i < queue.length; i++) {
var entry = queue[i];
if (remainingLevelEntries <= 0) {
remainingLevelEntries = nextLevelEntries;
nextLevelEntries = 0;
result.push(row);
row = [];
}
row.push(entry);
entry.children.forEach(function(childEntry) {
nextLevelEntries++;
queue.push(childEntry);
});
remainingLevelEntries--;
}
if (row.length) {
result.push(row);
}
return result;
}
}
// TODO(matsko): document the signature in a better way
return function(element, event, options) {
options = prepareAnimationOptions(options);
var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
// there is no animation at the current moment, however
// these runner methods will get later updated with the
// methods leading into the driver's end/cancel methods
// for now they just stop the animation from starting
var runner = new $$AnimateRunner({
end: function() { close(); },
cancel: function() { close(true); }
});
if (!drivers.length) {
close();
return runner;
}
var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass));
var tempClasses = options.tempClasses;
if (tempClasses) {
classes += ' ' + tempClasses;
options.tempClasses = null;
}
if (isStructural) {
element.data(PREPARE_CLASSES_KEY, 'ng-' + event + PREPARE_CLASS_SUFFIX);
}
setRunner(element, runner);
animationQueue.push({
// this data is used by the postDigest code and passed into
// the driver step function
element: element,
classes: classes,
event: event,
structural: isStructural,
options: options,
beforeStart: beforeStart,
close: close
});
element.on('$destroy', handleDestroyedElement);
// we only want there to be one function called within the post digest
// block. This way we can group animations for all the animations that
// were apart of the same postDigest flush call.
if (animationQueue.length > 1) return runner;
$rootScope.$$postDigest(function() {
var animations = [];
forEach(animationQueue, function(entry) {
// the element was destroyed early on which removed the runner
// form its storage. This means we can't animate this element
// at all and it already has been closed due to destruction.
if (getRunner(entry.element)) {
animations.push(entry);
} else {
entry.close();
}
});
// now any future animations will be in another postDigest
animationQueue.length = 0;
var groupedAnimations = groupAnimations(animations);
var toBeSortedAnimations = [];
forEach(groupedAnimations, function(animationEntry) {
var element = animationEntry.from ? animationEntry.from.element : animationEntry.element;
var extraClasses = options.addClass;
extraClasses = (extraClasses ? (extraClasses + ' ') : '') + NG_ANIMATE_CLASSNAME;
var cacheKey = $$animateCache.cacheKey(element[0], animationEntry.event, extraClasses, options.removeClass);
toBeSortedAnimations.push({
element: element,
domNode: getDomNode(element),
fn: function triggerAnimationStart() {
var startAnimationFn, closeFn = animationEntry.close;
// in the event that we've cached the animation status for this element
// and it's in fact an invalid animation (something that has duration = 0)
// then we should skip all the heavy work from here on
if ($$animateCache.containsCachedAnimationWithoutDuration(cacheKey)) {
closeFn();
return;
}
// it's important that we apply the `ng-animate` CSS class and the
// temporary classes before we do any driver invoking since these
// CSS classes may be required for proper CSS detection.
animationEntry.beforeStart();
// in the event that the element was removed before the digest runs or
// during the RAF sequencing then we should not trigger the animation.
var targetElement = animationEntry.anchors
? (animationEntry.from.element || animationEntry.to.element)
: animationEntry.element;
if (getRunner(targetElement)) {
var operation = invokeFirstDriver(animationEntry);
if (operation) {
startAnimationFn = operation.start;
}
}
if (!startAnimationFn) {
closeFn();
} else {
var animationRunner = startAnimationFn();
animationRunner.done(function(status) {
closeFn(!status);
});
updateAnimationRunners(animationEntry, animationRunner);
}
}
});
});
// we need to sort each of the animations in order of parent to child
// relationships. This ensures that the child classes are applied at the
// right time.
var finalAnimations = sortAnimations(toBeSortedAnimations);
for (var i = 0; i < finalAnimations.length; i++) {
var innerArray = finalAnimations[i];
for (var j = 0; j < innerArray.length; j++) {
var entry = innerArray[j];
var element = entry.element;
// the RAFScheduler code only uses functions
finalAnimations[i][j] = entry.fn;
// the first row of elements shouldn't have a prepare-class added to them
// since the elements are at the top of the animation hierarchy and they
// will be applied without a RAF having to pass...
if (i === 0) {
element.removeData(PREPARE_CLASSES_KEY);
continue;
}
var prepareClassName = element.data(PREPARE_CLASSES_KEY);
if (prepareClassName) {
$$jqLite.addClass(element, prepareClassName);
}
}
}
$$rAFScheduler(finalAnimations);
});
return runner;
// TODO(matsko): change to reference nodes
function getAnchorNodes(node) {
var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']';
var items = node.hasAttribute(NG_ANIMATE_REF_ATTR)
? [node]
: node.querySelectorAll(SELECTOR);
var anchors = [];
forEach(items, function(node) {
var attr = node.getAttribute(NG_ANIMATE_REF_ATTR);
if (attr && attr.length) {
anchors.push(node);
}
});
return anchors;
}
function groupAnimations(animations) {
var preparedAnimations = [];
var refLookup = {};
forEach(animations, function(animation, index) {
var element = animation.element;
var node = getDomNode(element);
var event = animation.event;
var enterOrMove = ['enter', 'move'].indexOf(event) >= 0;
var anchorNodes = animation.structural ? getAnchorNodes(node) : [];
if (anchorNodes.length) {
var direction = enterOrMove ? 'to' : 'from';
forEach(anchorNodes, function(anchor) {
var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR);
refLookup[key] = refLookup[key] || {};
refLookup[key][direction] = {
animationID: index,
element: jqLite(anchor)
};
});
} else {
preparedAnimations.push(animation);
}
});
var usedIndicesLookup = {};
var anchorGroups = {};
forEach(refLookup, function(operations, key) {
var from = operations.from;
var to = operations.to;
if (!from || !to) {
// only one of these is set therefore we can't have an
// anchor animation since all three pieces are required
var index = from ? from.animationID : to.animationID;
var indexKey = index.toString();
if (!usedIndicesLookup[indexKey]) {
usedIndicesLookup[indexKey] = true;
preparedAnimations.push(animations[index]);
}
return;
}
var fromAnimation = animations[from.animationID];
var toAnimation = animations[to.animationID];
var lookupKey = from.animationID.toString();
if (!anchorGroups[lookupKey]) {
var group = anchorGroups[lookupKey] = {
structural: true,
beforeStart: function() {
fromAnimation.beforeStart();
toAnimation.beforeStart();
},
close: function() {
fromAnimation.close();
toAnimation.close();
},
classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes),
from: fromAnimation,
to: toAnimation,
anchors: [] // TODO(matsko): change to reference nodes
};
// the anchor animations require that the from and to elements both have at least
// one shared CSS class which effectively marries the two elements together to use
// the same animation driver and to properly sequence the anchor animation.
if (group.classes.length) {
preparedAnimations.push(group);
} else {
preparedAnimations.push(fromAnimation);
preparedAnimations.push(toAnimation);
}
}
anchorGroups[lookupKey].anchors.push({
'out': from.element, 'in': to.element
});
});
return preparedAnimations;
}
function cssClassesIntersection(a,b) {
a = a.split(' ');
b = b.split(' ');
var matches = [];
for (var i = 0; i < a.length; i++) {
var aa = a[i];
if (aa.substring(0,3) === 'ng-') continue;
for (var j = 0; j < b.length; j++) {
if (aa === b[j]) {
matches.push(aa);
break;
}
}
}
return matches.join(' ');
}
function invokeFirstDriver(animationDetails) {
// we loop in reverse order since the more general drivers (like CSS and JS)
// may attempt more elements, but custom drivers are more particular
for (var i = drivers.length - 1; i >= 0; i--) {
var driverName = drivers[i];
var factory = $injector.get(driverName);
var driver = factory(animationDetails);
if (driver) {
return driver;
}
}
}
function beforeStart() {
tempClasses = (tempClasses ? (tempClasses + ' ') : '') + NG_ANIMATE_CLASSNAME;
$$jqLite.addClass(element, tempClasses);
var prepareClassName = element.data(PREPARE_CLASSES_KEY);
if (prepareClassName) {
$$jqLite.removeClass(element, prepareClassName);
prepareClassName = null;
}
}
function updateAnimationRunners(animation, newRunner) {
if (animation.from && animation.to) {
update(animation.from.element);
update(animation.to.element);
} else {
update(animation.element);
}
function update(element) {
var runner = getRunner(element);
if (runner) runner.setHost(newRunner);
}
}
function handleDestroyedElement() {
var runner = getRunner(element);
if (runner && (event !== 'leave' || !options.$$domOperationFired)) {
runner.end();
}
}
function close(rejected) {
element.off('$destroy', handleDestroyedElement);
removeRunner(element);
applyAnimationClasses(element, options);
applyAnimationStyles(element, options);
options.domOperation();
if (tempClasses) {
$$jqLite.removeClass(element, tempClasses);
}
runner.complete(!rejected);
}
};
}];
}];
/**
* @ngdoc directive
* @name ngAnimateSwap
* @restrict A
* @scope
*
* @description
*
* ngAnimateSwap is a animation-oriented directive that allows for the container to
* be removed and entered in whenever the associated expression changes. A
* common usecase for this directive is a rotating banner or slider component which
* contains one image being present at a time. When the active image changes
* then the old image will perform a `leave` animation and the new element
* will be inserted via an `enter` animation.
*
* @animations
* | Animation | Occurs |
* |----------------------------------|--------------------------------------|
* | {@link ng.$animate#enter enter} | when the new element is inserted to the DOM |
* | {@link ng.$animate#leave leave} | when the old element is removed from the DOM |
*
* @example
* <example name="ngAnimateSwap-directive" module="ngAnimateSwapExample"
* deps="angular-animate.js"
* animations="true" fixBase="true">
* <file name="index.html">
* <div class="container" ng-controller="AppCtrl">
* <div ng-animate-swap="number" class="cell swap-animation" ng-class="colorClass(number)">
* {{ number }}
* </div>
* </div>
* </file>
* <file name="script.js">
* angular.module('ngAnimateSwapExample', ['ngAnimate'])
* .controller('AppCtrl', ['$scope', '$interval', function($scope, $interval) {
* $scope.number = 0;
* $interval(function() {
* $scope.number++;
* }, 1000);
*
* var colors = ['red','blue','green','yellow','orange'];
* $scope.colorClass = function(number) {
* return colors[number % colors.length];
* };
* }]);
* </file>
* <file name="animations.css">
* .container {
* height:250px;
* width:250px;
* position:relative;
* overflow:hidden;
* border:2px solid black;
* }
* .container .cell {
* font-size:150px;
* text-align:center;
* line-height:250px;
* position:absolute;
* top:0;
* left:0;
* right:0;
* border-bottom:2px solid black;
* }
* .swap-animation.ng-enter, .swap-animation.ng-leave {
* transition:0.5s linear all;
* }
* .swap-animation.ng-enter {
* top:-250px;
* }
* .swap-animation.ng-enter-active {
* top:0px;
* }
* .swap-animation.ng-leave {
* top:0px;
* }
* .swap-animation.ng-leave-active {
* top:250px;
* }
* .red { background:red; }
* .green { background:green; }
* .blue { background:blue; }
* .yellow { background:yellow; }
* .orange { background:orange; }
* </file>
* </example>
*/
var ngAnimateSwapDirective = ['$animate', function($animate) {
return {
restrict: 'A',
transclude: 'element',
terminal: true,
priority: 550, // We use 550 here to ensure that the directive is caught before others,
// but after `ngIf` (at priority 600).
link: function(scope, $element, attrs, ctrl, $transclude) {
var previousElement, previousScope;
scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) {
if (previousElement) {
$animate.leave(previousElement);
}
if (previousScope) {
previousScope.$destroy();
previousScope = null;
}
if (value || value === 0) {
$transclude(function(clone, childScope) {
previousElement = clone;
previousScope = childScope;
$animate.enter(clone, null, $element);
});
}
});
}
};
}];
/**
* @ngdoc module
* @name ngAnimate
* @description
*
* The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via
* callback hooks. Animations are not enabled by default, however, by including `ngAnimate` the animation hooks are enabled for an AngularJS app.
*
* ## Usage
* 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
* using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For
* both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within
* the HTML element that the animation will be triggered on.
*
* ## Directive Support
* The following directives are "animation aware":
*
* | Directive | Supported Animations |
* |-------------------------------------------------------------------------------|---------------------------------------------------------------------------|
* | {@link ng.directive:form#animations form / ngForm} | add and remove ({@link ng.directive:form#css-classes various classes}) |
* | {@link ngAnimate.directive:ngAnimateSwap#animations ngAnimateSwap} | enter and leave |
* | {@link ng.directive:ngClass#animations ngClass / {{class&#125;&#8203;&#125;} | add and remove |
* | {@link ng.directive:ngClassEven#animations ngClassEven} | add and remove |
* | {@link ng.directive:ngClassOdd#animations ngClassOdd} | add and remove |
* | {@link ng.directive:ngHide#animations ngHide} | add and remove (the `ng-hide` class) |
* | {@link ng.directive:ngIf#animations ngIf} | enter and leave |
* | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave |
* | {@link module:ngMessages#animations ngMessage / ngMessageExp} | enter and leave |
* | {@link module:ngMessages#animations ngMessages} | add and remove (the `ng-active`/`ng-inactive` classes) |
* | {@link ng.directive:ngModel#animations ngModel} | add and remove ({@link ng.directive:ngModel#css-classes various classes}) |
* | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave, and move |
* | {@link ng.directive:ngShow#animations ngShow} | add and remove (the `ng-hide` class) |
* | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave |
* | {@link ngRoute.directive:ngView#animations ngView} | enter and leave |
*
* (More information can be found by visiting the documentation associated with each directive.)
*
* For a full breakdown of the steps involved during each animation event, refer to the
* {@link ng.$animate `$animate` API docs}.
*
* ## CSS-based Animations
*
* 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
* and CSS code we can create an animation that will be picked up by AngularJS when an underlying directive performs an operation.
*
* The example below shows how an `enter` animation can be made possible on an element using `ng-if`:
*
* ```html
* <div ng-if="bool" class="fade">
* Fade me in out
* </div>
* <button ng-click="bool=true">Fade In!</button>
* <button ng-click="bool=false">Fade Out!</button>
* ```
*
* Notice the CSS class **fade**? We can now create the CSS transition code that references this class:
*
* ```css
* /&#42; The starting CSS styles for the enter animation &#42;/
* .fade.ng-enter {
* transition:0.5s linear all;
* opacity:0;
* }
*
* /&#42; The finishing CSS styles for the enter animation &#42;/
* .fade.ng-enter.ng-enter-active {
* opacity:1;
* }
* ```
*
* 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
* 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
* code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards.
*
* 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:
*
* ```css
* /&#42; now the element will fade out before it is removed from the DOM &#42;/
* .fade.ng-leave {
* transition:0.5s linear all;
* opacity:1;
* }
* .fade.ng-leave.ng-leave-active {
* opacity:0;
* }
* ```
*
* We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class:
*
* ```css
* /&#42; there is no need to define anything inside of the destination
* CSS class since the keyframe will take charge of the animation &#42;/
* .fade.ng-leave {
* animation: my_fade_animation 0.5s linear;
* -webkit-animation: my_fade_animation 0.5s linear;
* }
*
* @keyframes my_fade_animation {
* from { opacity:1; }
* to { opacity:0; }
* }
*
* @-webkit-keyframes my_fade_animation {
* from { opacity:1; }
* to { opacity:0; }
* }
* ```
*
* Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element.
*
* ### CSS Class-based Animations
*
* Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different
* naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added
* and removed.
*
* For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class:
*
* ```html
* <div ng-show="bool" class="fade">
* Show and hide me
* </div>
* <button ng-click="bool=!bool">Toggle</button>
*
* <style>
* .fade.ng-hide {
* transition:0.5s linear all;
* opacity:0;
* }
* </style>
* ```
*
* 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
* ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest.
*
* 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
* with CSS styles.
*
* ```html
* <div ng-class="{on:onOff}" class="highlight">
* Highlight this box
* </div>
* <button ng-click="onOff=!onOff">Toggle</button>
*
* <style>
* .highlight {
* transition:0.5s linear all;
* }
* .highlight.on-add {
* background:white;
* }
* .highlight.on {
* background:yellow;
* }
* .highlight.on-remove {
* background:black;
* }
* </style>
* ```
*
* We can also make use of CSS keyframes by placing them within the CSS classes.
*
*
* ### CSS Staggering Animations
* A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a
* curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be
* performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for
* the animation. The style property expected within the stagger class can either be a **transition-delay** or an
* **animation-delay** property (or both if your animation contains both transitions and keyframe animations).
*
* ```css
* .my-animation.ng-enter {
* /&#42; standard transition code &#42;/
* transition: 1s linear all;
* opacity:0;
* }
* .my-animation.ng-enter-stagger {
* /&#42; this will have a 100ms delay between each successive leave animation &#42;/
* transition-delay: 0.1s;
*
* /&#42; As of 1.4.4, this must always be set: it signals ngAnimate
* to not accidentally inherit a delay property from another CSS class &#42;/
* transition-duration: 0s;
*
* /&#42; if you are using animations instead of transitions you should configure as follows:
* animation-delay: 0.1s;
* animation-duration: 0s; &#42;/
* }
* .my-animation.ng-enter.ng-enter-active {
* /&#42; standard transition styles &#42;/
* opacity:1;
* }
* ```
*
* Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations
* on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this
* are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation
* will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired.
*
* The following code will issue the **ng-leave-stagger** event on the element provided:
*
* ```js
* var kids = parent.children();
*
* $animate.leave(kids[0]); //stagger index=0
* $animate.leave(kids[1]); //stagger index=1
* $animate.leave(kids[2]); //stagger index=2
* $animate.leave(kids[3]); //stagger index=3
* $animate.leave(kids[4]); //stagger index=4
*
* window.requestAnimationFrame(function() {
* //stagger has reset itself
* $animate.leave(kids[5]); //stagger index=0
* $animate.leave(kids[6]); //stagger index=1
*
* $scope.$digest();
* });
* ```
*
* Stagger animations are currently only supported within CSS-defined animations.
*
* ### The `ng-animate` CSS class
*
* When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation.
* This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations).
*
* Therefore, animations can be applied to an element using this temporary class directly via CSS.
*
* ```css
* .zipper.ng-animate {
* transition:0.5s linear all;
* }
* .zipper.ng-enter {
* opacity:0;
* }
* .zipper.ng-enter.ng-enter-active {
* opacity:1;
* }
* .zipper.ng-leave {
* opacity:1;
* }
* .zipper.ng-leave.ng-leave-active {
* opacity:0;
* }
* ```
*
* (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove
* the CSS class once an animation has completed.)
*
*
* ### The `ng-[event]-prepare` class
*
* This is a special class that can be used to prevent unwanted flickering / flash of content before
* the actual animation starts. The class is added as soon as an animation is initialized, but removed
* before the actual animation starts (after waiting for a $digest).
* It is also only added for *structural* animations (`enter`, `move`, and `leave`).
*
* In practice, flickering can appear when nesting elements with structural animations such as `ngIf`
* into elements that have class-based animations such as `ngClass`.
*
* ```html
* <div ng-class="{red: myProp}">
* <div ng-class="{blue: myProp}">
* <div class="message" ng-if="myProp"></div>
* </div>
* </div>
* ```
*
* It is possible that during the `enter` animation, the `.message` div will be briefly visible before it starts animating.
* In that case, you can add styles to the CSS that make sure the element stays hidden before the animation starts:
*
* ```css
* .message.ng-enter-prepare {
* opacity: 0;
* }
* ```
*
* ### Animating between value changes
*
* Sometimes you need to animate between different expression states, whose values
* don't necessary need to be known or referenced in CSS styles.
* Unless possible with another {@link ngAnimate#directive-support "animation aware" directive},
* that specific use case can always be covered with {@link ngAnimate.directive:ngAnimateSwap} as
* can be seen in {@link ngAnimate.directive:ngAnimateSwap#examples this example}.
*
* Note that {@link ngAnimate.directive:ngAnimateSwap} is a *structural directive*, which means it
* creates a new instance of the element (including any other/child directives it may have) and
* links it to a new scope every time *swap* happens. In some cases this might not be desirable
* (e.g. for performance reasons, or when you wish to retain internal state on the original
* element instance).
*
* ## JavaScript-based Animations
*
* ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared
* 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
* `module.animation()` module function we can register the animation.
*
* Let's see an example of a enter/leave animation using `ngRepeat`:
*
* ```html
* <div ng-repeat="item in items" class="slide">
* {{ item }}
* </div>
* ```
*
* 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`:
*
* ```js
* myModule.animation('.slide', [function() {
* return {
* // make note that other events (like addClass/removeClass)
* // have different function input parameters
* enter: function(element, doneFn) {
* jQuery(element).fadeIn(1000, doneFn);
*
* // remember to call doneFn so that AngularJS
* // knows that the animation has concluded
* },
*
* move: function(element, doneFn) {
* jQuery(element).fadeIn(1000, doneFn);
* },
*
* leave: function(element, doneFn) {
* jQuery(element).fadeOut(1000, doneFn);
* }
* }
* }]);
* ```
*
* The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as
* greensock.js and velocity.js.
*
* If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define
* our animations inside of the same registered animation, however, the function input arguments are a bit different:
*
* ```html
* <div ng-class="color" class="colorful">
* this box is moody
* </div>
* <button ng-click="color='red'">Change to red</button>
* <button ng-click="color='blue'">Change to blue</button>
* <button ng-click="color='green'">Change to green</button>
* ```
*
* ```js
* myModule.animation('.colorful', [function() {
* return {
* addClass: function(element, className, doneFn) {
* // do some cool animation and call the doneFn
* },
* removeClass: function(element, className, doneFn) {
* // do some cool animation and call the doneFn
* },
* setClass: function(element, addedClass, removedClass, doneFn) {
* // do some cool animation and call the doneFn
* }
* }
* }]);
* ```
*
* ## CSS + JS Animations Together
*
* AngularJS 1.4 and higher has taken steps to make the amalgamation of CSS and JS animations more flexible. However, unlike earlier versions of AngularJS,
* 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
* charge of the animation**:
*
* ```html
* <div ng-if="bool" class="slide">
* Slide in and out
* </div>
* ```
*
* ```js
* myModule.animation('.slide', [function() {
* return {
* enter: function(element, doneFn) {
* jQuery(element).slideIn(1000, doneFn);
* }
* }
* }]);
* ```
*
* ```css
* .slide.ng-enter {
* transition:0.5s linear all;
* transform:translateY(-100px);
* }
* .slide.ng-enter.ng-enter-active {
* transform:translateY(0);
* }
* ```
*
* 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
* lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from
* our own JS-based animation code:
*
* ```js
* myModule.animation('.slide', ['$animateCss', function($animateCss) {
* return {
* enter: function(element) {
* // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`.
* return $animateCss(element, {
* event: 'enter',
* structural: true
* });
* }
* }
* }]);
* ```
*
* 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.
*
* 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
* 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
* data into `$animateCss` directly:
*
* ```js
* myModule.animation('.slide', ['$animateCss', function($animateCss) {
* return {
* enter: function(element) {
* return $animateCss(element, {
* event: 'enter',
* structural: true,
* addClass: 'maroon-setting',
* from: { height:0 },
* to: { height: 200 }
* });
* }
* }
* }]);
* ```
*
* Now we can fill in the rest via our transition CSS code:
*
* ```css
* /&#42; the transition tells ngAnimate to make the animation happen &#42;/
* .slide.ng-enter { transition:0.5s linear all; }
*
* /&#42; this extra CSS class will be absorbed into the transition
* since the $animateCss code is adding the class &#42;/
* .maroon-setting { background:red; }
* ```
*
* 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.
*
* To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}.
*
* ## Animation Anchoring (via `ng-animate-ref`)
*
* ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between
* structural areas of an application (like views) by pairing up elements using an attribute
* called `ng-animate-ref`.
*
* Let's say for example we have two views that are managed by `ng-view` and we want to show
* that there is a relationship between two components situated in within these views. By using the
* `ng-animate-ref` attribute we can identify that the two components are paired together and we
* can then attach an animation, which is triggered when the view changes.
*
* Say for example we have the following template code:
*
* ```html
* <!-- index.html -->
* <div ng-view class="view-animation">
* </div>
*
* <!-- home.html -->
* <a href="#/banner-page">
* <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
* </a>
*
* <!-- banner-page.html -->
* <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
* ```
*
* Now, when the view changes (once the link is clicked), ngAnimate will examine the
* HTML contents to see if there is a match reference between any components in the view
* that is leaving and the view that is entering. It will scan both the view which is being
* removed (leave) and inserted (enter) to see if there are any paired DOM elements that
* contain a matching ref value.
*
* The two images match since they share the same ref value. ngAnimate will now create a
* transport element (which is a clone of the first image element) and it will then attempt
* to animate to the position of the second image element in the next view. For the animation to
* work a special CSS class called `ng-anchor` will be added to the transported element.
*
* We can now attach a transition onto the `.banner.ng-anchor` CSS class and then
* ngAnimate will handle the entire transition for us as well as the addition and removal of
* any changes of CSS classes between the elements:
*
* ```css
* .banner.ng-anchor {
* /&#42; this animation will last for 1 second since there are
* two phases to the animation (an `in` and an `out` phase) &#42;/
* transition:0.5s linear all;
* }
* ```
*
* We also **must** include animations for the views that are being entered and removed
* (otherwise anchoring wouldn't be possible since the new view would be inserted right away).
*
* ```css
* .view-animation.ng-enter, .view-animation.ng-leave {
* transition:0.5s linear all;
* position:fixed;
* left:0;
* top:0;
* width:100%;
* }
* .view-animation.ng-enter {
* transform:translateX(100%);
* }
* .view-animation.ng-leave,
* .view-animation.ng-enter.ng-enter-active {
* transform:translateX(0%);
* }
* .view-animation.ng-leave.ng-leave-active {
* transform:translateX(-100%);
* }
* ```
*
* Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur:
* an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away
* from its origin. Once that animation is over then the `in` stage occurs which animates the
* element to its destination. The reason why there are two animations is to give enough time
* for the enter animation on the new element to be ready.
*
* The example above sets up a transition for both the in and out phases, but we can also target the out or
* in phases directly via `ng-anchor-out` and `ng-anchor-in`.
*
* ```css
* .banner.ng-anchor-out {
* transition: 0.5s linear all;
*
* /&#42; the scale will be applied during the out animation,
* but will be animated away when the in animation runs &#42;/
* transform: scale(1.2);
* }
*
* .banner.ng-anchor-in {
* transition: 1s linear all;
* }
* ```
*
*
*
*
* ### Anchoring Demo
*
<example module="anchoringExample"
name="anchoringExample"
id="anchoringExample"
deps="angular-animate.js;angular-route.js"
animations="true">
<file name="index.html">
<a href="#!/">Home</a>
<hr />
<div class="view-container">
<div ng-view class="view"></div>
</div>
</file>
<file name="script.js">
angular.module('anchoringExample', ['ngAnimate', 'ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'home.html',
controller: 'HomeController as home'
});
$routeProvider.when('/profile/:id', {
templateUrl: 'profile.html',
controller: 'ProfileController as profile'
});
}])
.run(['$rootScope', function($rootScope) {
$rootScope.records = [
{ id: 1, title: 'Miss Beulah Roob' },
{ id: 2, title: 'Trent Morissette' },
{ id: 3, title: 'Miss Ava Pouros' },
{ id: 4, title: 'Rod Pouros' },
{ id: 5, title: 'Abdul Rice' },
{ id: 6, title: 'Laurie Rutherford Sr.' },
{ id: 7, title: 'Nakia McLaughlin' },
{ id: 8, title: 'Jordon Blanda DVM' },
{ id: 9, title: 'Rhoda Hand' },
{ id: 10, title: 'Alexandrea Sauer' }
];
}])
.controller('HomeController', [function() {
//empty
}])
.controller('ProfileController', ['$rootScope', '$routeParams',
function ProfileController($rootScope, $routeParams) {
var index = parseInt($routeParams.id, 10);
var record = $rootScope.records[index - 1];
this.title = record.title;
this.id = record.id;
}]);
</file>
<file name="home.html">
<h2>Welcome to the home page</h1>
<p>Please click on an element</p>
<a class="record"
ng-href="#!/profile/{{ record.id }}"
ng-animate-ref="{{ record.id }}"
ng-repeat="record in records">
{{ record.title }}
</a>
</file>
<file name="profile.html">
<div class="profile record" ng-animate-ref="{{ profile.id }}">
{{ profile.title }}
</div>
</file>
<file name="animations.css">
.record {
display:block;
font-size:20px;
}
.profile {
background:black;
color:white;
font-size:100px;
}
.view-container {
position:relative;
}
.view-container > .view.ng-animate {
position:absolute;
top:0;
left:0;
width:100%;
min-height:500px;
}
.view.ng-enter, .view.ng-leave,
.record.ng-anchor {
transition:0.5s linear all;
}
.view.ng-enter {
transform:translateX(100%);
}
.view.ng-enter.ng-enter-active, .view.ng-leave {
transform:translateX(0%);
}
.view.ng-leave.ng-leave-active {
transform:translateX(-100%);
}
.record.ng-anchor-out {
background:red;
}
</file>
</example>
*
* ### How is the element transported?
*
* When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting
* element is located on screen via absolute positioning. The cloned element will be placed inside of the root element
* of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The
* element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match
* the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied
* to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class
* is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element
* will become visible since the shim class will be removed.
*
* ### How is the morphing handled?
*
* CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out
* what CSS classes differ between the starting element and the destination element. These different CSS classes
* will be added/removed on the anchor element and a transition will be applied (the transition that is provided
* in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will
* make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that
* do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since
* the cloned element is placed inside of root element which is likely close to the body element).
*
* Note that if the root element is on the `<html>` element then the cloned node will be placed inside of body.
*
*
* ## Using $animate in your directive code
*
* So far we've explored how to feed in animations into an AngularJS application, but how do we trigger animations within our own directives in our application?
* 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
* imagine we have a greeting box that shows and hides itself when the data changes
*
* ```html
* <greeting-box active="onOrOff">Hi there</greeting-box>
* ```
*
* ```js
* ngModule.directive('greetingBox', ['$animate', function($animate) {
* return function(scope, element, attrs) {
* attrs.$observe('active', function(value) {
* value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on');
* });
* });
* }]);
* ```
*
* 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
* in our HTML code then we can trigger a CSS or JS animation to happen.
*
* ```css
* /&#42; normally we would create a CSS class to reference on the element &#42;/
* greeting-box.on { transition:0.5s linear all; background:green; color:white; }
* ```
*
* The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's
* possible be sure to visit the {@link ng.$animate $animate service API page}.
*
*
* ## Callbacks and Promises
*
* 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
* an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has
* ended by chaining onto the returned promise that animation method returns.
*
* ```js
* // somewhere within the depths of the directive
* $animate.enter(element, parent).then(function() {
* //the animation has completed
* });
* ```
*
* (Note that earlier versions of AngularJS prior to v1.4 required the promise code to be wrapped using `$scope.$apply(...)`. This is not the case
* anymore.)
*
* In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering
* an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view
* routing controller to hook into that:
*
* ```js
* ngModule.controller('HomePageController', ['$animate', function($animate) {
* $animate.on('enter', ngViewElement, function(element) {
* // the animation for this route has completed
* }]);
* }])
* ```
*
* (Note that you will need to trigger a digest within the callback to get AngularJS to notice any scope-related changes.)
*/
var copy;
var extend;
var forEach;
var isArray;
var isDefined;
var isElement;
var isFunction;
var isObject;
var isString;
var isUndefined;
var jqLite;
var noop;
/**
* @ngdoc service
* @name $animate
* @kind object
*
* @description
* The ngAnimate `$animate` service documentation is the same for the core `$animate` service.
*
* Click here {@link ng.$animate to learn more about animations with `$animate`}.
*/
angular.module('ngAnimate', [], function initAngularHelpers() {
// Access helpers from AngularJS core.
// Do it inside a `config` block to ensure `window.angular` is available.
noop = angular.noop;
copy = angular.copy;
extend = angular.extend;
jqLite = angular.element;
forEach = angular.forEach;
isArray = angular.isArray;
isString = angular.isString;
isObject = angular.isObject;
isUndefined = angular.isUndefined;
isDefined = angular.isDefined;
isFunction = angular.isFunction;
isElement = angular.isElement;
})
.info({ angularVersion: '1.7.8' })
.directive('ngAnimateSwap', ngAnimateSwapDirective)
.directive('ngAnimateChildren', $$AnimateChildrenDirective)
.factory('$$rAFScheduler', $$rAFSchedulerFactory)
.provider('$$animateQueue', $$AnimateQueueProvider)
.provider('$$animateCache', $$AnimateCacheProvider)
.provider('$$animation', $$AnimationProvider)
.provider('$animateCss', $AnimateCssProvider)
.provider('$$animateCssDriver', $$AnimateCssDriverProvider)
.provider('$$animateJs', $$AnimateJsProvider)
.provider('$$animateJsDriver', $$AnimateJsDriverProvider);
})(window, window.angular);
/* global shallowCopy: true */
/**
* Creates a shallow copy of an object, an array or a primitive.
*
* Assumes that there are no proto properties for objects.
*/
function shallowCopy(src, dst) {
if (isArray(src)) {
dst = dst || [];
for (var i = 0, ii = src.length; i < ii; i++) {
dst[i] = src[i];
}
} else if (isObject(src)) {
dst = dst || {};
for (var key in src) {
if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
dst[key] = src[key];
}
}
}
return dst || src;
}
/* global routeToRegExp: true */
/**
* @param {string} path - The path to parse. (It is assumed to have query and hash stripped off.)
* @param {Object} opts - Options.
* @return {Object} - An object containing an array of path parameter names (`keys`) and a regular
* expression (`regexp`) that can be used to identify a matching URL and extract the path
* parameter values.
*
* @description
* Parses the given path, extracting path parameter names and a regular expression to match URLs.
*
* Originally inspired by `pathRexp` in `visionmedia/express/lib/utils.js`.
*/
function routeToRegExp(path, opts) {
var keys = [];
var pattern = path
.replace(/([().])/g, '\\$1')
.replace(/(\/)?:(\w+)(\*\?|[?*])?/g, function(_, slash, key, option) {
var optional = option === '?' || option === '*?';
var star = option === '*' || option === '*?';
keys.push({name: key, optional: optional});
slash = slash || '';
return (
(optional ? '(?:' + slash : slash + '(?:') +
(star ? '(.+?)' : '([^/]+)') +
(optional ? '?)?' : ')')
);
})
.replace(/([/$*])/g, '\\$1');
if (opts.ignoreTrailingSlashes) {
pattern = pattern.replace(/\/+$/, '') + '/*';
}
return {
keys: keys,
regexp: new RegExp(
'^' + pattern + '(?:[?#]|$)',
opts.caseInsensitiveMatch ? 'i' : ''
)
};
}
/* global routeToRegExp: false */
/* global shallowCopy: false */
// `isArray` and `isObject` are necessary for `shallowCopy()` (included via `src/shallowCopy.js`).
// They are initialized inside the `$RouteProvider`, to ensure `window.angular` is available.
var isArray;
var isObject;
var isDefined;
var noop;
/**
* @ngdoc module
* @name ngRoute
* @description
*
* The `ngRoute` module provides routing and deeplinking services and directives for AngularJS apps.
*
* ## Example
* See {@link ngRoute.$route#examples $route} for an example of configuring and using `ngRoute`.
*
*/
/* global -ngRouteModule */
var ngRouteModule = angular.
module('ngRoute', []).
info({ angularVersion: '1.7.8' }).
provider('$route', $RouteProvider).
// Ensure `$route` will be instantiated in time to capture the initial `$locationChangeSuccess`
// event (unless explicitly disabled). This is necessary in case `ngView` is included in an
// asynchronously loaded template.
run(instantiateRoute);
var $routeMinErr = angular.$$minErr('ngRoute');
var isEagerInstantiationEnabled;
/**
* @ngdoc provider
* @name $routeProvider
* @this
*
* @description
*
* Used for configuring routes.
*
* ## Example
* See {@link ngRoute.$route#examples $route} for an example of configuring and using `ngRoute`.
*
* ## Dependencies
* Requires the {@link ngRoute `ngRoute`} module to be installed.
*/
function $RouteProvider() {
isArray = angular.isArray;
isObject = angular.isObject;
isDefined = angular.isDefined;
noop = angular.noop;
function inherit(parent, extra) {
return angular.extend(Object.create(parent), extra);
}
var routes = {};
/**
* @ngdoc method
* @name $routeProvider#when
*
* @param {string} path Route path (matched against `$location.path`). If `$location.path`
* contains redundant trailing slash or is missing one, the route will still match and the
* `$location.path` will be updated to add or drop the trailing slash to exactly match the
* route definition.
*
* * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up
* to the next slash are matched and stored in `$routeParams` under the given `name`
* when the route matches.
* * `path` can contain named groups starting with a colon and ending with a star:
* e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name`
* when the route matches.
* * `path` can contain optional named groups with a question mark: e.g.`:name?`.
*
* For example, routes like `/color/:color/largecode/:largecode*\/edit` will match
* `/color/brown/largecode/code/with/slashes/edit` and extract:
*
* * `color: brown`
* * `largecode: code/with/slashes`.
*
*
* @param {Object} route Mapping information to be assigned to `$route.current` on route
* match.
*
* Object properties:
*
* - `controller` `{(string|Function)=}` Controller fn that should be associated with
* newly created scope or the name of a {@link angular.Module#controller registered
* controller} if passed as a string.
* - `controllerAs` `{string=}` An identifier name for a reference to the controller.
* If present, the controller will be published to scope under the `controllerAs` name.
* - `template` `{(string|Function)=}` html template as a string or a function that
* returns an html template as a string which should be used by {@link
* ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives.
* This property takes precedence over `templateUrl`.
*
* If `template` is a function, it will be called with the following parameters:
*
* - `{Array.<Object>}` - route parameters extracted from the current
* `$location.path()` by applying the current route
*
* One of `template` or `templateUrl` is required.
*
* - `templateUrl` `{(string|Function)=}` path or function that returns a path to an html
* template that should be used by {@link ngRoute.directive:ngView ngView}.
*
* If `templateUrl` is a function, it will be called with the following parameters:
*
* - `{Array.<Object>}` - route parameters extracted from the current
* `$location.path()` by applying the current route
*
* One of `templateUrl` or `template` is required.
*
* - `resolve` - `{Object.<string, Function>=}` - An optional map of dependencies which should
* be injected into the controller. If any of these dependencies are promises, the router
* will wait for them all to be resolved or one to be rejected before the controller is
* instantiated.
* If all the promises are resolved successfully, the values of the resolved promises are
* injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is
* fired. If any of the promises are rejected the
* {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired.
* For easier access to the resolved dependencies from the template, the `resolve` map will
* be available on the scope of the route, under `$resolve` (by default) or a custom name
* specified by the `resolveAs` property (see below). This can be particularly useful, when
* working with {@link angular.Module#component components} as route templates.<br />
* <div class="alert alert-warning">
* **Note:** If your scope already contains a property with this name, it will be hidden
* or overwritten. Make sure, you specify an appropriate name for this property, that
* does not collide with other properties on the scope.
* </div>
* The map object is:
*
* - `key` `{string}`: a name of a dependency to be injected into the controller.
* - `factory` - `{string|Function}`: If `string` then it is an alias for a service.
* Otherwise if function, then it is {@link auto.$injector#invoke injected}
* and the return value is treated as the dependency. If the result is a promise, it is
* resolved before its value is injected into the controller. Be aware that
* `ngRoute.$routeParams` will still refer to the previous route within these resolve
* functions. Use `$route.current.params` to access the new route parameters, instead.
*
* - `resolveAs` - `{string=}` - The name under which the `resolve` map will be available on
* the scope of the route. If omitted, defaults to `$resolve`.
*
* - `redirectTo` `{(string|Function)=}` value to update
* {@link ng.$location $location} path with and trigger route redirection.
*
* If `redirectTo` is a function, it will be called with the following parameters:
*
* - `{Object.<string>}` - route parameters extracted from the current
* `$location.path()` by applying the current route templateUrl.
* - `{string}` - current `$location.path()`
* - `{Object}` - current `$location.search()`
*
* The custom `redirectTo` function is expected to return a string which will be used
* to update `$location.url()`. If the function throws an error, no further processing will
* take place and the {@link ngRoute.$route#$routeChangeError $routeChangeError} event will
* be fired.
*
* Routes that specify `redirectTo` will not have their controllers, template functions
* or resolves called, the `$location` will be changed to the redirect url and route
* processing will stop. The exception to this is if the `redirectTo` is a function that
* returns `undefined`. In this case the route transition occurs as though there was no
* redirection.
*
* - `resolveRedirectTo` `{Function=}` a function that will (eventually) return the value
* to update {@link ng.$location $location} URL with and trigger route redirection. In
* contrast to `redirectTo`, dependencies can be injected into `resolveRedirectTo` and the
* return value can be either a string or a promise that will be resolved to a string.
*
* Similar to `redirectTo`, if the return value is `undefined` (or a promise that gets
* resolved to `undefined`), no redirection takes place and the route transition occurs as
* though there was no redirection.
*
* If the function throws an error or the returned promise gets rejected, no further
* processing will take place and the
* {@link ngRoute.$route#$routeChangeError $routeChangeError} event will be fired.
*
* `redirectTo` takes precedence over `resolveRedirectTo`, so specifying both on the same
* route definition, will cause the latter to be ignored.
*
* - `[reloadOnUrl=true]` - `{boolean=}` - reload route when any part of the URL changes
* (including the path) even if the new URL maps to the same route.
*
* If the option is set to `false` and the URL in the browser changes, but the new URL maps
* to the same route, then a `$routeUpdate` event is broadcasted on the root scope (without
* reloading the route).
*
* - `[reloadOnSearch=true]` - `{boolean=}` - reload route when only `$location.search()`
* or `$location.hash()` changes.
*
* If the option is set to `false` and the URL in the browser changes, then a `$routeUpdate`
* event is broadcasted on the root scope (without reloading the route).
*
* <div class="alert alert-warning">
* **Note:** This option has no effect if `reloadOnUrl` is set to `false`.
* </div>
*
* - `[caseInsensitiveMatch=false]` - `{boolean=}` - match routes without being case sensitive
*
* If the option is set to `true`, then the particular route can be matched without being
* case sensitive
*
* @returns {Object} self
*
* @description
* Adds a new route definition to the `$route` service.
*/
this.when = function(path, route) {
//copy original route object to preserve params inherited from proto chain
var routeCopy = shallowCopy(route);
if (angular.isUndefined(routeCopy.reloadOnUrl)) {
routeCopy.reloadOnUrl = true;
}
if (angular.isUndefined(routeCopy.reloadOnSearch)) {
routeCopy.reloadOnSearch = true;
}
if (angular.isUndefined(routeCopy.caseInsensitiveMatch)) {
routeCopy.caseInsensitiveMatch = this.caseInsensitiveMatch;
}
routes[path] = angular.extend(
routeCopy,
{originalPath: path},
path && routeToRegExp(path, routeCopy)
);
// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length - 1] === '/')
? path.substr(0, path.length - 1)
: path + '/';
routes[redirectPath] = angular.extend(
{originalPath: path, redirectTo: path},
routeToRegExp(redirectPath, routeCopy)
);
}
return this;
};
/**
* @ngdoc property
* @name $routeProvider#caseInsensitiveMatch
* @description
*
* A boolean property indicating if routes defined
* using this provider should be matched using a case insensitive
* algorithm. Defaults to `false`.
*/
this.caseInsensitiveMatch = false;
/**
* @ngdoc method
* @name $routeProvider#otherwise
*
* @description
* Sets route definition that will be used on route change when no other route definition
* is matched.
*
* @param {Object|string} params Mapping information to be assigned to `$route.current`.
* If called with a string, the value maps to `redirectTo`.
* @returns {Object} self
*/
this.otherwise = function(params) {
if (typeof params === 'string') {
params = {redirectTo: params};
}
this.when(null, params);
return this;
};
/**
* @ngdoc method
* @name $routeProvider#eagerInstantiationEnabled
* @kind function
*
* @description
* Call this method as a setter to enable/disable eager instantiation of the
* {@link ngRoute.$route $route} service upon application bootstrap. You can also call it as a
* getter (i.e. without any arguments) to get the current value of the
* `eagerInstantiationEnabled` flag.
*
* Instantiating `$route` early is necessary for capturing the initial
* {@link ng.$location#$locationChangeStart $locationChangeStart} event and navigating to the
* appropriate route. Usually, `$route` is instantiated in time by the
* {@link ngRoute.ngView ngView} directive. Yet, in cases where `ngView` is included in an
* asynchronously loaded template (e.g. in another directive's template), the directive factory
* might not be called soon enough for `$route` to be instantiated _before_ the initial
* `$locationChangeSuccess` event is fired. Eager instantiation ensures that `$route` is always
* instantiated in time, regardless of when `ngView` will be loaded.
*
* The default value is true.
*
* **Note**:<br />
* You may want to disable the default behavior when unit-testing modules that depend on
* `ngRoute`, in order to avoid an unexpected request for the default route's template.
*
* @param {boolean=} enabled - If provided, update the internal `eagerInstantiationEnabled` flag.
*
* @returns {*} The current value of the `eagerInstantiationEnabled` flag if used as a getter or
* itself (for chaining) if used as a setter.
*/
isEagerInstantiationEnabled = true;
this.eagerInstantiationEnabled = function eagerInstantiationEnabled(enabled) {
if (isDefined(enabled)) {
isEagerInstantiationEnabled = enabled;
return this;
}
return isEagerInstantiationEnabled;
};
this.$get = ['$rootScope',
'$location',
'$routeParams',
'$q',
'$injector',
'$templateRequest',
'$sce',
'$browser',
function($rootScope, $location, $routeParams, $q, $injector, $templateRequest, $sce, $browser) {
/**
* @ngdoc service
* @name $route
* @requires $location
* @requires $routeParams
*
* @property {Object} current Reference to the current route definition.
* The route definition contains:
*
* - `controller`: The controller constructor as defined in the route definition.
* - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
* controller instantiation. The `locals` contain
* the resolved values of the `resolve` map. Additionally the `locals` also contain:
*
* - `$scope` - The current route scope.
* - `$template` - The current route template HTML.
*
* The `locals` will be assigned to the route scope's `$resolve` property. You can override
* the property name, using `resolveAs` in the route definition. See
* {@link ngRoute.$routeProvider $routeProvider} for more info.
*
* @property {Object} routes Object with all route configuration Objects as its properties.
*
* @description
* `$route` is used for deep-linking URLs to controllers and views (HTML partials).
* It watches `$location.url()` and tries to map the path to an existing route definition.
*
* Requires the {@link ngRoute `ngRoute`} module to be installed.
*
* You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API.
*
* The `$route` service is typically used in conjunction with the
* {@link ngRoute.directive:ngView `ngView`} directive and the
* {@link ngRoute.$routeParams `$routeParams`} service.
*
* @example
* This example shows how changing the URL hash causes the `$route` to match a route against the
* URL, and the `ngView` pulls in the partial.
*
* <example name="$route-service" module="ngRouteExample"
* deps="angular-route.js" fixBase="true">
* <file name="index.html">
* <div ng-controller="MainController">
* Choose:
* <a href="Book/Moby">Moby</a> |
* <a href="Book/Moby/ch/1">Moby: Ch1</a> |
* <a href="Book/Gatsby">Gatsby</a> |
* <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
* <a href="Book/Scarlet">Scarlet Letter</a><br/>
*
* <div ng-view></div>
*
* <hr />
*
* <pre>$location.path() = {{$location.path()}}</pre>
* <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
* <pre>$route.current.params = {{$route.current.params}}</pre>
* <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
* <pre>$routeParams = {{$routeParams}}</pre>
* </div>
* </file>
*
* <file name="book.html">
* controller: {{name}}<br />
* Book Id: {{params.bookId}}<br />
* </file>
*
* <file name="chapter.html">
* controller: {{name}}<br />
* Book Id: {{params.bookId}}<br />
* Chapter Id: {{params.chapterId}}
* </file>
*
* <file name="script.js">
* angular.module('ngRouteExample', ['ngRoute'])
*
* .controller('MainController', function($scope, $route, $routeParams, $location) {
* $scope.$route = $route;
* $scope.$location = $location;
* $scope.$routeParams = $routeParams;
* })
*
* .controller('BookController', function($scope, $routeParams) {
* $scope.name = 'BookController';
* $scope.params = $routeParams;
* })
*
* .controller('ChapterController', function($scope, $routeParams) {
* $scope.name = 'ChapterController';
* $scope.params = $routeParams;
* })
*
* .config(function($routeProvider, $locationProvider) {
* $routeProvider
* .when('/Book/:bookId', {
* templateUrl: 'book.html',
* controller: 'BookController',
* resolve: {
* // I will cause a 1 second delay
* delay: function($q, $timeout) {
* var delay = $q.defer();
* $timeout(delay.resolve, 1000);
* return delay.promise;
* }
* }
* })
* .when('/Book/:bookId/ch/:chapterId', {
* templateUrl: 'chapter.html',
* controller: 'ChapterController'
* });
*
* // configure html5 to get links working on jsfiddle
* $locationProvider.html5Mode(true);
* });
*
* </file>
*
* <file name="protractor.js" type="protractor">
* it('should load and compile correct template', function() {
* element(by.linkText('Moby: Ch1')).click();
* var content = element(by.css('[ng-view]')).getText();
* expect(content).toMatch(/controller: ChapterController/);
* expect(content).toMatch(/Book Id: Moby/);
* expect(content).toMatch(/Chapter Id: 1/);
*
* element(by.partialLinkText('Scarlet')).click();
*
* content = element(by.css('[ng-view]')).getText();
* expect(content).toMatch(/controller: BookController/);
* expect(content).toMatch(/Book Id: Scarlet/);
* });
* </file>
* </example>
*/
/**
* @ngdoc event
* @name $route#$routeChangeStart
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change. At this point the route services starts
* resolving all of the dependencies needed for the route change to occur.
* Typically this involves fetching the view template as well as any dependencies
* defined in `resolve` route property. Once all of the dependencies are resolved
* `$routeChangeSuccess` is fired.
*
* The route change (and the `$location` change that triggered it) can be prevented
* by calling `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on}
* for more details about event object.
*
* @param {Object} angularEvent Synthetic event object.
* @param {Route} next Future route information.
* @param {Route} current Current route information.
*/
/**
* @ngdoc event
* @name $route#$routeChangeSuccess
* @eventType broadcast on root scope
* @description
* Broadcasted after a route change has happened successfully.
* The `resolve` dependencies are now available in the `current.locals` property.
*
* {@link ngRoute.directive:ngView ngView} listens for the directive
* to instantiate the controller and render the view.
*
* @param {Object} angularEvent Synthetic event object.
* @param {Route} current Current route information.
* @param {Route|Undefined} previous Previous route information, or undefined if current is
* first route entered.
*/
/**
* @ngdoc event
* @name $route#$routeChangeError
* @eventType broadcast on root scope
* @description
* Broadcasted if a redirection function fails or any redirection or resolve promises are
* rejected.
*
* @param {Object} angularEvent Synthetic event object
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
* @param {Route} rejection The thrown error or the rejection reason of the promise. Usually
* the rejection reason is the error that caused the promise to get rejected.
*/
/**
* @ngdoc event
* @name $route#$routeUpdate
* @eventType broadcast on root scope
* @description
* Broadcasted if the same instance of a route (including template, controller instance,
* resolved dependencies, etc.) is being reused. This can happen if either `reloadOnSearch` or
* `reloadOnUrl` has been set to `false`.
*
* @param {Object} angularEvent Synthetic event object
* @param {Route} current Current/previous route information.
*/
var forceReload = false,
preparedRoute,
preparedRouteIsUpdateOnly,
$route = {
routes: routes,
/**
* @ngdoc method
* @name $route#reload
*
* @description
* Causes `$route` service to reload the current route even if
* {@link ng.$location $location} hasn't changed.
*
* As a result of that, {@link ngRoute.directive:ngView ngView}
* creates new scope and reinstantiates the controller.
*/
reload: function() {
forceReload = true;
var fakeLocationEvent = {
defaultPrevented: false,
preventDefault: function fakePreventDefault() {
this.defaultPrevented = true;
forceReload = false;
}
};
$rootScope.$evalAsync(function() {
prepareRoute(fakeLocationEvent);
if (!fakeLocationEvent.defaultPrevented) commitRoute();
});
},
/**
* @ngdoc method
* @name $route#updateParams
*
* @description
* Causes `$route` service to update the current URL, replacing
* current route parameters with those specified in `newParams`.
* Provided property names that match the route's path segment
* definitions will be interpolated into the location's path, while
* remaining properties will be treated as query params.
*
* @param {!Object<string, string>} newParams mapping of URL parameter names to values
*/
updateParams: function(newParams) {
if (this.current && this.current.$$route) {
newParams = angular.extend({}, this.current.params, newParams);
$location.path(interpolate(this.current.$$route.originalPath, newParams));
// interpolate modifies newParams, only query params are left
$location.search(newParams);
} else {
throw $routeMinErr('norout', 'Tried updating route with no current route');
}
}
};
$rootScope.$on('$locationChangeStart', prepareRoute);
$rootScope.$on('$locationChangeSuccess', commitRoute);
return $route;
/////////////////////////////////////////////////////
/**
* @param on {string} current url
* @param route {Object} route regexp to match the url against
* @return {?Object}
*
* @description
* Check if the route matches the current url.
*
* Inspired by match in
* visionmedia/express/lib/router/router.js.
*/
function switchRouteMatcher(on, route) {
var keys = route.keys,
params = {};
if (!route.regexp) return null;
var m = route.regexp.exec(on);
if (!m) return null;
for (var i = 1, len = m.length; i < len; ++i) {
var key = keys[i - 1];
var val = m[i];
if (key && val) {
params[key.name] = val;
}
}
return params;
}
function prepareRoute($locationEvent) {
var lastRoute = $route.current;
preparedRoute = parseRoute();
preparedRouteIsUpdateOnly = isNavigationUpdateOnly(preparedRoute, lastRoute);
if (!preparedRouteIsUpdateOnly && (lastRoute || preparedRoute)) {
if ($rootScope.$broadcast('$routeChangeStart', preparedRoute, lastRoute).defaultPrevented) {
if ($locationEvent) {
$locationEvent.preventDefault();
}
}
}
}
function commitRoute() {
var lastRoute = $route.current;
var nextRoute = preparedRoute;
if (preparedRouteIsUpdateOnly) {
lastRoute.params = nextRoute.params;
angular.copy(lastRoute.params, $routeParams);
$rootScope.$broadcast('$routeUpdate', lastRoute);
} else if (nextRoute || lastRoute) {
forceReload = false;
$route.current = nextRoute;
var nextRoutePromise = $q.resolve(nextRoute);
$browser.$$incOutstandingRequestCount('$route');
nextRoutePromise.
then(getRedirectionData).
then(handlePossibleRedirection).
then(function(keepProcessingRoute) {
return keepProcessingRoute && nextRoutePromise.
then(resolveLocals).
then(function(locals) {
// after route change
if (nextRoute === $route.current) {
if (nextRoute) {
nextRoute.locals = locals;
angular.copy(nextRoute.params, $routeParams);
}
$rootScope.$broadcast('$routeChangeSuccess', nextRoute, lastRoute);
}
});
}).catch(function(error) {
if (nextRoute === $route.current) {
$rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, error);
}
}).finally(function() {
// Because `commitRoute()` is called from a `$rootScope.$evalAsync` block (see
// `$locationWatch`), this `$$completeOutstandingRequest()` call will not cause
// `outstandingRequestCount` to hit zero. This is important in case we are redirecting
// to a new route which also requires some asynchronous work.
$browser.$$completeOutstandingRequest(noop, '$route');
});
}
}
function getRedirectionData(route) {
var data = {
route: route,
hasRedirection: false
};
if (route) {
if (route.redirectTo) {
if (angular.isString(route.redirectTo)) {
data.path = interpolate(route.redirectTo, route.params);
data.search = route.params;
data.hasRedirection = true;
} else {
var oldPath = $location.path();
var oldSearch = $location.search();
var newUrl = route.redirectTo(route.pathParams, oldPath, oldSearch);
if (angular.isDefined(newUrl)) {
data.url = newUrl;
data.hasRedirection = true;
}
}
} else if (route.resolveRedirectTo) {
return $q.
resolve($injector.invoke(route.resolveRedirectTo)).
then(function(newUrl) {
if (angular.isDefined(newUrl)) {
data.url = newUrl;
data.hasRedirection = true;
}
return data;
});
}
}
return data;
}
function handlePossibleRedirection(data) {
var keepProcessingRoute = true;
if (data.route !== $route.current) {
keepProcessingRoute = false;
} else if (data.hasRedirection) {
var oldUrl = $location.url();
var newUrl = data.url;
if (newUrl) {
$location.
url(newUrl).
replace();
} else {
newUrl = $location.
path(data.path).
search(data.search).
replace().
url();
}
if (newUrl !== oldUrl) {
// Exit out and don't process current next value,
// wait for next location change from redirect
keepProcessingRoute = false;
}
}
return keepProcessingRoute;
}
function resolveLocals(route) {
if (route) {
var locals = angular.extend({}, route.resolve);
angular.forEach(locals, function(value, key) {
locals[key] = angular.isString(value) ?
$injector.get(value) :
$injector.invoke(value, null, null, key);
});
var template = getTemplateFor(route);
if (angular.isDefined(template)) {
locals['$template'] = template;
}
return $q.all(locals);
}
}
function getTemplateFor(route) {
var template, templateUrl;
if (angular.isDefined(template = route.template)) {
if (angular.isFunction(template)) {
template = template(route.params);
}
} else if (angular.isDefined(templateUrl = route.templateUrl)) {
if (angular.isFunction(templateUrl)) {
templateUrl = templateUrl(route.params);
}
if (angular.isDefined(templateUrl)) {
route.loadedTemplateUrl = $sce.valueOf(templateUrl);
template = $templateRequest(templateUrl);
}
}
return template;
}
/**
* @returns {Object} the current active route, by matching it against the URL
*/
function parseRoute() {
// Match a route
var params, match;
angular.forEach(routes, function(route, path) {
if (!match && (params = switchRouteMatcher($location.path(), route))) {
match = inherit(route, {
params: angular.extend({}, $location.search(), params),
pathParams: params});
match.$$route = route;
}
});
// No route matched; fallback to "otherwise" route
return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
}
/**
* @param {Object} newRoute - The new route configuration (as returned by `parseRoute()`).
* @param {Object} oldRoute - The previous route configuration (as returned by `parseRoute()`).
* @returns {boolean} Whether this is an "update-only" navigation, i.e. the URL maps to the same
* route and it can be reused (based on the config and the type of change).
*/
function isNavigationUpdateOnly(newRoute, oldRoute) {
// IF this is not a forced reload
return !forceReload
// AND both `newRoute`/`oldRoute` are defined
&& newRoute && oldRoute
// AND they map to the same Route Definition Object
&& (newRoute.$$route === oldRoute.$$route)
// AND `reloadOnUrl` is disabled
&& (!newRoute.reloadOnUrl
// OR `reloadOnSearch` is disabled
|| (!newRoute.reloadOnSearch
// AND both routes have the same path params
&& angular.equals(newRoute.pathParams, oldRoute.pathParams)
)
);
}
/**
* @returns {string} interpolation of the redirect path with the parameters
*/
function interpolate(string, params) {
var result = [];
angular.forEach((string || '').split(':'), function(segment, i) {
if (i === 0) {
result.push(segment);
} else {
var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/);
var key = segmentMatch[1];
result.push(params[key]);
result.push(segmentMatch[2] || '');
delete params[key];
}
});
return result.join('');
}
}];
}
instantiateRoute.$inject = ['$injector'];
function instantiateRoute($injector) {
if (isEagerInstantiationEnabled) {
// Instantiate `$route`
$injector.get('$route');
}
}
ngRouteModule.provider('$routeParams', $RouteParamsProvider);
/**
* @ngdoc service
* @name $routeParams
* @requires $route
* @this
*
* @description
* The `$routeParams` service allows you to retrieve the current set of route parameters.
*
* Requires the {@link ngRoute `ngRoute`} module to be installed.
*
* The route parameters are a combination of {@link ng.$location `$location`}'s
* {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}.
* The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched.
*
* In case of parameter name collision, `path` params take precedence over `search` params.
*
* The service guarantees that the identity of the `$routeParams` object will remain unchanged
* (but its properties will likely change) even when a route change occurs.
*
* Note that the `$routeParams` are only updated *after* a route change completes successfully.
* This means that you cannot rely on `$routeParams` being correct in route resolve functions.
* Instead you can use `$route.current.params` to access the new route's parameters.
*
* @example
* ```js
* // Given:
* // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
* // Route: /Chapter/:chapterId/Section/:sectionId
* //
* // Then
* $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
* ```
*/
function $RouteParamsProvider() {
this.$get = function() { return {}; };
}
ngRouteModule.directive('ngView', ngViewFactory);
ngRouteModule.directive('ngView', ngViewFillContentFactory);
/**
* @ngdoc directive
* @name ngView
* @restrict ECA
*
* @description
* `ngView` is a directive that complements the {@link ngRoute.$route $route} service by
* including the rendered template of the current route into the main layout (`index.html`) file.
* Every time the current route changes, the included view changes with it according to the
* configuration of the `$route` service.
*
* Requires the {@link ngRoute `ngRoute`} module to be installed.
*
* @animations
* | Animation | Occurs |
* |----------------------------------|-------------------------------------|
* | {@link ng.$animate#enter enter} | when the new element is inserted to the DOM |
* | {@link ng.$animate#leave leave} | when the old element is removed from to the DOM |
*
* The enter and leave animation occur concurrently.
*
* @scope
* @priority 400
* @param {string=} onload Expression to evaluate whenever the view updates.
*
* @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll
* $anchorScroll} to scroll the viewport after the view is updated.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated
* as an expression yields a truthy value.
* @example
<example name="ngView-directive" module="ngViewExample"
deps="angular-route.js;angular-animate.js"
animations="true" fixBase="true">
<file name="index.html">
<div ng-controller="MainCtrl as main">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div class="view-animate-container">
<div ng-view class="view-animate"></div>
</div>
<hr />
<pre>$location.path() = {{main.$location.path()}}</pre>
<pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
<pre>$route.current.params = {{main.$route.current.params}}</pre>
<pre>$routeParams = {{main.$routeParams}}</pre>
</div>
</file>
<file name="book.html">
<div>
controller: {{book.name}}<br />
Book Id: {{book.params.bookId}}<br />
</div>
</file>
<file name="chapter.html">
<div>
controller: {{chapter.name}}<br />
Book Id: {{chapter.params.bookId}}<br />
Chapter Id: {{chapter.params.chapterId}}
</div>
</file>
<file name="animations.css">
.view-animate-container {
position:relative;
height:100px!important;
background:white;
border:1px solid black;
height:40px;
overflow:hidden;
}
.view-animate {
padding:10px;
}
.view-animate.ng-enter, .view-animate.ng-leave {
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
display:block;
width:100%;
border-left:1px solid black;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
padding:10px;
}
.view-animate.ng-enter {
left:100%;
}
.view-animate.ng-enter.ng-enter-active {
left:0;
}
.view-animate.ng-leave.ng-leave-active {
left:-100%;
}
</file>
<file name="script.js">
angular.module('ngViewExample', ['ngRoute', 'ngAnimate'])
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: 'BookCtrl',
controllerAs: 'book'
})
.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: 'ChapterCtrl',
controllerAs: 'chapter'
});
$locationProvider.html5Mode(true);
}])
.controller('MainCtrl', ['$route', '$routeParams', '$location',
function MainCtrl($route, $routeParams, $location) {
this.$route = $route;
this.$location = $location;
this.$routeParams = $routeParams;
}])
.controller('BookCtrl', ['$routeParams', function BookCtrl($routeParams) {
this.name = 'BookCtrl';
this.params = $routeParams;
}])
.controller('ChapterCtrl', ['$routeParams', function ChapterCtrl($routeParams) {
this.name = 'ChapterCtrl';
this.params = $routeParams;
}]);
</file>
<file name="protractor.js" type="protractor">
it('should load and compile correct template', function() {
element(by.linkText('Moby: Ch1')).click();
var content = element(by.css('[ng-view]')).getText();
expect(content).toMatch(/controller: ChapterCtrl/);
expect(content).toMatch(/Book Id: Moby/);
expect(content).toMatch(/Chapter Id: 1/);
element(by.partialLinkText('Scarlet')).click();
content = element(by.css('[ng-view]')).getText();
expect(content).toMatch(/controller: BookCtrl/);
expect(content).toMatch(/Book Id: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ngView#$viewContentLoaded
* @eventType emit on the current ngView scope
* @description
* Emitted every time the ngView content is reloaded.
*/
ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate'];
function ngViewFactory($route, $anchorScroll, $animate) {
return {
restrict: 'ECA',
terminal: true,
priority: 400,
transclude: 'element',
link: function(scope, $element, attr, ctrl, $transclude) {
var currentScope,
currentElement,
previousLeaveAnimation,
autoScrollExp = attr.autoscroll,
onloadExp = attr.onload || '';
scope.$on('$routeChangeSuccess', update);
update();
function cleanupLastView() {
if (previousLeaveAnimation) {
$animate.cancel(previousLeaveAnimation);
previousLeaveAnimation = null;
}
if (currentScope) {
currentScope.$destroy();
currentScope = null;
}
if (currentElement) {
previousLeaveAnimation = $animate.leave(currentElement);
previousLeaveAnimation.done(function(response) {
if (response !== false) previousLeaveAnimation = null;
});
currentElement = null;
}
}
function update() {
var locals = $route.current && $route.current.locals,
template = locals && locals.$template;
if (angular.isDefined(template)) {
var newScope = scope.$new();
var current = $route.current;
// Note: This will also link all children of ng-view that were contained in the original
// html. If that content contains controllers, ... they could pollute/change the scope.
// However, using ng-view on an element with additional content does not make sense...
// Note: We can't remove them in the cloneAttchFn of $transclude as that
// function is called before linking the content, which would apply child
// directives to non existing elements.
var clone = $transclude(newScope, function(clone) {
$animate.enter(clone, null, currentElement || $element).done(function onNgViewEnter(response) {
if (response !== false && angular.isDefined(autoScrollExp)
&& (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
});
cleanupLastView();
});
currentElement = clone;
currentScope = current.scope = newScope;
currentScope.$emit('$viewContentLoaded');
currentScope.$eval(onloadExp);
} else {
cleanupLastView();
}
}
}
};
}
// This directive is called during the $transclude call of the first `ngView` directive.
// It will replace and compile the content of the element with the loaded template.
// We need this directive so that the element content is already filled when
// the link function of another directive on the same element as ngView
// is called.
ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route'];
function ngViewFillContentFactory($compile, $controller, $route) {
return {
restrict: 'ECA',
priority: -400,
link: function(scope, $element) {
var current = $route.current,
locals = current.locals;
$element.html(locals.$template);
var link = $compile($element.contents());
if (current.controller) {
locals.$scope = scope;
var controller = $controller(current.controller, locals);
if (current.controllerAs) {
scope[current.controllerAs] = controller;
}
$element.data('$ngControllerController', controller);
$element.children().data('$ngControllerController', controller);
}
scope[current.resolveAs || '$resolve'] = locals;
link(scope);
}
};
}
describe('ngView', function() {
describe('basics', function() {
var element;
beforeEach(module('ngRoute'));
beforeEach(module(function($provide) {
return function($rootScope, $compile, $animate) {
element = $compile('<div><ng:view onload="load()"></ng:view></div>')($rootScope);
};
}));
afterEach(function() {
dealoc(element);
});
it('should do nothing when no routes are defined',
inject(function($rootScope, $compile, $location) {
$location.path('/unknown');
$rootScope.$digest();
expect(element.text()).toEqual('');
}));
it('should instantiate controller after compiling the content', function() {
var log = [], controllerScope,
Ctrl = function($scope) {
controllerScope = $scope;
log.push('ctrl-init');
};
module(function($compileProvider, $routeProvider) {
$compileProvider.directive('compileLog', function() {
return {
compile: function() {
log.push('compile');
}
};
});
$routeProvider.when('/some', {templateUrl: '/tpl.html', controller: Ctrl});
});
inject(function($route, $rootScope, $templateCache, $location) {
$templateCache.put('/tpl.html', [200, '<div compile-log>partial</div>', {}]);
$location.path('/some');
$rootScope.$digest();
expect(controllerScope.$parent).toBe($rootScope);
expect(controllerScope).toBe($route.current.scope);
expect(log).toEqual(['compile', 'ctrl-init']);
});
});
it('should instantiate the associated controller when an empty template is downloaded', function() {
var log = [], controllerScope,
Ctrl = function($scope) {
controllerScope = $scope;
log.push('ctrl-init');
};
module(function($routeProvider) {
$routeProvider.when('/some', {templateUrl: '/tpl.html', controller: Ctrl});
});
inject(function($route, $rootScope, $templateCache, $location) {
$templateCache.put('/tpl.html', [200, '', {}]);
$location.path('/some');
expect(function() {
$rootScope.$digest();
}).not.toThrow();
expect(controllerScope).toBeDefined();
});
});
it('should instantiate controller with an alias', function() {
var log = [], controllerScope;
function Ctrl($scope) {
this.name = 'alias';
controllerScope = $scope;
}
module(function($compileProvider, $routeProvider) {
$routeProvider.when('/some', {templateUrl: '/tpl.html', controller: Ctrl, controllerAs: 'ctrl'});
});
inject(function($route, $rootScope, $templateCache, $location) {
$templateCache.put('/tpl.html', [200, '<div></div>', {}]);
$location.path('/some');
$rootScope.$digest();
expect(controllerScope.ctrl.name).toBe('alias');
});
});
it('should support string controller declaration', function() {
var MyCtrl = jasmine.createSpy('MyCtrl');
module(function($controllerProvider, $routeProvider) {
$controllerProvider.register('MyCtrl', ['$scope', MyCtrl]);
$routeProvider.when('/foo', {controller: 'MyCtrl', templateUrl: '/tpl.html'});
});
inject(function($route, $location, $rootScope, $templateCache) {
$templateCache.put('/tpl.html', [200, '<div></div>', {}]);
$location.path('/foo');
$rootScope.$digest();
expect($route.current.controller).toBe('MyCtrl');
expect(MyCtrl).toHaveBeenCalledWith(element.children().scope());
});
});
it('should reference resolved locals in scope', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {
resolve: {
name: function() {
return 'shahar';
}
},
template: '<div>{{$resolve.name}}</div>'
});
});
inject(function($location, $rootScope) {
$location.path('/foo');
$rootScope.$digest();
expect(element.text()).toEqual('shahar');
});
});
it('should allow to provide an alias for resolved locals using resolveAs', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {
resolveAs: 'myResolve',
resolve: {
name: function() {
return 'shahar';
}
},
template: '<div>{{myResolve.name}}</div>'
});
});
inject(function($location, $rootScope) {
$location.path('/foo');
$rootScope.$digest();
expect(element.text()).toEqual('shahar');
});
});
it('should load content via xhr when route changes', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'myUrl1'});
$routeProvider.when('/bar', {templateUrl: 'myUrl2'});
});
inject(function($rootScope, $compile, $httpBackend, $location, $route) {
expect(element.text()).toEqual('');
$location.path('/foo');
$httpBackend.expect('GET', 'myUrl1').respond('<div>{{1+3}}</div>');
$rootScope.$digest();
$httpBackend.flush();
expect(element.text()).toEqual('4');
$location.path('/bar');
$httpBackend.expect('GET', 'myUrl2').respond('angular is da best');
$rootScope.$digest();
$httpBackend.flush();
expect(element.text()).toEqual('angular is da best');
});
});
it('should use inline content route changes', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {template: '<div>{{1+3}}</div>'});
$routeProvider.when('/bar', {template: 'AngularJS is da best'});
$routeProvider.when('/blank', {template: ''});
});
inject(function($rootScope, $compile, $location, $route) {
expect(element.text()).toEqual('');
$location.path('/foo');
$rootScope.$digest();
expect(element.text()).toEqual('4');
$location.path('/bar');
$rootScope.$digest();
expect(element.text()).toEqual('AngularJS is da best');
$location.path('/blank');
$rootScope.$digest();
expect(element.text()).toEqual('');
});
});
it('should remove all content when location changes to an unknown route', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'myUrl1'});
});
inject(function($rootScope, $compile, $location, $httpBackend, $route) {
$location.path('/foo');
$httpBackend.expect('GET', 'myUrl1').respond('<div>{{1+3}}</div>');
$rootScope.$digest();
$httpBackend.flush();
expect(element.text()).toEqual('4');
$location.path('/unknown');
$rootScope.$digest();
expect(element.text()).toEqual('');
});
});
it('should chain scopes and propagate evals to the child scope', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'myUrl1'});
});
inject(function($rootScope, $compile, $location, $httpBackend, $route) {
$rootScope.parentVar = 'parent';
$location.path('/foo');
$httpBackend.expect('GET', 'myUrl1').respond('<div>{{parentVar}}</div>');
$rootScope.$digest();
$httpBackend.flush();
expect(element.text()).toEqual('parent');
$rootScope.parentVar = 'new parent';
$rootScope.$digest();
expect(element.text()).toEqual('new parent');
});
});
it('should be possible to nest ngView in ngInclude', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'viewPartial.html'});
});
inject(function($httpBackend, $location, $route, $compile, $rootScope) {
$httpBackend.whenGET('includePartial.html').respond('view: <ng:view></ng:view>');
$httpBackend.whenGET('viewPartial.html').respond('content');
$location.path('/foo');
var elm = $compile(
'<div>' +
'include: <ng:include src="\'includePartial.html\'"> </ng:include>' +
'</div>')($rootScope);
$rootScope.$digest();
$httpBackend.flush();
expect(elm.text()).toEqual('include: view: content');
expect($route.current.templateUrl).toEqual('viewPartial.html');
dealoc(elm);
});
});
it('should initialize view template after the view controller was initialized even when ' +
'templates were cached', function() {
//this is a test for a regression that was introduced by making the ng-view cache sync
function ParentCtrl($scope) {
$scope.log.push('parent');
}
module(function($routeProvider) {
$routeProvider.when('/foo', {controller: ParentCtrl, templateUrl: 'viewPartial.html'});
});
inject(function($rootScope, $compile, $location, $httpBackend, $route) {
$rootScope.log = [];
$rootScope.ChildCtrl = function($scope) {
$scope.log.push('child');
};
$location.path('/foo');
$httpBackend.expect('GET', 'viewPartial.html').
respond('<div ng-init="log.push(\'init\')">' +
'<div ng-controller="ChildCtrl"></div>' +
'</div>');
$rootScope.$apply();
$httpBackend.flush();
expect($rootScope.log).toEqual(['parent', 'init', 'child']);
$location.path('/');
$rootScope.$apply();
expect($rootScope.log).toEqual(['parent', 'init', 'child']);
$rootScope.log = [];
$location.path('/foo');
$rootScope.$apply();
expect($rootScope.log).toEqual(['parent', 'init', 'child']);
});
});
it('should discard pending xhr callbacks if a new route is requested before the current ' +
'finished loading', function() {
// this is a test for a bad race condition that affected feedback
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'myUrl1'});
$routeProvider.when('/bar', {templateUrl: 'myUrl2'});
});
inject(function($route, $rootScope, $location, $httpBackend) {
expect(element.text()).toEqual('');
$location.path('/foo');
$httpBackend.expect('GET', 'myUrl1').respond('<div>{{1+3}}</div>');
$rootScope.$digest();
$location.path('/bar');
$httpBackend.expect('GET', 'myUrl2').respond('<div>{{1+1}}</div>');
$rootScope.$digest();
$httpBackend.flush(); // now that we have two requests pending, flush!
expect(element.text()).toEqual('2');
});
});
it('should be async even if served from cache', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {controller: angular.noop, templateUrl: 'myUrl1'});
});
inject(function($route, $rootScope, $location, $templateCache) {
$templateCache.put('myUrl1', [200, 'my partial', {}]);
$location.path('/foo');
var called = 0;
// we want to assert only during first watch
$rootScope.$watch(function() {
if (!called) expect(element.text()).toBe('');
called++;
});
$rootScope.$digest();
expect(element.text()).toBe('my partial');
});
});
it('should fire $contentLoaded event when content compiled and linked', function() {
var log = [];
var logger = function(name) {
return function() {
log.push(name);
};
};
var Ctrl = function($scope) {
$scope.value = 'bound-value';
log.push('init-ctrl');
};
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'tpl.html', controller: Ctrl});
});
inject(function($templateCache, $rootScope, $location) {
$rootScope.$on('$routeChangeStart', logger('$routeChangeStart'));
$rootScope.$on('$routeChangeSuccess', logger('$routeChangeSuccess'));
$rootScope.$on('$viewContentLoaded', logger('$viewContentLoaded'));
$templateCache.put('tpl.html', [200, '{{value}}', {}]);
$location.path('/foo');
$rootScope.$digest();
expect(element.text()).toBe('bound-value');
expect(log).toEqual([
'$routeChangeStart', 'init-ctrl', '$viewContentLoaded', '$routeChangeSuccess'
]);
});
});
it('should destroy previous scope', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'tpl.html'});
});
inject(function($templateCache, $rootScope, $location) {
$templateCache.put('tpl.html', [200, 'partial', {}]);
expect($rootScope.$$childHead).toBeNull();
expect($rootScope.$$childTail).toBeNull();
$location.path('/foo');
$rootScope.$digest();
expect(element.text()).toBe('partial');
expect($rootScope.$$childHead).not.toBeNull();
expect($rootScope.$$childTail).not.toBeNull();
$location.path('/non/existing/route');
$rootScope.$digest();
expect(element.text()).toBe('');
expect($rootScope.$$childHead).toBeNull();
expect($rootScope.$$childTail).toBeNull();
});
});
it('should destroy previous scope if multiple route changes occur before server responds',
function() {
var log = [];
var createCtrl = function(name) {
return function($scope) {
log.push('init-' + name);
$scope.$on('$destroy', function() {log.push('destroy-' + name);});
};
};
module(function($routeProvider) {
$routeProvider.when('/one', {templateUrl: 'one.html', controller: createCtrl('ctrl1')});
$routeProvider.when('/two', {templateUrl: 'two.html', controller: createCtrl('ctrl2')});
});
inject(function($httpBackend, $rootScope, $location) {
$httpBackend.whenGET('one.html').respond('content 1');
$httpBackend.whenGET('two.html').respond('content 2');
$location.path('/one');
$rootScope.$digest();
$location.path('/two');
$rootScope.$digest();
$httpBackend.flush();
expect(element.text()).toBe('content 2');
expect(log).toEqual(['init-ctrl2']);
$location.path('/non-existing');
$rootScope.$digest();
expect(element.text()).toBe('');
expect(log).toEqual(['init-ctrl2', 'destroy-ctrl2']);
expect($rootScope.$$childHead).toBeNull();
expect($rootScope.$$childTail).toBeNull();
});
});
it('should $destroy scope after update and reload', function() {
// this is a regression of bug, where $route doesn't copy scope when only updating
var log = [];
function logger(msg) {
return function() {
log.push(msg);
};
}
function createController(name) {
return function($scope) {
log.push('init-' + name);
$scope.$on('$destroy', logger('destroy-' + name));
$scope.$on('$routeUpdate', logger('route-update'));
};
}
module(function($routeProvider) {
$routeProvider.when('/bar', {templateUrl: 'tpl.html', controller: createController('bar')});
$routeProvider.when('/foo', {
templateUrl: 'tpl.html',
controller: createController('foo'),
reloadOnSearch: false
});
});
inject(function($templateCache, $location, $rootScope) {
$templateCache.put('tpl.html', [200, 'partial', {}]);
$location.url('/foo');
$rootScope.$digest();
expect(log).toEqual(['init-foo']);
$location.search({q: 'some'});
$rootScope.$digest();
expect(log).toEqual(['init-foo', 'route-update']);
$location.url('/bar');
$rootScope.$digest();
expect(log).toEqual(['init-foo', 'route-update', 'destroy-foo', 'init-bar']);
});
});
it('should evaluate onload expression after linking the content', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'tpl.html'});
});
inject(function($templateCache, $location, $rootScope) {
$templateCache.put('tpl.html', [200, '{{1+1}}', {}]);
$rootScope.load = jasmine.createSpy('onload');
$location.url('/foo');
$rootScope.$digest();
expect($rootScope.load).toHaveBeenCalledOnce();
});
});
it('should set $scope and $controllerController on the view elements (except for non-element nodes)', function() {
function MyCtrl($scope) {
$scope.state = 'WORKS';
$scope.ctrl = this;
}
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'tpl.html', controller: MyCtrl});
});
inject(function($templateCache, $location, $rootScope, $route) {
// in the template the white-space before the div is an intentional non-element node,
// a text might get wrapped into span so it's safer to just use white space
$templateCache.put('tpl.html', [200, ' \n <div>{{state}}</div>', {}]);
$location.url('/foo');
$rootScope.$digest();
expect(element.text()).toEqual(' \n WORKS');
var div = element.find('div');
expect(div.parent()[0].nodeName.toUpperCase()).toBeOneOf('NG:VIEW', 'VIEW');
expect(div.scope()).toBe($route.current.scope);
expect(div.scope().hasOwnProperty('state')).toBe(true);
expect(div.scope().state).toEqual('WORKS');
expect(div.controller()).toBe($route.current.scope.ctrl);
});
});
it('should not set $scope or $controllerController on top level text elements in the view', function() {
function MyCtrl($scope) {}
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'tpl.html', controller: MyCtrl});
});
inject(function($templateCache, $location, $rootScope, $route) {
$templateCache.put('tpl.html', '<div></div> ');
$location.url('/foo');
$rootScope.$digest();
angular.forEach(element.contents(), function(node) {
if (node.nodeType === 3 /* text node */) {
expect(angular.element(node).scope()).not.toBe($route.current.scope);
expect(angular.element(node).controller()).not.toBeDefined();
} else if (node.nodeType === 8 /* comment node */) {
expect(angular.element(node).scope()).toBe(element.scope());
expect(angular.element(node).controller()).toBe(element.controller());
} else {
expect(angular.element(node).scope()).toBe($route.current.scope);
expect(angular.element(node).controller()).toBeDefined();
}
});
});
});
it('should not trigger a digest when the view is changed', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'myUrl1'});
$routeProvider.when('/bar', {templateUrl: 'myUrl2'});
});
inject(function($$rAF, $templateCache, $rootScope, $compile, $timeout, $location, $httpBackend) {
var spy = spyOn($rootScope, '$digest').and.callThrough();
$templateCache.put('myUrl1', 'my template content');
$templateCache.put('myUrl2', 'my other template content');
$location.path('/foo');
$rootScope.$digest();
// The animation completion is async even without actual animations
$$rAF.flush();
expect(element.text()).toEqual('my template content');
$location.path('/bar');
$rootScope.$digest();
spy.calls.reset();
$$rAF.flush();
expect(element.text()).toEqual('my other template content');
expect(spy).not.toHaveBeenCalled();
// A digest may have been triggered asynchronously, so check the queue
$timeout.verifyNoPendingTasks();
});
});
});
describe('and transcludes', function() {
var element, directive;
beforeEach(module('ngRoute', function($compileProvider) {
element = null;
directive = $compileProvider.directive;
}));
afterEach(function() {
if (element) {
dealoc(element);
}
});
it('should allow access to directive controller from children when used in a replace template', function() {
var controller;
module(function($routeProvider) {
$routeProvider.when('/view', {templateUrl: 'view.html'});
directive('template', function() {
return {
template: '<div ng-view></div>',
replace: true,
controller: function() {
this.flag = true;
}
};
});
directive('test', function() {
return {
require: '^template',
link: function(scope, el, attr, ctrl) {
controller = ctrl;
}
};
});
});
inject(function($compile, $rootScope, $httpBackend, $location) {
$httpBackend.expectGET('view.html').respond('<div><div test></div></div>');
element = $compile('<div><div template></div></div>')($rootScope);
$location.url('/view');
$rootScope.$apply();
$httpBackend.flush();
expect(controller.flag).toBe(true);
});
});
it('should compile its content correctly (although we remove it later)', function() {
var testElement;
module(function($compileProvider, $routeProvider) {
$routeProvider.when('/view', {template: ' '});
var directive = $compileProvider.directive;
directive('test', function() {
return {
link: function(scope, element) {
testElement = element;
}
};
});
});
inject(function($compile, $rootScope, $location) {
element = $compile('<div><div ng-view><div test someAttr></div></div></div>')($rootScope);
$location.url('/view');
$rootScope.$apply();
expect(testElement[0].nodeName).toBe('DIV');
});
});
it('should link directives on the same element after the content has been loaded', function() {
var contentOnLink;
module(function($compileProvider, $routeProvider) {
$routeProvider.when('/view', {template: 'someContent'});
$compileProvider.directive('test', function() {
return {
link: function(scope, element) {
contentOnLink = element.text();
}
};
});
});
inject(function($compile, $rootScope, $location) {
element = $compile('<div><div ng-view test></div>')($rootScope);
$location.url('/view');
$rootScope.$apply();
expect(contentOnLink).toBe('someContent');
});
});
it('should add the content to the element before compiling it', function() {
var root;
module(function($compileProvider, $routeProvider) {
$routeProvider.when('/view', {template: '<span test></span>'});
$compileProvider.directive('test', function() {
return {
link: function(scope, element) {
root = element.parent().parent();
}
};
});
});
inject(function($compile, $rootScope, $location) {
element = $compile('<div><div ng-view></div>')($rootScope);
$location.url('/view');
$rootScope.$apply();
expect(root[0]).toBe(element[0]);
});
});
});
describe('animations', function() {
var body, element, $rootElement;
beforeEach(module('ngRoute'));
function html(content) {
$rootElement.html(content);
body.append($rootElement);
element = $rootElement.children().eq(0);
return element;
}
beforeEach(module(function() {
// we need to run animation on attached elements;
return function(_$rootElement_) {
$rootElement = _$rootElement_;
body = angular.element(window.document.body);
};
}));
afterEach(function() {
dealoc(body);
dealoc(element);
});
beforeEach(module(function($provide, $routeProvider) {
$routeProvider.when('/foo', {controller: angular.noop, templateUrl: '/foo.html'});
$routeProvider.when('/bar', {controller: angular.noop, templateUrl: '/bar.html'});
return function($templateCache) {
$templateCache.put('/foo.html', [200, '<div>data</div>', {}]);
$templateCache.put('/bar.html', [200, '<div>data2</div>', {}]);
};
}));
describe('hooks', function() {
beforeEach(module('ngAnimate'));
beforeEach(module('ngAnimateMock'));
it('should fire off the enter animation',
inject(function($compile, $rootScope, $location, $timeout, $animate) {
element = $compile(html('<div ng-view></div>'))($rootScope);
$location.path('/foo');
$rootScope.$digest();
var animation = $animate.queue.pop();
expect(animation.event).toBe('enter');
}));
it('should fire off the leave animation',
inject(function($compile, $rootScope, $location, $templateCache, $timeout, $animate) {
var item;
$templateCache.put('/foo.html', [200, '<div>foo</div>', {}]);
element = $compile(html('<div ng-view></div>'))($rootScope);
$location.path('/foo');
$rootScope.$digest();
$location.path('/');
$rootScope.$digest();
var animation = $animate.queue.pop();
expect(animation.event).toBe('leave');
}));
it('should animate two separate ngView elements',
inject(function($compile, $rootScope, $templateCache, $location, $animate) {
var item;
$rootScope.tpl = 'one';
element = $compile(html('<div ng-view></div>'))($rootScope);
$rootScope.$digest();
$location.path('/foo');
$rootScope.$digest();
//we don't care about the enter animation for the first element
$animate.queue.pop();
$location.path('/bar');
$rootScope.$digest();
var animationB = $animate.queue.pop();
expect(animationB.event).toBe('leave');
var itemB = animationB.args[0];
var animationA = $animate.queue.pop();
expect(animationA.event).toBe('enter');
var itemA = animationA.args[0];
expect(itemA).not.toEqual(itemB);
})
);
it('should render ngClass on ngView',
inject(function($compile, $rootScope, $templateCache, $animate, $location) {
var item;
$rootScope.tpl = 'one';
$rootScope.klass = 'classy';
element = $compile(html('<div><div ng-view ng-class="klass"></div></div>'))($rootScope);
$rootScope.$digest();
$location.path('/foo');
$rootScope.$digest();
$animate.flush();
//we don't care about the enter animation
$animate.queue.shift();
var animation = $animate.queue.shift();
expect(animation.event).toBe('addClass');
item = animation.element;
expect(item.hasClass('classy')).toBe(true);
$rootScope.klass = 'boring';
$rootScope.$digest();
expect($animate.queue.shift().event).toBe('addClass');
expect($animate.queue.shift().event).toBe('removeClass');
$animate.flush();
expect(item.hasClass('classy')).toBe(false);
expect(item.hasClass('boring')).toBe(true);
$location.path('/bar');
$rootScope.$digest();
//we don't care about the enter animation
$animate.queue.shift();
animation = $animate.queue.shift();
item = animation.element;
expect(animation.event).toBe('leave');
expect($animate.queue.shift().event).toBe('addClass');
expect(item.hasClass('boring')).toBe(true);
})
);
it('should not double compile when the route changes', function() {
var window;
module(function($routeProvider, $animateProvider, $provide) {
$routeProvider.when('/foo', {template: '<div ng-repeat="i in [1,2]">{{i}}</div>'});
$routeProvider.when('/bar', {template: '<div ng-repeat="i in [3,4]">{{i}}</div>'});
$animateProvider.register('.my-animation', function() {
return {
leave: function(element, done) {
done();
}
};
});
});
inject(function($rootScope, $compile, $location, $route, $timeout, $rootElement, $sniffer, $animate) {
element = $compile(html('<div><ng:view onload="load()" class="my-animation"></ng:view></div>'))($rootScope);
$animate.enabled(true);
$location.path('/foo');
$rootScope.$digest();
expect($animate.queue.shift().event).toBe('enter'); //ngView
expect($animate.queue.shift().event).toBe('enter'); //repeat 1
expect($animate.queue.shift().event).toBe('enter'); //repeat 2
expect(element.text()).toEqual('12');
$location.path('/bar');
$rootScope.$digest();
expect($animate.queue.shift().event).toBe('enter'); //ngView new
expect($animate.queue.shift().event).toBe('leave'); //ngView old
$rootScope.$digest();
expect($animate.queue.shift().event).toBe('enter'); //ngRepeat 3
expect($animate.queue.shift().event).toBe('enter'); //ngRepeat 4
$animate.flush();
expect(element.text()).toEqual('34');
function n(text) {
return text.replace(/\r\n/m, '').replace(/\r\n/m, '');
}
});
});
it('should destroy the previous leave animation if a new one takes place',
inject(function($compile, $rootScope, $animate, $location, $timeout) {
var $scope = $rootScope.$new();
element = $compile(html(
'<div>' +
'<div ng-view></div>' +
'</div>'
))($scope);
$scope.$apply('value = true');
$location.path('/bar');
$rootScope.$digest();
var destroyed, inner = element.children(0);
inner.on('$destroy', function() {
destroyed = true;
});
$location.path('/foo');
$rootScope.$digest();
$location.path('/bar');
$rootScope.$digest();
$location.path('/bar');
$rootScope.$digest();
expect(destroyed).toBe(true);
})
);
});
describe('autoscroll', function() {
var autoScrollSpy;
function spyOnAnchorScroll() {
return function($provide, $routeProvider) {
autoScrollSpy = jasmine.createSpy('$anchorScroll');
$provide.value('$anchorScroll', autoScrollSpy);
$routeProvider.when('/foo', {
controller: angular.noop,
template: '<div></div>'
});
};
}
function spyOnAnimateEnter() {
return function($animate) {
spyOn($animate, 'enter').and.callThrough();
};
}
function compileAndLink(tpl) {
return function($compile, $rootScope, $location) {
element = $compile(tpl)($rootScope);
};
}
beforeEach(module(spyOnAnchorScroll(), 'ngAnimateMock'));
beforeEach(inject(spyOnAnimateEnter()));
it('should call $anchorScroll if autoscroll attribute is present', inject(
compileAndLink('<div><ng:view autoscroll></ng:view></div>'),
function($rootScope, $animate, $timeout, $location) {
$location.path('/foo');
$rootScope.$digest();
$animate.flush();
$rootScope.$digest();
expect($animate.queue.shift().event).toBe('enter');
expect(autoScrollSpy).toHaveBeenCalledOnce();
}));
it('should call $anchorScroll if autoscroll evaluates to true', inject(
compileAndLink('<div><ng:view src="tpl" autoscroll="value"></ng:view></div>'),
function($rootScope, $animate, $timeout, $location) {
$rootScope.value = true;
$location.path('/foo');
$rootScope.$digest();
$animate.flush();
$rootScope.$digest();
expect($animate.queue.shift().event).toBe('enter');
expect(autoScrollSpy).toHaveBeenCalledOnce();
}));
it('should not call $anchorScroll if autoscroll attribute is not present', inject(
compileAndLink('<div><ng:view></ng:view></div>'),
function($rootScope, $location, $animate, $timeout) {
$location.path('/foo');
$rootScope.$digest();
expect($animate.queue.shift().event).toBe('enter');
expect(autoScrollSpy).not.toHaveBeenCalled();
}));
it('should not call $anchorScroll if autoscroll evaluates to false', inject(
compileAndLink('<div><ng:view autoscroll="value"></ng:view></div>'),
function($rootScope, $location, $animate, $timeout) {
$rootScope.value = false;
$location.path('/foo');
$rootScope.$digest();
expect($animate.queue.shift().event).toBe('enter');
expect(autoScrollSpy).not.toHaveBeenCalled();
}));
it('should only call $anchorScroll after the "enter" animation completes', inject(
compileAndLink('<div><ng:view autoscroll></ng:view></div>'),
function($rootScope, $location, $animate, $timeout) {
$location.path('/foo');
expect($animate.enter).not.toHaveBeenCalled();
$rootScope.$digest();
expect(autoScrollSpy).not.toHaveBeenCalled();
expect($animate.queue.shift().event).toBe('enter');
$animate.flush();
$rootScope.$digest();
expect($animate.enter).toHaveBeenCalledOnce();
expect(autoScrollSpy).toHaveBeenCalledOnce();
}
));
});
});
describe('in async template', function() {
beforeEach(module('ngRoute'));
beforeEach(module(function($compileProvider, $provide, $routeProvider) {
$compileProvider.directive('asyncView', function() {
return {templateUrl: 'async-view.html'};
});
$provide.decorator('$templateRequest', function($timeout) {
return function() {
return $timeout(angular.identity, 500, false, '<ng-view></ng-view>');
};
});
$routeProvider.when('/', {template: 'Hello, world!'});
}));
it('should work correctly upon initial page load',
// Injecting `$location` here is necessary, so that it gets instantiated early
inject(function($compile, $location, $rootScope, $timeout) {
var elem = $compile('<async-view></async-view>')($rootScope);
$rootScope.$digest();
$timeout.flush(500);
expect(elem.text()).toBe('Hello, world!');
dealoc(elem);
})
);
});
});
describe('$routeParams', function() {
beforeEach(module('ngRoute'));
it('should publish the params into a service', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {});
$routeProvider.when('/bar/:barId', {});
});
inject(function($rootScope, $route, $location, $routeParams) {
$location.path('/foo').search('a=b');
$rootScope.$digest();
expect($routeParams).toEqual({a:'b'});
$location.path('/bar/123').search('x=abc');
$rootScope.$digest();
expect($routeParams).toEqual({barId:'123', x:'abc'});
});
});
it('should correctly extract the params when a param name is part of the route', function() {
module(function($routeProvider) {
$routeProvider.when('/bar/:foo/:bar', {});
});
inject(function($rootScope, $route, $location, $routeParams) {
$location.path('/bar/foovalue/barvalue');
$rootScope.$digest();
expect($routeParams).toEqual({bar:'barvalue', foo:'foovalue'});
});
});
it('should support route params not preceded by slashes', function() {
module(function($routeProvider) {
$routeProvider.when('/bar:barId/foo:fooId/', {});
});
inject(function($rootScope, $route, $location, $routeParams) {
$location.path('/barbarvalue/foofoovalue/');
$rootScope.$digest();
expect($routeParams).toEqual({barId: 'barvalue', fooId: 'foovalue'});
});
});
it('should correctly extract the params when an optional param name is part of the route', function() {
module(function($routeProvider) {
$routeProvider.when('/bar/:foo?', {});
$routeProvider.when('/baz/:foo?/edit', {});
$routeProvider.when('/qux/:bar?/:baz?', {});
});
inject(function($rootScope, $route, $location, $routeParams) {
$location.path('/bar');
$rootScope.$digest();
expect($routeParams).toEqual({});
$location.path('/bar/fooValue');
$rootScope.$digest();
expect($routeParams).toEqual({foo: 'fooValue'});
$location.path('/baz/fooValue/edit');
$rootScope.$digest();
expect($routeParams).toEqual({foo: 'fooValue'});
$location.path('/baz/edit');
$rootScope.$digest();
expect($routeParams).toEqual({});
$location.path('/qux//bazValue');
$rootScope.$digest();
expect($routeParams).toEqual({baz: 'bazValue'});
});
});
it('should correctly extract path params containing hashes and/or question marks', function() {
module(function($routeProvider) {
$routeProvider.when('/foo/:bar', {});
$routeProvider.when('/zoo/:bar/:baz/:qux', {});
});
inject(function($location, $rootScope, $routeParams) {
$location.path('/foo/bar?baz');
$rootScope.$digest();
expect($routeParams).toEqual({bar: 'bar?baz'});
$location.path('/foo/bar?baz=val');
$rootScope.$digest();
expect($routeParams).toEqual({bar: 'bar?baz=val'});
$location.path('/foo/bar#baz');
$rootScope.$digest();
expect($routeParams).toEqual({bar: 'bar#baz'});
$location.path('/foo/bar?baz#qux');
$rootScope.$digest();
expect($routeParams).toEqual({bar: 'bar?baz#qux'});
$location.path('/foo/bar?baz=val#qux');
$rootScope.$digest();
expect($routeParams).toEqual({bar: 'bar?baz=val#qux'});
$location.path('/foo/bar#baz?qux');
$rootScope.$digest();
expect($routeParams).toEqual({bar: 'bar#baz?qux'});
$location.path('/zoo/bar?p1=v1#h1/baz?p2=v2#h2/qux?p3=v3#h3');
$rootScope.$digest();
expect($routeParams).toEqual({
bar: 'bar?p1=v1#h1',
baz: 'baz?p2=v2#h2',
qux: 'qux?p3=v3#h3'
});
});
});
});
describe('$routeProvider', function() {
var $routeProvider;
beforeEach(module('ngRoute'));
beforeEach(module(function(_$routeProvider_) {
$routeProvider = _$routeProvider_;
$routeProvider.when('/foo', {template: 'Hello, world!'});
}));
it('should support enabling/disabling automatic instantiation upon initial load',
inject(function() {
expect($routeProvider.eagerInstantiationEnabled(true)).toBe($routeProvider);
expect($routeProvider.eagerInstantiationEnabled()).toBe(true);
expect($routeProvider.eagerInstantiationEnabled(false)).toBe($routeProvider);
expect($routeProvider.eagerInstantiationEnabled()).toBe(false);
expect($routeProvider.eagerInstantiationEnabled(true)).toBe($routeProvider);
expect($routeProvider.eagerInstantiationEnabled()).toBe(true);
})
);
it('should automatically instantiate `$route` upon initial load', function() {
inject(function($location, $rootScope) {
$location.path('/foo');
$rootScope.$digest();
});
inject(function($route) {
expect($route.current).toBeDefined();
});
});
it('should not automatically instantiate `$route` if disabled', function() {
module(function($routeProvider) {
$routeProvider.eagerInstantiationEnabled(false);
});
inject(function($location, $rootScope) {
$location.path('/foo');
$rootScope.$digest();
});
inject(function($route) {
expect($route.current).toBeUndefined();
});
});
});
describe('$route', function() {
var $httpBackend,
element;
beforeEach(module('ngRoute'));
beforeEach(module(function() {
return function(_$httpBackend_) {
$httpBackend = _$httpBackend_;
$httpBackend.when('GET', 'Chapter.html').respond('chapter');
$httpBackend.when('GET', 'test.html').respond('test');
$httpBackend.when('GET', 'foo.html').respond('foo');
$httpBackend.when('GET', 'bar.html').respond('bar');
$httpBackend.when('GET', 'baz.html').respond('baz');
$httpBackend.when('GET', 'http://example.com/trusted-template.html').respond('cross domain trusted template');
$httpBackend.when('GET', '404.html').respond('not found');
};
}));
afterEach(function() {
dealoc(element);
});
it('should allow cancellation via $locationChangeStart via $routeChangeStart', function() {
module(function($routeProvider) {
$routeProvider.when('/Edit', {
id: 'edit', template: 'Some edit functionality'
});
$routeProvider.when('/Home', {
id: 'home'
});
});
module(provideLog);
inject(function($route, $location, $rootScope, $compile, log) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (next.id === 'home' && current.scope.unsavedChanges) {
event.preventDefault();
}
});
element = $compile('<div><div ng-view></div></div>')($rootScope);
$rootScope.$apply(function() {
$location.path('/Edit');
});
$rootScope.$on('$routeChangeSuccess', log.fn('routeChangeSuccess'));
$rootScope.$on('$locationChangeSuccess', log.fn('locationChangeSuccess'));
// aborted route change
$rootScope.$apply(function() {
$route.current.scope.unsavedChanges = true;
});
$rootScope.$apply(function() {
$location.path('/Home');
});
expect($route.current.id).toBe('edit');
expect($location.path()).toBe('/Edit');
expect(log).toEqual([]);
// successful route change
$rootScope.$apply(function() {
$route.current.scope.unsavedChanges = false;
});
$rootScope.$apply(function() {
$location.path('/Home');
});
expect($route.current.id).toBe('home');
expect($location.path()).toBe('/Home');
expect(log).toEqual(['locationChangeSuccess', 'routeChangeSuccess']);
});
});
it('should allow redirects while handling $routeChangeStart', function() {
module(function($routeProvider) {
$routeProvider.when('/some', {
id: 'some', template: 'Some functionality'
});
$routeProvider.when('/redirect', {
id: 'redirect'
});
});
module(provideLog);
inject(function($route, $location, $rootScope, $compile, log) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (next.id === 'some') {
$location.path('/redirect');
}
});
$compile('<div><div ng-view></div></div>')($rootScope);
$rootScope.$on('$routeChangeStart', log.fn('routeChangeStart'));
$rootScope.$on('$routeChangeError', log.fn('routeChangeError'));
$rootScope.$on('$routeChangeSuccess', log.fn('routeChangeSuccess'));
$rootScope.$apply(function() {
$location.path('/some');
});
expect($route.current.id).toBe('redirect');
expect($location.path()).toBe('/redirect');
expect(log).toEqual(['routeChangeStart', 'routeChangeStart', 'routeChangeSuccess']);
});
});
it('should route and fire change event', function() {
var log = '',
lastRoute,
nextRoute;
module(function($routeProvider) {
$routeProvider.when('/Book/:book/Chapter/:chapter',
{controller: angular.noop, templateUrl: 'Chapter.html'});
$routeProvider.when('/Blank', {});
});
inject(function($route, $location, $rootScope) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
log += 'before();';
expect(current).toBe($route.current);
lastRoute = current;
nextRoute = next;
});
$rootScope.$on('$routeChangeSuccess', function(event, current, last) {
log += 'after();';
expect(current).toBe($route.current);
expect(lastRoute).toBe(last);
expect(nextRoute).toBe(current);
});
$location.path('/Book/Moby/Chapter/Intro').search('p=123');
$rootScope.$digest();
$httpBackend.flush();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', p:'123'});
log = '';
$location.path('/Blank').search('ignore');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({ignore:true});
log = '';
$location.path('/NONE');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current).toEqual(undefined);
});
});
it('should route and fire change event when catch-all params are used', function() {
var log = '',
lastRoute,
nextRoute;
module(function($routeProvider) {
$routeProvider.when('/Book1/:book/Chapter/:chapter/:highlight*/edit',
{controller: angular.noop, templateUrl: 'Chapter.html'});
$routeProvider.when('/Book2/:book/:highlight*/Chapter/:chapter',
{controller: angular.noop, templateUrl: 'Chapter.html'});
$routeProvider.when('/Blank', {});
});
inject(function($route, $location, $rootScope) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
log += 'before();';
expect(current).toBe($route.current);
lastRoute = current;
nextRoute = next;
});
$rootScope.$on('$routeChangeSuccess', function(event, current, last) {
log += 'after();';
expect(current).toBe($route.current);
expect(lastRoute).toBe(last);
expect(nextRoute).toBe(current);
});
$location.path('/Book1/Moby/Chapter/Intro/one/edit').search('p=123');
$rootScope.$digest();
$httpBackend.flush();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one', p:'123'});
log = '';
$location.path('/Blank').search('ignore');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({ignore:true});
log = '';
$location.path('/Book1/Moby/Chapter/Intro/one/two/edit').search('p=123');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one/two', p:'123'});
log = '';
$location.path('/Book2/Moby/one/two/Chapter/Intro').search('p=123');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one/two', p:'123'});
log = '';
$location.path('/NONE');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current).toEqual(undefined);
});
});
it('should route and fire change event correctly whenever the case insensitive flag is utilized', function() {
var log = '',
lastRoute,
nextRoute;
module(function($routeProvider) {
$routeProvider.when('/Book1/:book/Chapter/:chapter/:highlight*/edit',
{controller: angular.noop, templateUrl: 'Chapter.html', caseInsensitiveMatch: true});
$routeProvider.when('/Book2/:book/:highlight*/Chapter/:chapter',
{controller: angular.noop, templateUrl: 'Chapter.html'});
$routeProvider.when('/Blank', {});
});
inject(function($route, $location, $rootScope) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
log += 'before();';
expect(current).toBe($route.current);
lastRoute = current;
nextRoute = next;
});
$rootScope.$on('$routeChangeSuccess', function(event, current, last) {
log += 'after();';
expect(current).toBe($route.current);
expect(lastRoute).toBe(last);
expect(nextRoute).toBe(current);
});
$location.path('/Book1/Moby/Chapter/Intro/one/edit').search('p=123');
$rootScope.$digest();
$httpBackend.flush();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one', p:'123'});
log = '';
$location.path('/BOOK1/Moby/CHAPTER/Intro/one/EDIT').search('p=123');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one', p:'123'});
log = '';
$location.path('/Blank').search('ignore');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({ignore:true});
log = '';
$location.path('/BLANK');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current).toEqual(undefined);
log = '';
$location.path('/Book2/Moby/one/two/Chapter/Intro').search('p=123');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one/two', p:'123'});
log = '';
$location.path('/BOOK2/Moby/one/two/CHAPTER/Intro').search('p=123');
$rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current).toEqual(undefined);
});
});
it('should allow configuring caseInsensitiveMatch on the route provider level', function() {
module(function($routeProvider) {
$routeProvider.caseInsensitiveMatch = true;
$routeProvider.when('/Blank', {template: 'blank'});
$routeProvider.otherwise({template: 'other'});
});
inject(function($route, $location, $rootScope) {
$location.path('/bLaNk');
$rootScope.$digest();
expect($route.current.template).toBe('blank');
});
});
it('should allow overriding provider\'s caseInsensitiveMatch setting on the route level', function() {
module(function($routeProvider) {
$routeProvider.caseInsensitiveMatch = true;
$routeProvider.when('/Blank', {template: 'blank', caseInsensitiveMatch: false});
$routeProvider.otherwise({template: 'other'});
});
inject(function($route, $location, $rootScope) {
$location.path('/bLaNk');
$rootScope.$digest();
expect($route.current.template).toBe('other');
});
});
it('should not change route when location is canceled', function() {
module(function($routeProvider) {
$routeProvider.when('/somePath', {template: 'some path'});
});
inject(function($route, $location, $rootScope, $log) {
$rootScope.$on('$locationChangeStart', function(event) {
$log.info('$locationChangeStart');
event.preventDefault();
});
$rootScope.$on('$routeChangeSuccess', function(event) {
throw new Error('Should not get here');
});
$location.path('/somePath');
$rootScope.$digest();
expect($log.info.logs.shift()).toEqual(['$locationChangeStart']);
});
});
describe('should match a route that contains special chars in the path', function() {
beforeEach(module(function($routeProvider) {
$routeProvider.when('/$test.23/foo*(bar)/:baz', {templateUrl: 'test.html'});
}));
it('matches the full path', inject(function($route, $location, $rootScope) {
$location.path('/test');
$rootScope.$digest();
expect($route.current).toBeUndefined();
}));
it('matches literal .', inject(function($route, $location, $rootScope) {
$location.path('/$testX23/foo*(bar)/222');
$rootScope.$digest();
expect($route.current).toBeUndefined();
}));
it('matches literal *', inject(function($route, $location, $rootScope) {
$location.path('/$test.23/foooo(bar)/222');
$rootScope.$digest();
expect($route.current).toBeUndefined();
}));
it('treats backslashes normally', inject(function($route, $location, $rootScope) {
$location.path('/$test.23/foo*\\(bar)/222');
$rootScope.$digest();
expect($route.current).toBeUndefined();
}));
it('matches a URL with special chars', inject(function($route, $location, $rootScope) {
$location.path('/$test.23/foo*(bar)/~!@#$%^&*()_+=-`');
$rootScope.$digest();
expect($route.current).toBeDefined();
}));
it('should use route params inherited from prototype chain', function() {
function BaseRoute() {}
BaseRoute.prototype.templateUrl = 'foo.html';
module(function($routeProvider) {
$routeProvider.when('/foo', new BaseRoute());
});
inject(function($route, $location, $rootScope) {
$location.path('/foo');
$rootScope.$digest();
expect($route.current.templateUrl).toBe('foo.html');
});
});
});
describe('should match a route that contains optional params in the path', function() {
beforeEach(module(function($routeProvider) {
$routeProvider.when('/test/:opt?/:baz/edit', {templateUrl: 'test.html'});
}));
it('matches a URL with optional params', inject(function($route, $location, $rootScope) {
$location.path('/test/optValue/bazValue/edit');
$rootScope.$digest();
expect($route.current).toBeDefined();
}));
it('matches a URL without optional param', inject(function($route, $location, $rootScope) {
$location.path('/test//bazValue/edit');
$rootScope.$digest();
expect($route.current).toBeDefined();
}));
it('not match a URL with a required param', inject(function($route, $location, $rootScope) {
$location.path('///edit');
$rootScope.$digest();
expect($route.current).not.toBeDefined();
}));
});
it('should change route even when only search param changes', function() {
module(function($routeProvider) {
$routeProvider.when('/test', {templateUrl: 'test.html'});
});
inject(function($route, $location, $rootScope) {
var callback = jasmine.createSpy('onRouteChange');
$rootScope.$on('$routeChangeStart', callback);
$location.path('/test');
$rootScope.$digest();
callback.calls.reset();
$location.search({any: true});
$rootScope.$digest();
expect(callback).toHaveBeenCalled();
});
});
it('should allow routes to be defined with just templates without controllers', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'foo.html'});
});
inject(function($route, $location, $rootScope) {
var onChangeSpy = jasmine.createSpy('onChange');
$rootScope.$on('$routeChangeStart', onChangeSpy);
expect($route.current).toBeUndefined();
expect(onChangeSpy).not.toHaveBeenCalled();
$location.path('/foo');
$rootScope.$digest();
expect($route.current.templateUrl).toEqual('foo.html');
expect($route.current.controller).toBeUndefined();
expect(onChangeSpy).toHaveBeenCalled();
});
});
it('should chain whens and otherwise', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'foo.html'}).
otherwise({templateUrl: 'bar.html'}).
when('/baz', {templateUrl: 'baz.html'});
});
inject(function($route, $location, $rootScope) {
$rootScope.$digest();
expect($route.current.templateUrl).toBe('bar.html');
$location.url('/baz');
$rootScope.$digest();
expect($route.current.templateUrl).toBe('baz.html');
});
});
it('should skip routes with incomplete params', function() {
module(function($routeProvider) {
$routeProvider
.otherwise({template: 'other'})
.when('/pages/:page/:comment*', {template: 'comment'})
.when('/pages/:page', {template: 'page'})
.when('/pages', {template: 'index'})
.when('/foo/', {template: 'foo'})
.when('/foo/:bar', {template: 'bar'})
.when('/foo/:bar*/:baz', {template: 'baz'});
});
inject(function($route, $location, $rootScope) {
$location.url('/pages/');
$rootScope.$digest();
expect($route.current.template).toBe('index');
$location.url('/pages/page/');
$rootScope.$digest();
expect($route.current.template).toBe('page');
$location.url('/pages/page/1/');
$rootScope.$digest();
expect($route.current.template).toBe('comment');
$location.url('/foo/');
$rootScope.$digest();
expect($route.current.template).toBe('foo');
$location.url('/foo/bar/');
$rootScope.$digest();
expect($route.current.template).toBe('bar');
$location.url('/foo/bar/baz/');
$rootScope.$digest();
expect($route.current.template).toBe('baz');
$location.url('/something/');
$rootScope.$digest();
expect($route.current.template).toBe('other');
});
});
describe('otherwise', function() {
it('should handle unknown routes with "otherwise" route definition', function() {
function NotFoundCtrl() {}
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'foo.html'});
$routeProvider.otherwise({templateUrl: '404.html', controller: NotFoundCtrl});
});
inject(function($route, $location, $rootScope) {
var onChangeSpy = jasmine.createSpy('onChange');
$rootScope.$on('$routeChangeStart', onChangeSpy);
expect($route.current).toBeUndefined();
expect(onChangeSpy).not.toHaveBeenCalled();
$location.path('/unknownRoute');
$rootScope.$digest();
expect($route.current.templateUrl).toBe('404.html');
expect($route.current.controller).toBe(NotFoundCtrl);
expect(onChangeSpy).toHaveBeenCalled();
onChangeSpy.calls.reset();
$location.path('/foo');
$rootScope.$digest();
expect($route.current.templateUrl).toEqual('foo.html');
expect($route.current.controller).toBeUndefined();
expect(onChangeSpy).toHaveBeenCalled();
});
});
it('should update $route.current and $route.next when default route is matched', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'foo.html'});
$routeProvider.otherwise({templateUrl: '404.html'});
});
inject(function($route, $location, $rootScope) {
var currentRoute, nextRoute,
onChangeSpy = jasmine.createSpy('onChange').and.callFake(function(e, next) {
currentRoute = $route.current;
nextRoute = next;
});
// init
$rootScope.$on('$routeChangeStart', onChangeSpy);
expect($route.current).toBeUndefined();
expect(onChangeSpy).not.toHaveBeenCalled();
// match otherwise route
$location.path('/unknownRoute');
$rootScope.$digest();
expect(currentRoute).toBeUndefined();
expect(nextRoute.templateUrl).toBe('404.html');
expect($route.current.templateUrl).toBe('404.html');
expect(onChangeSpy).toHaveBeenCalled();
onChangeSpy.calls.reset();
// match regular route
$location.path('/foo');
$rootScope.$digest();
expect(currentRoute.templateUrl).toBe('404.html');
expect(nextRoute.templateUrl).toBe('foo.html');
expect($route.current.templateUrl).toEqual('foo.html');
expect(onChangeSpy).toHaveBeenCalled();
onChangeSpy.calls.reset();
// match otherwise route again
$location.path('/anotherUnknownRoute');
$rootScope.$digest();
expect(currentRoute.templateUrl).toBe('foo.html');
expect(nextRoute.templateUrl).toBe('404.html');
expect($route.current.templateUrl).toEqual('404.html');
expect(onChangeSpy).toHaveBeenCalled();
});
});
it('should interpret a string as a redirect route', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'foo.html'});
$routeProvider.when('/baz', {templateUrl: 'baz.html'});
$routeProvider.otherwise('/foo');
});
inject(function($route, $location, $rootScope) {
$location.path('/unknownRoute');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.templateUrl).toBe('foo.html');
});
});
});
describe('events', function() {
it('should not fire $routeChangeStart/Success during bootstrap (if no route)', function() {
var routeChangeSpy = jasmine.createSpy('route change');
module(function($routeProvider) {
$routeProvider.when('/one', {}); // no otherwise defined
});
inject(function($rootScope, $route, $location) {
$rootScope.$on('$routeChangeStart', routeChangeSpy);
$rootScope.$on('$routeChangeSuccess', routeChangeSpy);
$rootScope.$digest();
expect(routeChangeSpy).not.toHaveBeenCalled();
$location.path('/no-route-here');
$rootScope.$digest();
expect(routeChangeSpy).not.toHaveBeenCalled();
$location.path('/one');
$rootScope.$digest();
expect(routeChangeSpy).toHaveBeenCalled();
});
});
it('should fire $routeChangeStart and resolve promises', function() {
var deferA,
deferB;
module(function($provide, $routeProvider) {
$provide.factory('b', function($q) {
deferB = $q.defer();
return deferB.promise;
});
$routeProvider.when('/path', { templateUrl: 'foo.html', resolve: {
a: ['$q', function($q) {
deferA = $q.defer();
return deferA.promise;
}],
b: 'b'
} });
});
inject(function($location, $route, $rootScope, $httpBackend) {
var log = '';
$httpBackend.expectGET('foo.html').respond('FOO');
$location.path('/path');
$rootScope.$digest();
expect(log).toEqual('');
$httpBackend.flush();
expect(log).toEqual('');
deferA.resolve();
$rootScope.$digest();
expect(log).toEqual('');
deferB.resolve();
$rootScope.$digest();
expect($route.current.locals.$template).toEqual('FOO');
});
});
it('should fire $routeChangeError event on resolution error', function() {
var deferA;
module(function($provide, $routeProvider) {
$routeProvider.when('/path', { template: 'foo', resolve: {
a: function($q) {
deferA = $q.defer();
return deferA.promise;
}
} });
});
inject(function($location, $route, $rootScope) {
var log = '';
$rootScope.$on('$routeChangeStart', function() { log += 'before();'; });
$rootScope.$on('$routeChangeError', function(e, n, l, reason) { log += 'failed(' + reason + ');'; });
$location.path('/path');
$rootScope.$digest();
expect(log).toEqual('before();');
deferA.reject('MyError');
$rootScope.$digest();
expect(log).toEqual('before();failed(MyError);');
});
});
it('should fetch templates', function() {
module(function($routeProvider) {
$routeProvider.
when('/r1', { templateUrl: 'r1.html' }).
when('/r2', { templateUrl: 'r2.html' });
});
inject(function($route, $httpBackend, $location, $rootScope) {
var log = '';
$rootScope.$on('$routeChangeStart', function(e, next) { log += '$before(' + next.templateUrl + ');'; });
$rootScope.$on('$routeChangeSuccess', function(e, next) { log += '$after(' + next.templateUrl + ');'; });
$httpBackend.expectGET('r1.html').respond('R1');
$httpBackend.expectGET('r2.html').respond('R2');
$location.path('/r1');
$rootScope.$digest();
expect(log).toBe('$before(r1.html);');
$location.path('/r2');
$rootScope.$digest();
expect(log).toBe('$before(r1.html);$before(r2.html);');
$httpBackend.flush();
expect(log).toBe('$before(r1.html);$before(r2.html);$after(r2.html);');
expect(log).not.toContain('$after(r1.html);');
});
});
it('should NOT load cross domain templates by default', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', { templateUrl: 'http://example.com/foo.html' });
});
inject(function($route, $location, $rootScope) {
var onError = jasmine.createSpy('onError');
var onSuccess = jasmine.createSpy('onSuccess');
$rootScope.$on('$routeChangeError', onError);
$rootScope.$on('$routeChangeSuccess', onSuccess);
$location.path('/foo');
$rootScope.$digest();
expect(onSuccess).not.toHaveBeenCalled();
expect(onError).toHaveBeenCalled();
expect(onError.calls.mostRecent().args[3]).toEqualMinErr('$sce', 'insecurl',
'Blocked loading resource from url not allowed by $sceDelegate policy. ' +
'URL: http://example.com/foo.html');
});
});
it('should load cross domain templates that are trusted', function() {
module(function($routeProvider, $sceDelegateProvider) {
$routeProvider.when('/foo', { templateUrl: 'http://example.com/foo.html' });
$sceDelegateProvider.resourceUrlWhitelist([/^http:\/\/example\.com\/foo\.html$/]);
});
inject(function($route, $location, $rootScope) {
$httpBackend.whenGET('http://example.com/foo.html').respond('FOO BODY');
$location.path('/foo');
$rootScope.$digest();
$httpBackend.flush();
expect($route.current.locals.$template).toEqual('FOO BODY');
});
});
it('should not update $routeParams until $routeChangeSuccess', function() {
module(function($routeProvider) {
$routeProvider.
when('/r1/:id', { templateUrl: 'r1.html' }).
when('/r2/:id', { templateUrl: 'r2.html' });
});
inject(function($route, $httpBackend, $location, $rootScope, $routeParams) {
var log = '';
$rootScope.$on('$routeChangeStart', function(e, next) { log += '$before' + angular.toJson($routeParams) + ';'; });
$rootScope.$on('$routeChangeSuccess', function(e, next) { log += '$after' + angular.toJson($routeParams) + ';'; });
$httpBackend.whenGET('r1.html').respond('R1');
$httpBackend.whenGET('r2.html').respond('R2');
$location.path('/r1/1');
$rootScope.$digest();
expect(log).toBe('$before{};');
$httpBackend.flush();
expect(log).toBe('$before{};$after{"id":"1"};');
log = '';
$location.path('/r2/2');
$rootScope.$digest();
expect(log).toBe('$before{"id":"1"};');
$httpBackend.flush();
expect(log).toBe('$before{"id":"1"};$after{"id":"2"};');
});
});
it('should drop in progress route change when new route change occurs', function() {
module(function($routeProvider) {
$routeProvider.
when('/r1', { templateUrl: 'r1.html' }).
when('/r2', { templateUrl: 'r2.html' });
});
inject(function($route, $httpBackend, $location, $rootScope) {
var log = '';
$rootScope.$on('$routeChangeStart', function(e, next) { log += '$before(' + next.templateUrl + ');'; });
$rootScope.$on('$routeChangeSuccess', function(e, next) { log += '$after(' + next.templateUrl + ');'; });
$httpBackend.expectGET('r1.html').respond('R1');
$httpBackend.expectGET('r2.html').respond('R2');
$location.path('/r1');
$rootScope.$digest();
expect(log).toBe('$before(r1.html);');
$location.path('/r2');
$rootScope.$digest();
expect(log).toBe('$before(r1.html);$before(r2.html);');
$httpBackend.flush();
expect(log).toBe('$before(r1.html);$before(r2.html);$after(r2.html);');
expect(log).not.toContain('$after(r1.html);');
});
});
it('should throw an error when a template is not found', function() {
module(function($routeProvider, $exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
$routeProvider.
when('/r1', { templateUrl: 'r1.html' }).
when('/r2', { templateUrl: 'r2.html' }).
when('/r3', { templateUrl: 'r3.html' });
});
inject(function($route, $httpBackend, $location, $rootScope, $exceptionHandler) {
$httpBackend.expectGET('r1.html').respond(404, 'R1');
$location.path('/r1');
$rootScope.$digest();
$httpBackend.flush();
expect($exceptionHandler.errors.pop()).
toEqualMinErr('$templateRequest', 'tpload', 'Failed to load template: r1.html');
$httpBackend.expectGET('r2.html').respond('');
$location.path('/r2');
$rootScope.$digest();
$httpBackend.flush();
expect($exceptionHandler.errors.length).toBe(0);
$httpBackend.expectGET('r3.html').respond('abc');
$location.path('/r3');
$rootScope.$digest();
$httpBackend.flush();
expect($exceptionHandler.errors.length).toBe(0);
});
});
it('should catch local factory errors', function() {
var myError = new Error('MyError');
module(function($routeProvider) {
$routeProvider.when('/locals', {
resolve: {
a: function($q) {
throw myError;
}
}
});
});
inject(function($location, $route, $rootScope) {
spyOn($rootScope, '$broadcast').and.callThrough();
$location.path('/locals');
$rootScope.$digest();
expect($rootScope.$broadcast).toHaveBeenCalledWith(
'$routeChangeError', jasmine.any(Object), undefined, myError);
});
});
});
it('should match route with and without trailing slash', function() {
module(function($routeProvider) {
$routeProvider.when('/foo', {templateUrl: 'foo.html'});
$routeProvider.when('/bar/', {templateUrl: 'bar.html'});
});
inject(function($route, $location, $rootScope) {
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.templateUrl).toBe('foo.html');
$location.path('/foo/');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.templateUrl).toBe('foo.html');
$location.path('/bar');
$rootScope.$digest();
expect($location.path()).toBe('/bar/');
expect($route.current.templateUrl).toBe('bar.html');
$location.path('/bar/');
$rootScope.$digest();
expect($location.path()).toBe('/bar/');
expect($route.current.templateUrl).toBe('bar.html');
});
});
it('should not get affected by modifying the route definition object after route registration',
function() {
module(function($routeProvider) {
var rdo = {};
rdo.templateUrl = 'foo.html';
$routeProvider.when('/foo', rdo);
rdo.templateUrl = 'bar.html';
$routeProvider.when('/bar', rdo);
});
inject(function($location, $rootScope, $route) {
$location.path('/bar');
$rootScope.$digest();
expect($location.path()).toBe('/bar');
expect($route.current.templateUrl).toBe('bar.html');
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.templateUrl).toBe('foo.html');
});
}
);
it('should use the property values of the passed in route definition object directly',
function() {
var $routeProvider;
module(function(_$routeProvider_) {
$routeProvider = _$routeProvider_;
});
inject(function($location, $rootScope, $route, $sce) {
var sceWrappedUrl = $sce.trustAsResourceUrl('foo.html');
$routeProvider.when('/foo', {templateUrl: sceWrappedUrl});
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.templateUrl).toBe(sceWrappedUrl);
});
}
);
it('should support custom `$sce` implementations', function() {
function MySafeResourceUrl(val) {
var self = this;
this._val = val;
this.getVal = function() {
return (this !== self) ? null : this._val;
};
}
var $routeProvider;
module(function($provide, _$routeProvider_) {
$routeProvider = _$routeProvider_;
$provide.decorator('$sce', function($delegate) {
function getVal(v) { return v.getVal ? v.getVal() : v; }
$delegate.trustAsResourceUrl = function(url) { return new MySafeResourceUrl(url); };
$delegate.getTrustedResourceUrl = function(v) { return getVal(v); };
$delegate.valueOf = function(v) { return getVal(v); };
return $delegate;
});
});
inject(function($location, $rootScope, $route, $sce) {
$routeProvider.when('/foo', {templateUrl: $sce.trustAsResourceUrl('foo.html')});
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($sce.valueOf($route.current.templateUrl)).toBe('foo.html');
});
});
describe('redirection', function() {
describe('via `redirectTo`', function() {
it('should support redirection via redirectTo property by updating $location', function() {
module(function($routeProvider) {
$routeProvider.when('/', {redirectTo: '/foo'});
$routeProvider.when('/foo', {templateUrl: 'foo.html'});
$routeProvider.when('/bar', {templateUrl: 'bar.html'});
$routeProvider.when('/baz', {redirectTo: '/bar'});
$routeProvider.otherwise({templateUrl: '404.html'});
});
inject(function($route, $location, $rootScope) {
var onChangeSpy = jasmine.createSpy('onChange');
$rootScope.$on('$routeChangeStart', onChangeSpy);
expect($route.current).toBeUndefined();
expect(onChangeSpy).not.toHaveBeenCalled();
$location.path('/');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.templateUrl).toBe('foo.html');
expect(onChangeSpy).toHaveBeenCalledTimes(2);
onChangeSpy.calls.reset();
$location.path('/baz');
$rootScope.$digest();
expect($location.path()).toBe('/bar');
expect($route.current.templateUrl).toBe('bar.html');
expect(onChangeSpy).toHaveBeenCalledTimes(2);
});
});
it('should interpolate route vars in the redirected path from original path', function() {
module(function($routeProvider) {
$routeProvider.when('/foo/:id/foo/:subid/:extraId', {redirectTo: '/bar/:id/:subid/23'});
$routeProvider.when('/bar/:id/:subid/:subsubid', {templateUrl: 'bar.html'});
$routeProvider.when('/baz/:id/:path*', {redirectTo: '/path/:path/:id'});
$routeProvider.when('/path/:path*/:id', {templateUrl: 'foo.html'});
});
inject(function($route, $location, $rootScope) {
$location.path('/foo/id1/foo/subid3/gah');
$rootScope.$digest();
expect($location.path()).toEqual('/bar/id1/subid3/23');
expect($location.search()).toEqual({extraId: 'gah'});
expect($route.current.templateUrl).toEqual('bar.html');
$location.path('/baz/1/foovalue/barvalue');
$rootScope.$digest();
expect($location.path()).toEqual('/path/foovalue/barvalue/1');
expect($route.current.templateUrl).toEqual('foo.html');
});
});
it('should interpolate route vars in the redirected path from original search', function() {
module(function($routeProvider) {
$routeProvider.when('/bar/:id/:subid/:subsubid', {templateUrl: 'bar.html'});
$routeProvider.when('/foo/:id/:extra', {redirectTo: '/bar/:id/:subid/99'});
});
inject(function($route, $location, $rootScope) {
$location.path('/foo/id3/eId').search('subid=sid1&appended=true');
$rootScope.$digest();
expect($location.path()).toEqual('/bar/id3/sid1/99');
expect($location.search()).toEqual({appended: 'true', extra: 'eId'});
expect($route.current.templateUrl).toEqual('bar.html');
});
});
it('should properly process route params which are both eager and optional', function() {
module(function($routeProvider) {
$routeProvider.when('/foo/:param1*?/:param2', {templateUrl: 'foo.html'});
});
inject(function($location, $rootScope, $route) {
$location.path('/foo/bar1/bar2/bar3/baz');
$rootScope.$digest();
expect($location.path()).toEqual('/foo/bar1/bar2/bar3/baz');
expect($route.current.params.param1).toEqual('bar1/bar2/bar3');
expect($route.current.params.param2).toEqual('baz');
expect($route.current.templateUrl).toEqual('foo.html');
$location.path('/foo/baz');
$rootScope.$digest();
expect($location.path()).toEqual('/foo/baz');
expect($route.current.params.param1).toEqual(undefined);
expect($route.current.params.param2).toEqual('baz');
expect($route.current.templateUrl).toEqual('foo.html');
});
});
it('should properly interpolate optional and eager route vars ' +
'when redirecting from path with trailing slash', function() {
module(function($routeProvider) {
$routeProvider.when('/foo/:id?/:subid?', {templateUrl: 'foo.html'});
$routeProvider.when('/bar/:id*/:subid', {templateUrl: 'bar.html'});
});
inject(function($location, $rootScope, $route) {
$location.path('/foo/id1/subid2/');
$rootScope.$digest();
expect($location.path()).toEqual('/foo/id1/subid2');
expect($route.current.templateUrl).toEqual('foo.html');
$location.path('/bar/id1/extra/subid2/');
$rootScope.$digest();
expect($location.path()).toEqual('/bar/id1/extra/subid2');
expect($route.current.templateUrl).toEqual('bar.html');
});
});
it('should allow custom redirectTo function to be used', function() {
function customRedirectFn(routePathParams, path, search) {
expect(routePathParams).toEqual({id: 'id3'});
expect(path).toEqual('/foo/id3');
expect(search).toEqual({subid: 'sid1', appended: 'true'});
return '/custom';
}
module(function($routeProvider) {
$routeProvider.when('/foo/:id', {redirectTo: customRedirectFn});
});
inject(function($route, $location, $rootScope) {
$location.path('/foo/id3').search('subid=sid1&appended=true');
$rootScope.$digest();
expect($location.path()).toEqual('/custom');
});
});
it('should broadcast `$routeChangeError` when redirectTo throws', function() {
var error = new Error('Test');
module(function($routeProvider) {
$routeProvider.when('/foo', {redirectTo: function() { throw error; }});
});
inject(function($exceptionHandler, $location, $rootScope, $route) {
spyOn($rootScope, '$broadcast').and.callThrough();
$location.path('/foo');
$rootScope.$digest();
var lastCallArgs = $rootScope.$broadcast.calls.mostRecent().args;
expect(lastCallArgs[0]).toBe('$routeChangeError');
expect(lastCallArgs[3]).toBe(error);
});
});
it('should replace the url when redirecting', function() {
module(function($routeProvider) {
$routeProvider.when('/bar/:id', {templateUrl: 'bar.html'});
$routeProvider.when('/foo/:id/:extra', {redirectTo: '/bar/:id'});
});
inject(function($browser, $route, $location, $rootScope) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
$location.path('/foo/id3/eId');
$rootScope.$digest();
expect($location.path()).toEqual('/bar/id3');
expect($browserUrl.calls.mostRecent().args)
.toEqual(['http://server/#!/bar/id3?extra=eId', true, null]);
});
});
it('should not process route bits', function() {
var firstController = jasmine.createSpy('first controller spy');
var firstTemplate = jasmine.createSpy('first template spy').and.returnValue('redirected view');
var firstResolve = jasmine.createSpy('first resolve spy');
var secondController = jasmine.createSpy('second controller spy');
var secondTemplate = jasmine.createSpy('second template spy').and.returnValue('redirected view');
var secondResolve = jasmine.createSpy('second resolve spy');
module(function($routeProvider) {
$routeProvider.when('/redirect', {
template: firstTemplate,
redirectTo: '/redirected',
resolve: { value: firstResolve },
controller: firstController
});
$routeProvider.when('/redirected', {
template: secondTemplate,
resolve: { value: secondResolve },
controller: secondController
});
});
inject(function($route, $location, $rootScope, $compile) {
var element = $compile('<div><ng-view></ng-view></div>')($rootScope);
$location.path('/redirect');
$rootScope.$digest();
expect(firstController).not.toHaveBeenCalled();
expect(firstTemplate).not.toHaveBeenCalled();
expect(firstResolve).not.toHaveBeenCalled();
expect(secondController).toHaveBeenCalled();
expect(secondTemplate).toHaveBeenCalled();
expect(secondResolve).toHaveBeenCalled();
dealoc(element);
});
});
it('should not redirect transition if `redirectTo` returns `undefined`', function() {
var controller = jasmine.createSpy('first controller spy');
var templateFn = jasmine.createSpy('first template spy').and.returnValue('redirected view');
module(function($routeProvider) {
$routeProvider.when('/redirect/to/undefined', {
template: templateFn,
redirectTo: function() {},
controller: controller
});
});
inject(function($route, $location, $rootScope, $compile) {
var element = $compile('<div><ng-view></ng-view></div>')($rootScope);
$location.path('/redirect/to/undefined');
$rootScope.$digest();
expect(controller).toHaveBeenCalled();
expect(templateFn).toHaveBeenCalled();
expect($location.path()).toEqual('/redirect/to/undefined');
dealoc(element);
});
});
});
describe('via `resolveRedirectTo`', function() {
var $compile;
var $location;
var $rootScope;
var $route;
beforeEach(module(function() {
return function(_$compile_, _$location_, _$rootScope_, _$route_) {
$compile = _$compile_;
$location = _$location_;
$rootScope = _$rootScope_;
$route = _$route_;
};
}));
it('should be ignored if `redirectTo` is also present', function() {
var newUrl;
var getNewUrl = function() { return newUrl; };
var resolveRedirectToSpy = jasmine.createSpy('resolveRedirectTo').and.returnValue('/bar');
var redirectToSpy = jasmine.createSpy('redirectTo').and.callFake(getNewUrl);
var templateSpy = jasmine.createSpy('template').and.returnValue('Foo');
module(function($routeProvider) {
$routeProvider.
when('/foo', {
resolveRedirectTo: resolveRedirectToSpy,
redirectTo: redirectToSpy,
template: templateSpy
}).
when('/bar', {template: 'Bar'}).
when('/baz', {template: 'Baz'});
});
inject(function() {
newUrl = '/baz';
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/baz');
expect($route.current.template).toBe('Baz');
expect(resolveRedirectToSpy).not.toHaveBeenCalled();
expect(redirectToSpy).toHaveBeenCalled();
expect(templateSpy).not.toHaveBeenCalled();
redirectToSpy.calls.reset();
newUrl = undefined;
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.template).toBe(templateSpy);
expect(resolveRedirectToSpy).not.toHaveBeenCalled();
expect(redirectToSpy).toHaveBeenCalled();
expect(templateSpy).toHaveBeenCalled();
});
});
it('should redirect to the returned url', function() {
module(function($routeProvider) {
$routeProvider.
when('/foo', {resolveRedirectTo: function() { return '/bar?baz=qux'; }}).
when('/bar', {template: 'Bar'});
});
inject(function() {
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/bar');
expect($location.search()).toEqual({baz: 'qux'});
expect($route.current.template).toBe('Bar');
});
});
it('should support returning a promise', function() {
module(function($routeProvider) {
$routeProvider.
when('/foo', {resolveRedirectTo: function($q) { return $q.resolve('/bar'); }}).
when('/bar', {template: 'Bar'});
});
inject(function() {
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/bar');
expect($route.current.template).toBe('Bar');
});
});
it('should support dependency injection', function() {
module(function($provide, $routeProvider) {
$provide.value('nextRoute', '/bar');
$routeProvider.
when('/foo', {
resolveRedirectTo: function(nextRoute) {
return nextRoute;
}
});
});
inject(function() {
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/bar');
});
});
it('should have access to the current routeParams via `$route.current.params`', function() {
module(function($routeProvider) {
$routeProvider.
when('/foo/:bar/baz/:qux', {
resolveRedirectTo: function($route) {
expect($route.current.params).toEqual(jasmine.objectContaining({
bar: '1',
qux: '2'
}));
return '/passed';
}
});
});
inject(function() {
$location.path('/foo/1/baz/2').search({bar: 'qux'});
$rootScope.$digest();
expect($location.path()).toBe('/passed');
});
});
it('should not process route bits until the promise is resolved', function() {
var spies = createSpies();
var called = false;
var deferred;
module(function($routeProvider) {
setupRoutes($routeProvider, spies, function($q) {
called = true;
deferred = $q.defer();
return deferred.promise;
});
});
inject(function() {
var element = $compile('<div><ng-view></ng-view></div>')($rootScope);
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect(called).toBe(true);
expect(spies.fooResolveSpy).not.toHaveBeenCalled();
expect(spies.fooTemplateSpy).not.toHaveBeenCalled();
expect(spies.fooControllerSpy).not.toHaveBeenCalled();
expect(spies.barResolveSpy).not.toHaveBeenCalled();
expect(spies.barTemplateSpy).not.toHaveBeenCalled();
expect(spies.barControllerSpy).not.toHaveBeenCalled();
deferred.resolve('/bar');
$rootScope.$digest();
expect($location.path()).toBe('/bar');
expect(spies.fooResolveSpy).not.toHaveBeenCalled();
expect(spies.fooTemplateSpy).not.toHaveBeenCalled();
expect(spies.fooControllerSpy).not.toHaveBeenCalled();
expect(spies.barResolveSpy).toHaveBeenCalled();
expect(spies.barTemplateSpy).toHaveBeenCalled();
expect(spies.barControllerSpy).toHaveBeenCalled();
dealoc(element);
});
});
it('should not redirect if `undefined` is returned', function() {
var spies = createSpies();
var called = false;
module(function($routeProvider) {
setupRoutes($routeProvider, spies, function() {
called = true;
return undefined;
});
});
inject(function() {
var element = $compile('<div><ng-view></ng-view></div>')($rootScope);
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect(called).toBe(true);
expect(spies.fooResolveSpy).toHaveBeenCalled();
expect(spies.fooTemplateSpy).toHaveBeenCalled();
expect(spies.fooControllerSpy).toHaveBeenCalled();
expect(spies.barResolveSpy).not.toHaveBeenCalled();
expect(spies.barTemplateSpy).not.toHaveBeenCalled();
expect(spies.barControllerSpy).not.toHaveBeenCalled();
dealoc(element);
});
});
it('should not redirect if the returned promise resolves to `undefined`', function() {
var spies = createSpies();
var called = false;
module(function($routeProvider) {
setupRoutes($routeProvider, spies, function($q) {
called = true;
return $q.resolve(undefined);
});
});
inject(function() {
var element = $compile('<div><ng-view></ng-view></div>')($rootScope);
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect(called).toBe(true);
expect(spies.fooResolveSpy).toHaveBeenCalled();
expect(spies.fooTemplateSpy).toHaveBeenCalled();
expect(spies.fooControllerSpy).toHaveBeenCalled();
expect(spies.barResolveSpy).not.toHaveBeenCalled();
expect(spies.barTemplateSpy).not.toHaveBeenCalled();
expect(spies.barControllerSpy).not.toHaveBeenCalled();
dealoc(element);
});
});
it('should not redirect if the returned promise gets rejected', function() {
var spies = createSpies();
var called = false;
module(function($routeProvider) {
setupRoutes($routeProvider, spies, function($q) {
called = true;
return $q.reject('');
});
});
inject(function() {
spyOn($rootScope, '$broadcast').and.callThrough();
var element = $compile('<div><ng-view></ng-view></div>')($rootScope);
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect(called).toBe(true);
expect(spies.fooResolveSpy).not.toHaveBeenCalled();
expect(spies.fooTemplateSpy).not.toHaveBeenCalled();
expect(spies.fooControllerSpy).not.toHaveBeenCalled();
expect(spies.barResolveSpy).not.toHaveBeenCalled();
expect(spies.barTemplateSpy).not.toHaveBeenCalled();
expect(spies.barControllerSpy).not.toHaveBeenCalled();
var lastCallArgs = $rootScope.$broadcast.calls.mostRecent().args;
expect(lastCallArgs[0]).toBe('$routeChangeError');
dealoc(element);
});
});
it('should ignore previous redirection if newer transition happened', function() {
var spies = createSpies();
var called = false;
var deferred;
module(function($routeProvider) {
setupRoutes($routeProvider, spies, function($q) {
called = true;
deferred = $q.defer();
return deferred.promise;
});
});
inject(function() {
spyOn($location, 'url').and.callThrough();
var element = $compile('<div><ng-view></ng-view></div>')($rootScope);
$location.path('/foo');
$rootScope.$digest();
expect($location.path()).toBe('/foo');
expect(called).toBe(true);
expect(spies.fooResolveSpy).not.toHaveBeenCalled();
expect(spies.fooTemplateSpy).not.toHaveBeenCalled();
expect(spies.fooControllerSpy).not.toHaveBeenCalled();
expect(spies.barResolveSpy).not.toHaveBeenCalled();
expect(spies.barTemplateSpy).not.toHaveBeenCalled();
expect(spies.barControllerSpy).not.toHaveBeenCalled();
expect(spies.bazResolveSpy).not.toHaveBeenCalled();
expect(spies.bazTemplateSpy).not.toHaveBeenCalled();
expect(spies.bazControllerSpy).not.toHaveBeenCalled();
$location.path('/baz');
$rootScope.$digest();
expect($location.path()).toBe('/baz');
expect(spies.fooResolveSpy).not.toHaveBeenCalled();
expect(spies.fooTemplateSpy).not.toHaveBeenCalled();
expect(spies.fooControllerSpy).not.toHaveBeenCalled();
expect(spies.barResolveSpy).not.toHaveBeenCalled();
expect(spies.barTemplateSpy).not.toHaveBeenCalled();
expect(spies.barControllerSpy).not.toHaveBeenCalled();
expect(spies.bazResolveSpy).toHaveBeenCalledOnce();
expect(spies.bazTemplateSpy).toHaveBeenCalledOnce();
expect(spies.bazControllerSpy).toHaveBeenCalledOnce();
deferred.resolve();
$rootScope.$digest();
expect($location.path()).toBe('/baz');
expect(spies.fooResolveSpy).not.toHaveBeenCalled();
expect(spies.fooTemplateSpy).not.toHaveBeenCalled();
expect(spies.fooControllerSpy).not.toHaveBeenCalled();
expect(spies.barResolveSpy).not.toHaveBeenCalled();
expect(spies.barTemplateSpy).not.toHaveBeenCalled();
expect(spies.barControllerSpy).not.toHaveBeenCalled();
expect(spies.bazResolveSpy).toHaveBeenCalledOnce();
expect(spies.bazTemplateSpy).toHaveBeenCalledOnce();
expect(spies.bazControllerSpy).toHaveBeenCalledOnce();
dealoc(element);
});
});
// Helpers
function createSpies() {
return {
fooResolveSpy: jasmine.createSpy('fooResolve'),
fooTemplateSpy: jasmine.createSpy('fooTemplate').and.returnValue('Foo'),
fooControllerSpy: jasmine.createSpy('fooController'),
barResolveSpy: jasmine.createSpy('barResolve'),
barTemplateSpy: jasmine.createSpy('barTemplate').and.returnValue('Bar'),
barControllerSpy: jasmine.createSpy('barController'),
bazResolveSpy: jasmine.createSpy('bazResolve'),
bazTemplateSpy: jasmine.createSpy('bazTemplate').and.returnValue('Baz'),
bazControllerSpy: jasmine.createSpy('bazController')
};
}
function setupRoutes(routeProvider, spies, resolveRedirectToFn) {
routeProvider.
when('/foo', {
resolveRedirectTo: resolveRedirectToFn,
resolve: {_: spies.fooResolveSpy},
template: spies.fooTemplateSpy,
controller: spies.fooControllerSpy
}).
when('/bar', {
resolve: {_: spies.barResolveSpy},
template: spies.barTemplateSpy,
controller: spies.barControllerSpy
}).
when('/baz', {
resolve: {_: spies.bazResolveSpy},
template: spies.bazTemplateSpy,
controller: spies.bazControllerSpy
});
}
});
});
describe('reloadOnUrl', function() {
it('should reload when `reloadOnUrl` is true and `.url()` changes', function() {
var routeChange = jasmine.createSpy('routeChange');
module(function($routeProvider) {
$routeProvider.when('/path/:param', {});
});
inject(function($location, $rootScope, $routeParams) {
$rootScope.$on('$routeChangeStart', routeChange);
// Initial load
$location.path('/path/foo');
$rootScope.$digest();
expect(routeChange).toHaveBeenCalledOnce();
expect($routeParams).toEqual({param: 'foo'});
routeChange.calls.reset();
// Reload on `path` change
$location.path('/path/bar');
$rootScope.$digest();
expect(routeChange).toHaveBeenCalledOnce();
expect($routeParams).toEqual({param: 'bar'});
routeChange.calls.reset();
// Reload on `search` change
$location.search('foo', 'bar');
$rootScope.$digest();
expect(routeChange).toHaveBeenCalledOnce();
expect($routeParams).toEqual({param: 'bar', foo: 'bar'});
routeChange.calls.reset();
// Reload on `hash` change
$location.hash('baz');
$rootScope.$digest();
expect(routeChange).toHaveBeenCalledOnce();
expect($routeParams).toEqual({param: 'bar', foo: 'bar'});
});
});
it('should reload when `reloadOnUrl` is false and URL maps to different route',
function() {
var routeChange = jasmine.createSpy('routeChange');
var routeUpdate = jasmine.createSpy('routeUpdate');
module(function($routeProvider) {
$routeProvider.
when('/path/:param', {reloadOnUrl: false}).
otherwise({});
});
inject(function($location, $rootScope, $routeParams) {
$rootScope.$on('$routeChangeStart', routeChange);
$rootScope.$on('$routeChangeSuccess', routeChange);
$rootScope.$on('$routeUpdate', routeUpdate);
expect(routeChange).not.toHaveBeenCalled();
// Initial load
$location.path('/path/foo');
$rootScope.$digest();
expect(routeChange).toHaveBeenCalledTimes(2);
expect(routeUpdate).not.toHaveBeenCalled();
expect($routeParams).toEqual({param: 'foo'});
routeChange.calls.reset();
// Route change
$location.path('/other/path/bar');
$rootScope.$digest();
expect(routeChange).toHaveBeenCalledTimes(2);
expect(routeUpdate).not.toHaveBeenCalled();
expect($routeParams).toEqual({});
});
}
);
it('should not reload when `reloadOnUrl` is false and URL maps to the same route',
function() {
var routeChange = jasmine.createSpy('routeChange');
var routeUpdate = jasmine.createSpy('routeUpdate');
module(function($routeProvider) {
$routeProvider.when('/path/:param', {reloadOnUrl: false});
});
inject(function($location, $rootScope, $routeParams) {
$rootScope.$on('$routeChangeStart', routeChange);
$rootScope.$on('$routeChangeSuccess', routeChange);
$rootScope.$on('$routeUpdate', routeUpdate);
expect(routeChange).not.toHaveBeenCalled();
// Initial load
$location.path('/path/foo');
$rootScope.$digest();
expect(routeChange).toHaveBeenCalledTimes(2);
expect(routeUpdate).not.toHaveBeenCalled();
expect($routeParams).toEqual({param: 'foo'});
routeChange.calls.reset();
// Route update (no reload)
$location.path('/path/bar').search('foo', 'bar').hash('baz');
$rootScope.$digest();
expect(routeChange).not.toHaveBeenCalled();
expect(routeUpdate).toHaveBeenCalledOnce();
expect($routeParams).toEqual({param: 'bar', foo: 'bar'});
});
}
);
it('should update `$routeParams` even when not reloading a route', function() {
var routeChange = jasmine.createSpy('routeChange');
module(function($routeProvider) {
$routeProvider.when('/path/:param', {reloadOnUrl: false});
});
inject(function($location, $rootScope, $routeParams) {
$rootScope.$on('$routeChangeStart', routeChange);
$rootScope.$on('$routeChangeSuccess', routeChange);
expect(routeChange).not.toHaveBeenCalled();
// Initial load
$location.path('/path/foo');
$rootScope.$digest();
expect(routeChange).toHaveBeenCalledTimes(2);
expect($routeParams).toEqual({param: 'foo'});
routeChange.calls.reset();
// Route update (no reload)
$location.path('/path/bar');
$rootScope.$digest();
expect(routeChange).not.toHaveBeenCalled();
expect($routeParams).toEqual({param: 'bar'});
});
});
describe('with `$route.reload()`', function() {
var $location;
var $log;
var $rootScope;
var $route;
var routeChangeStart;
var routeChangeSuccess;
beforeEach(module(function($routeProvider) {
$routeProvider.when('/path/:param', {
template: '',
reloadOnUrl: false,
controller: function Controller($log) {
$log.debug('initialized');
}
});
}));
beforeEach(inject(function($compile, _$location_, _$log_, _$rootScope_, _$route_) {
$location = _$location_;
$log = _$log_;
$rootScope = _$rootScope_;
$route = _$route_;
routeChangeStart = jasmine.createSpy('routeChangeStart');
routeChangeSuccess = jasmine.createSpy('routeChangeSuccess');
$rootScope.$on('$routeChangeStart', routeChangeStart);
$rootScope.$on('$routeChangeSuccess', routeChangeSuccess);
element = $compile('<div><ng-view></ng-view></div>')($rootScope);
}));
it('should reload the current route', function() {
$location.path('/path/foo');
$rootScope.$digest();
expect($location.path()).toBe('/path/foo');
expect(routeChangeStart).toHaveBeenCalledOnce();
expect(routeChangeSuccess).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
routeChangeStart.calls.reset();
routeChangeSuccess.calls.reset();
$log.reset();
$route.reload();
$rootScope.$digest();
expect($location.path()).toBe('/path/foo');
expect(routeChangeStart).toHaveBeenCalledOnce();
expect(routeChangeSuccess).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
$log.reset();
});
it('should support preventing a route reload', function() {
$location.path('/path/foo');
$rootScope.$digest();
expect($location.path()).toBe('/path/foo');
expect(routeChangeStart).toHaveBeenCalledOnce();
expect(routeChangeSuccess).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
routeChangeStart.calls.reset();
routeChangeSuccess.calls.reset();
$log.reset();
routeChangeStart.and.callFake(function(evt) { evt.preventDefault(); });
$route.reload();
$rootScope.$digest();
expect($location.path()).toBe('/path/foo');
expect(routeChangeStart).toHaveBeenCalledOnce();
expect(routeChangeSuccess).not.toHaveBeenCalled();
expect($log.debug.logs).toEqual([]);
});
it('should reload the current route even if `reloadOnUrl` is disabled',
inject(function($routeParams) {
$location.path('/path/foo');
$rootScope.$digest();
expect(routeChangeStart).toHaveBeenCalledOnce();
expect(routeChangeSuccess).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
expect($routeParams).toEqual({param: 'foo'});
routeChangeStart.calls.reset();
routeChangeSuccess.calls.reset();
$log.reset();
$location.path('/path/bar');
$rootScope.$digest();
expect(routeChangeStart).not.toHaveBeenCalled();
expect(routeChangeSuccess).not.toHaveBeenCalled();
expect($log.debug.logs).toEqual([]);
expect($routeParams).toEqual({param: 'bar'});
$route.reload();
$rootScope.$digest();
expect(routeChangeStart).toHaveBeenCalledOnce();
expect(routeChangeSuccess).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
expect($routeParams).toEqual({param: 'bar'});
$log.reset();
})
);
});
});
describe('reloadOnSearch', function() {
it('should not have any effect if `reloadOnUrl` is false', function() {
var reloaded = jasmine.createSpy('route reload');
module(function($routeProvider) {
$routeProvider.when('/foo', {
reloadOnUrl: false,
reloadOnSearch: true
});
});
inject(function($route, $location, $rootScope, $routeParams) {
$rootScope.$on('$routeChangeStart', reloaded);
$location.path('/foo');
$rootScope.$digest();
expect(reloaded).toHaveBeenCalledOnce();
expect($routeParams).toEqual({});
reloaded.calls.reset();
// trigger reload (via .search())
$location.search({foo: 'bar'});
$rootScope.$digest();
expect(reloaded).not.toHaveBeenCalled();
expect($routeParams).toEqual({foo: 'bar'});
// trigger reload (via .hash())
$location.hash('baz');
$rootScope.$digest();
expect(reloaded).not.toHaveBeenCalled();
expect($routeParams).toEqual({foo: 'bar'});
});
});
it('should reload when `reloadOnSearch` is true and `.search()`/`.hash()` changes',
function() {
var reloaded = jasmine.createSpy('route reload');
module(function($routeProvider) {
$routeProvider.when('/foo', {controller: angular.noop});
});
inject(function($route, $location, $rootScope, $routeParams) {
$rootScope.$on('$routeChangeStart', reloaded);
$location.path('/foo');
$rootScope.$digest();
expect(reloaded).toHaveBeenCalledOnce();
expect($routeParams).toEqual({});
reloaded.calls.reset();
// trigger reload (via .search())
$location.search({foo: 'bar'});
$rootScope.$digest();
expect(reloaded).toHaveBeenCalledOnce();
expect($routeParams).toEqual({foo: 'bar'});
reloaded.calls.reset();
// trigger reload (via .hash())
$location.hash('baz');
$rootScope.$digest();
expect(reloaded).toHaveBeenCalledOnce();
expect($routeParams).toEqual({foo: 'bar'});
});
}
);
it('should not reload when `reloadOnSearch` is false and `.search()`/`.hash()` changes',
function() {
var routeChange = jasmine.createSpy('route change'),
routeUpdate = jasmine.createSpy('route update');
module(function($routeProvider) {
$routeProvider.when('/foo', {controller: angular.noop, reloadOnSearch: false});
});
inject(function($route, $location, $rootScope) {
$rootScope.$on('$routeChangeStart', routeChange);
$rootScope.$on('$routeChangeSuccess', routeChange);
$rootScope.$on('$routeUpdate', routeUpdate);
expect(routeChange).not.toHaveBeenCalled();
$location.path('/foo');
$rootScope.$digest();
expect(routeChange).toHaveBeenCalledTimes(2);
expect(routeUpdate).not.toHaveBeenCalled();
routeChange.calls.reset();
// don't trigger reload (via .search())
$location.search({foo: 'bar'});
$rootScope.$digest();
expect(routeChange).not.toHaveBeenCalled();
expect(routeUpdate).toHaveBeenCalledOnce();
routeUpdate.calls.reset();
// don't trigger reload (via .hash())
$location.hash('baz');
$rootScope.$digest();
expect(routeChange).not.toHaveBeenCalled();
expect(routeUpdate).toHaveBeenCalled();
});
}
);
it('should reload when `reloadOnSearch` is false and url differs only in route path param',
function() {
var routeChange = jasmine.createSpy('route change');
module(function($routeProvider) {
$routeProvider.when('/foo/:fooId', {controller: angular.noop, reloadOnSearch: false});
});
inject(function($route, $location, $rootScope) {
$rootScope.$on('$routeChangeStart', routeChange);
$rootScope.$on('$routeChangeSuccess', routeChange);
expect(routeChange).not.toHaveBeenCalled();
$location.path('/foo/aaa');
$rootScope.$digest();
expect(routeChange).toHaveBeenCalledTimes(2);
routeChange.calls.reset();
$location.path('/foo/bbb');
$rootScope.$digest();
expect(routeChange).toHaveBeenCalledTimes(2);
routeChange.calls.reset();
$location.search({foo: 'bar'}).hash('baz');
$rootScope.$digest();
expect(routeChange).not.toHaveBeenCalled();
});
}
);
it('should update params when `reloadOnSearch` is false and `.search()` changes', function() {
var routeParamsWatcher = jasmine.createSpy('routeParamsWatcher');
module(function($routeProvider) {
$routeProvider.when('/foo', {controller: angular.noop});
$routeProvider.when('/bar/:barId', {controller: angular.noop, reloadOnSearch: false});
});
inject(function($route, $location, $rootScope, $routeParams) {
$rootScope.$watch(function() {
return $routeParams;
}, function(value) {
routeParamsWatcher(value);
}, true);
expect(routeParamsWatcher).not.toHaveBeenCalled();
$location.path('/foo');
$rootScope.$digest();
expect(routeParamsWatcher).toHaveBeenCalledWith({});
routeParamsWatcher.calls.reset();
// trigger reload
$location.search({foo: 'bar'});
$rootScope.$digest();
expect(routeParamsWatcher).toHaveBeenCalledWith({foo: 'bar'});
routeParamsWatcher.calls.reset();
$location.path('/bar/123').search({});
$rootScope.$digest();
expect(routeParamsWatcher).toHaveBeenCalledWith({barId: '123'});
routeParamsWatcher.calls.reset();
// don't trigger reload
$location.search({foo: 'bar'});
$rootScope.$digest();
expect(routeParamsWatcher).toHaveBeenCalledWith({barId: '123', foo: 'bar'});
});
});
it('should allow using a function as a template', function() {
var customTemplateWatcher = jasmine.createSpy('customTemplateWatcher');
function customTemplateFn(routePathParams) {
customTemplateWatcher(routePathParams);
expect(routePathParams).toEqual({id: 'id3'});
return '<h1>' + routePathParams.id + '</h1>';
}
module(function($routeProvider) {
$routeProvider.when('/bar/:id/:subid/:subsubid', {templateUrl: 'bar.html'});
$routeProvider.when('/foo/:id', {template: customTemplateFn});
});
inject(function($route, $location, $rootScope) {
$location.path('/foo/id3');
$rootScope.$digest();
expect(customTemplateWatcher).toHaveBeenCalledWith({id: 'id3'});
});
});
it('should allow using a function as a templateUrl', function() {
var customTemplateUrlWatcher = jasmine.createSpy('customTemplateUrlWatcher');
function customTemplateUrlFn(routePathParams) {
customTemplateUrlWatcher(routePathParams);
expect(routePathParams).toEqual({id: 'id3'});
return 'foo.html';
}
module(function($routeProvider) {
$routeProvider.when('/bar/:id/:subid/:subsubid', {templateUrl: 'bar.html'});
$routeProvider.when('/foo/:id', {templateUrl: customTemplateUrlFn});
});
inject(function($route, $location, $rootScope) {
$location.path('/foo/id3');
$rootScope.$digest();
expect(customTemplateUrlWatcher).toHaveBeenCalledWith({id: 'id3'});
expect($route.current.loadedTemplateUrl).toEqual('foo.html');
});
});
describe('with `$route.reload()`', function() {
var $location;
var $log;
var $rootScope;
var $route;
var routeChangeStartSpy;
var routeChangeSuccessSpy;
beforeEach(module(function($routeProvider) {
$routeProvider.when('/bar/:barId', {
template: '',
controller: controller,
reloadOnSearch: false
});
function controller($log) {
$log.debug('initialized');
}
}));
beforeEach(inject(function($compile, _$location_, _$log_, _$rootScope_, _$route_) {
$location = _$location_;
$log = _$log_;
$rootScope = _$rootScope_;
$route = _$route_;
routeChangeStartSpy = jasmine.createSpy('routeChangeStart');
routeChangeSuccessSpy = jasmine.createSpy('routeChangeSuccess');
$rootScope.$on('$routeChangeStart', routeChangeStartSpy);
$rootScope.$on('$routeChangeSuccess', routeChangeSuccessSpy);
element = $compile('<div><div ng-view></div></div>')($rootScope);
}));
it('should reload the current route', function() {
$location.path('/bar/123');
$rootScope.$digest();
expect($location.path()).toBe('/bar/123');
expect(routeChangeStartSpy).toHaveBeenCalledOnce();
expect(routeChangeSuccessSpy).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
routeChangeStartSpy.calls.reset();
routeChangeSuccessSpy.calls.reset();
$log.reset();
$route.reload();
$rootScope.$digest();
expect($location.path()).toBe('/bar/123');
expect(routeChangeStartSpy).toHaveBeenCalledOnce();
expect(routeChangeSuccessSpy).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
$log.reset();
});
it('should support preventing a route reload', function() {
$location.path('/bar/123');
$rootScope.$digest();
expect($location.path()).toBe('/bar/123');
expect(routeChangeStartSpy).toHaveBeenCalledOnce();
expect(routeChangeSuccessSpy).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
routeChangeStartSpy.calls.reset();
routeChangeSuccessSpy.calls.reset();
$log.reset();
routeChangeStartSpy.and.callFake(function(evt) { evt.preventDefault(); });
$route.reload();
$rootScope.$digest();
expect($location.path()).toBe('/bar/123');
expect(routeChangeStartSpy).toHaveBeenCalledOnce();
expect(routeChangeSuccessSpy).not.toHaveBeenCalled();
expect($log.debug.logs).toEqual([]);
});
it('should reload even if reloadOnSearch is false', inject(function($routeParams) {
$location.path('/bar/123');
$rootScope.$digest();
expect($routeParams).toEqual({barId: '123'});
expect(routeChangeSuccessSpy).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
routeChangeSuccessSpy.calls.reset();
$log.reset();
$location.search('a=b');
$rootScope.$digest();
expect($routeParams).toEqual({barId: '123', a: 'b'});
expect(routeChangeSuccessSpy).not.toHaveBeenCalled();
expect($log.debug.logs).toEqual([]);
routeChangeSuccessSpy.calls.reset();
$log.reset();
$location.hash('c');
$rootScope.$digest();
expect($routeParams).toEqual({barId: '123', a: 'b'});
expect(routeChangeSuccessSpy).not.toHaveBeenCalled();
expect($log.debug.logs).toEqual([]);
$route.reload();
$rootScope.$digest();
expect($routeParams).toEqual({barId: '123', a: 'b'});
expect(routeChangeSuccessSpy).toHaveBeenCalledOnce();
expect($log.debug.logs).toEqual([['initialized']]);
$log.reset();
}));
});
});
describe('update', function() {
it('should support single-parameter route updating', function() {
var routeChangeSpy = jasmine.createSpy('route change');
module(function($routeProvider) {
$routeProvider.when('/bar/:barId', {controller: angular.noop});
});
inject(function($route, $routeParams, $location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', routeChangeSpy);
$location.path('/bar/1');
$rootScope.$digest();
routeChangeSpy.calls.reset();
$route.updateParams({barId: '2'});
$rootScope.$digest();
expect($routeParams).toEqual({barId: '2'});
expect(routeChangeSpy).toHaveBeenCalledOnce();
expect($location.path()).toEqual('/bar/2');
});
});
it('should support total multi-parameter route updating', function() {
var routeChangeSpy = jasmine.createSpy('route change');
module(function($routeProvider) {
$routeProvider.when('/bar/:barId/:fooId/:spamId/:eggId', {controller: angular.noop});
});
inject(function($route, $routeParams, $location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', routeChangeSpy);
$location.path('/bar/1/2/3/4');
$rootScope.$digest();
routeChangeSpy.calls.reset();
$route.updateParams({barId: '5', fooId: '6', spamId: '7', eggId: '8'});
$rootScope.$digest();
expect($routeParams).toEqual({barId: '5', fooId: '6', spamId: '7', eggId: '8'});
expect(routeChangeSpy).toHaveBeenCalledOnce();
expect($location.path()).toEqual('/bar/5/6/7/8');
});
});
it('should support partial multi-parameter route updating', function() {
var routeChangeSpy = jasmine.createSpy('route change');
module(function($routeProvider) {
$routeProvider.when('/bar/:barId/:fooId/:spamId/:eggId', {controller: angular.noop});
});
inject(function($route, $routeParams, $location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', routeChangeSpy);
$location.path('/bar/1/2/3/4');
$rootScope.$digest();
routeChangeSpy.calls.reset();
$route.updateParams({barId: '5', fooId: '6'});
$rootScope.$digest();
expect($routeParams).toEqual({barId: '5', fooId: '6', spamId: '3', eggId: '4'});
expect(routeChangeSpy).toHaveBeenCalledOnce();
expect($location.path()).toEqual('/bar/5/6/3/4');
});
});
it('should update query params when new properties are not in path', function() {
var routeChangeSpy = jasmine.createSpy('route change');
module(function($routeProvider) {
$routeProvider.when('/bar/:barId/:fooId/:spamId/', {controller: angular.noop});
});
inject(function($route, $routeParams, $location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', routeChangeSpy);
$location.path('/bar/1/2/3');
$location.search({initial: 'true'});
$rootScope.$digest();
routeChangeSpy.calls.reset();
$route.updateParams({barId: '5', fooId: '6', eggId: '4'});
$rootScope.$digest();
expect($routeParams).toEqual({barId: '5', fooId: '6', spamId: '3', eggId: '4', initial: 'true'});
expect(routeChangeSpy).toHaveBeenCalledOnce();
expect($location.path()).toEqual('/bar/5/6/3/');
expect($location.search()).toEqual({eggId: '4', initial: 'true'});
});
});
it('should not update query params when an optional property was previously not in path', function() {
var routeChangeSpy = jasmine.createSpy('route change');
module(function($routeProvider) {
$routeProvider.when('/bar/:barId/:fooId/:spamId/:eggId?', {controller: angular.noop});
});
inject(function($route, $routeParams, $location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', routeChangeSpy);
$location.path('/bar/1/2/3');
$location.search({initial: 'true'});
$rootScope.$digest();
routeChangeSpy.calls.reset();
$route.updateParams({barId: '5', fooId: '6', eggId: '4'});
$rootScope.$digest();
expect($routeParams).toEqual({barId: '5', fooId: '6', spamId: '3', eggId: '4', initial: 'true'});
expect(routeChangeSpy).toHaveBeenCalledOnce();
expect($location.path()).toEqual('/bar/5/6/3/4');
expect($location.search()).toEqual({initial: 'true'});
});
});
it('should complain if called without an existing route', inject(function($route) {
expect(function() { $route.updateParams(); }).toThrowMinErr('ngRoute', 'norout');
}));
});
describe('testability', function() {
it('should wait for $resolve promises before calling callbacks', function() {
var deferred;
module(function($routeProvider) {
$routeProvider.when('/path', {
resolve: {
a: function($q) {
deferred = $q.defer();
return deferred.promise;
}
}
});
});
inject(function($browser, $location, $rootScope, $$testability) {
$location.path('/path');
$rootScope.$digest();
var callback = jasmine.createSpy('callback');
$$testability.whenStable(callback);
expect(callback).not.toHaveBeenCalled();
deferred.resolve();
$browser.defer.flush();
expect(callback).toHaveBeenCalled();
});
});
it('should call callback after $resolve promises are rejected', function() {
var deferred;
module(function($routeProvider) {
$routeProvider.when('/path', {
resolve: {
a: function($q) {
deferred = $q.defer();
return deferred.promise;
}
}
});
});
inject(function($browser, $location, $rootScope, $$testability) {
$location.path('/path');
$rootScope.$digest();
var callback = jasmine.createSpy('callback');
$$testability.whenStable(callback);
expect(callback).not.toHaveBeenCalled();
deferred.reject();
$browser.defer.flush();
expect(callback).toHaveBeenCalled();
});
});
it('should wait for resolveRedirectTo promises before calling callbacks', function() {
var deferred;
module(function($routeProvider) {
$routeProvider.when('/path', {
resolveRedirectTo: function($q) {
deferred = $q.defer();
return deferred.promise;
}
});
});
inject(function($browser, $location, $rootScope, $$testability) {
$location.path('/path');
$rootScope.$digest();
var callback = jasmine.createSpy('callback');
$$testability.whenStable(callback);
expect(callback).not.toHaveBeenCalled();
deferred.resolve();
$browser.defer.flush();
expect(callback).toHaveBeenCalled();
});
});
it('should call callback after resolveRedirectTo promises are rejected', function() {
var deferred;
module(function($routeProvider) {
$routeProvider.when('/path', {
resolveRedirectTo: function($q) {
deferred = $q.defer();
return deferred.promise;
}
});
});
inject(function($browser, $location, $rootScope, $$testability) {
$location.path('/path');
$rootScope.$digest();
var callback = jasmine.createSpy('callback');
$$testability.whenStable(callback);
expect(callback).not.toHaveBeenCalled();
deferred.reject();
$browser.defer.flush();
expect(callback).toHaveBeenCalled();
});
});
it('should wait for all route promises before calling callbacks', function() {
var deferreds = {};
module(function($routeProvider) {
addRouteWithAsyncRedirect('/foo', '/bar');
addRouteWithAsyncRedirect('/bar', '/baz');
addRouteWithAsyncRedirect('/baz', '/qux');
$routeProvider.when('/qux', {
resolve: {
a: function($q) {
var deferred = deferreds['/qux'] = $q.defer();
return deferred.promise;
}
}
});
// Helpers
function addRouteWithAsyncRedirect(fromPath, toPath) {
$routeProvider.when(fromPath, {
resolveRedirectTo: function($q) {
var deferred = deferreds[fromPath] = $q.defer();
return deferred.promise.then(function() { return toPath; });
}
});
}
});
inject(function($browser, $location, $rootScope, $$testability) {
$location.path('/foo');
$rootScope.$digest();
var callback = jasmine.createSpy('callback');
$$testability.whenStable(callback);
expect(callback).not.toHaveBeenCalled();
deferreds['/foo'].resolve();
$browser.defer.flush();
expect(callback).not.toHaveBeenCalled();
deferreds['/bar'].resolve();
$browser.defer.flush();
expect(callback).not.toHaveBeenCalled();
deferreds['/baz'].resolve();
$browser.defer.flush();
expect(callback).not.toHaveBeenCalled();
deferreds['/qux'].resolve();
$browser.defer.flush();
expect(callback).toHaveBeenCalled();
});
});
});
});
})(window, window.angular);