1 /*eslint-disable no-unused-vars*/
3 * jQuery JavaScript Library v3.1.0
7 * https://sizzlejs.com/
9 * Copyright jQuery Foundation and other contributors
10 * Released under the MIT license
11 * https://jquery.org/license
13 * Date: 2016-07-07T21:44Z
15 ( function( global, factory ) {
17 if ( typeof module === "object" && typeof module.exports === "object" ) {
19 // For CommonJS and CommonJS-like environments where a proper `window`
20 // is present, execute the factory and get jQuery.
21 // For environments that do not have a `window` with a `document`
22 // (such as Node.js), expose a factory as module.exports.
23 // This accentuates the need for the creation of a real `window`.
24 // e.g. var jQuery = require("jquery")(window);
25 // See ticket #14549 for more info.
26 module.exports = global.document ?
27 factory( global, true ) :
30 throw new Error( "jQuery requires a window with a document" );
38 // Pass this if window is not defined yet
39 } )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
41 // Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
42 // throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
43 // arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
44 // enough that all such attempts are guarded in a try block.
48 var document = window.document;
50 var getProto = Object.getPrototypeOf;
52 var slice = arr.slice;
54 var concat = arr.concat;
58 var indexOf = arr.indexOf;
62 var toString = class2type.toString;
64 var hasOwn = class2type.hasOwnProperty;
66 var fnToString = hasOwn.toString;
68 var ObjectFunctionString = fnToString.call( Object );
74 function DOMEval( code, doc ) {
75 doc = doc || document;
77 var script = doc.createElement( "script" );
80 doc.head.appendChild( script ).parentNode.removeChild( script );
83 // Defining this global in .eslintrc would create a danger of using the global
84 // unguarded in another place, it seems safer to define global only for this module
91 // Define a local copy of jQuery
92 jQuery = function( selector, context ) {
94 // The jQuery object is actually just the init constructor 'enhanced'
95 // Need init if jQuery is called (just allow error to be thrown if not included)
96 return new jQuery.fn.init( selector, context );
99 // Support: Android <=4.0 only
100 // Make sure we trim BOM and NBSP
101 rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
103 // Matches dashed string for camelizing
105 rdashAlpha = /-([a-z])/g,
107 // Used by jQuery.camelCase as callback to replace()
108 fcamelCase = function( all, letter ) {
109 return letter.toUpperCase();
112 jQuery.fn = jQuery.prototype = {
114 // The current version of jQuery being used
119 // The default length of a jQuery object is 0
122 toArray: function() {
123 return slice.call( this );
126 // Get the Nth element in the matched element set OR
127 // Get the whole matched element set as a clean array
128 get: function( num ) {
131 // Return just the one element from the set
132 ( num < 0 ? this[ num + this.length ] : this[ num ] ) :
134 // Return all the elements in a clean array
138 // Take an array of elements and push it onto the stack
139 // (returning the new matched element set)
140 pushStack: function( elems ) {
142 // Build a new jQuery matched element set
143 var ret = jQuery.merge( this.constructor(), elems );
145 // Add the old object onto the stack (as a reference)
146 ret.prevObject = this;
148 // Return the newly-formed element set
152 // Execute a callback for every element in the matched set.
153 each: function( callback ) {
154 return jQuery.each( this, callback );
157 map: function( callback ) {
158 return this.pushStack( jQuery.map( this, function( elem, i ) {
159 return callback.call( elem, i, elem );
164 return this.pushStack( slice.apply( this, arguments ) );
172 return this.eq( -1 );
176 var len = this.length,
177 j = +i + ( i < 0 ? len : 0 );
178 return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
182 return this.prevObject || this.constructor();
185 // For internal use only.
186 // Behaves like an Array's method, not like a jQuery method.
192 jQuery.extend = jQuery.fn.extend = function() {
193 var options, name, src, copy, copyIsArray, clone,
194 target = arguments[ 0 ] || {},
196 length = arguments.length,
199 // Handle a deep copy situation
200 if ( typeof target === "boolean" ) {
203 // Skip the boolean and the target
204 target = arguments[ i ] || {};
208 // Handle case when target is a string or something (possible in deep copy)
209 if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
213 // Extend jQuery itself if only one argument is passed
214 if ( i === length ) {
219 for ( ; i < length; i++ ) {
221 // Only deal with non-null/undefined values
222 if ( ( options = arguments[ i ] ) != null ) {
224 // Extend the base object
225 for ( name in options ) {
226 src = target[ name ];
227 copy = options[ name ];
229 // Prevent never-ending loop
230 if ( target === copy ) {
234 // Recurse if we're merging plain objects or arrays
235 if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
236 ( copyIsArray = jQuery.isArray( copy ) ) ) ) {
240 clone = src && jQuery.isArray( src ) ? src : [];
243 clone = src && jQuery.isPlainObject( src ) ? src : {};
246 // Never move original objects, clone them
247 target[ name ] = jQuery.extend( deep, clone, copy );
249 // Don't bring in undefined values
250 } else if ( copy !== undefined ) {
251 target[ name ] = copy;
257 // Return the modified object
263 // Unique for each copy of jQuery on the page
264 expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
266 // Assume jQuery is ready without the ready module
269 error: function( msg ) {
270 throw new Error( msg );
275 isFunction: function( obj ) {
276 return jQuery.type( obj ) === "function";
279 isArray: Array.isArray,
281 isWindow: function( obj ) {
282 return obj != null && obj === obj.window;
285 isNumeric: function( obj ) {
287 // As of jQuery 3.0, isNumeric is limited to
288 // strings and numbers (primitives or objects)
289 // that can be coerced to finite numbers (gh-2662)
290 var type = jQuery.type( obj );
291 return ( type === "number" || type === "string" ) &&
293 // parseFloat NaNs numeric-cast false positives ("")
294 // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
295 // subtraction forces infinities to NaN
296 !isNaN( obj - parseFloat( obj ) );
299 isPlainObject: function( obj ) {
302 // Detect obvious negatives
303 // Use toString instead of jQuery.type to catch host objects
304 if ( !obj || toString.call( obj ) !== "[object Object]" ) {
308 proto = getProto( obj );
310 // Objects with no prototype (e.g., `Object.create( null )`) are plain
315 // Objects with prototype are plain iff they were constructed by a global Object function
316 Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
317 return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
320 isEmptyObject: function( obj ) {
322 /* eslint-disable no-unused-vars */
323 // See https://github.com/eslint/eslint/issues/6125
326 for ( name in obj ) {
332 type: function( obj ) {
337 // Support: Android <=2.3 only (functionish RegExp)
338 return typeof obj === "object" || typeof obj === "function" ?
339 class2type[ toString.call( obj ) ] || "object" :
343 // Evaluates a script in a global context
344 globalEval: function( code ) {
348 // Convert dashed to camelCase; used by the css and data modules
349 // Support: IE <=9 - 11, Edge 12 - 13
350 // Microsoft forgot to hump their vendor prefix (#9572)
351 camelCase: function( string ) {
352 return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
355 nodeName: function( elem, name ) {
356 return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
359 each: function( obj, callback ) {
362 if ( isArrayLike( obj ) ) {
364 for ( ; i < length; i++ ) {
365 if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
371 if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
380 // Support: Android <=4.0 only
381 trim: function( text ) {
382 return text == null ?
384 ( text + "" ).replace( rtrim, "" );
387 // results is for internal usage only
388 makeArray: function( arr, results ) {
389 var ret = results || [];
392 if ( isArrayLike( Object( arr ) ) ) {
394 typeof arr === "string" ?
398 push.call( ret, arr );
405 inArray: function( elem, arr, i ) {
406 return arr == null ? -1 : indexOf.call( arr, elem, i );
409 // Support: Android <=4.0 only, PhantomJS 1 only
410 // push.apply(_, arraylike) throws on ancient WebKit
411 merge: function( first, second ) {
412 var len = +second.length,
416 for ( ; j < len; j++ ) {
417 first[ i++ ] = second[ j ];
425 grep: function( elems, callback, invert ) {
429 length = elems.length,
430 callbackExpect = !invert;
432 // Go through the array, only saving the items
433 // that pass the validator function
434 for ( ; i < length; i++ ) {
435 callbackInverse = !callback( elems[ i ], i );
436 if ( callbackInverse !== callbackExpect ) {
437 matches.push( elems[ i ] );
444 // arg is for internal usage only
445 map: function( elems, callback, arg ) {
450 // Go through the array, translating each of the items to their new values
451 if ( isArrayLike( elems ) ) {
452 length = elems.length;
453 for ( ; i < length; i++ ) {
454 value = callback( elems[ i ], i, arg );
456 if ( value != null ) {
461 // Go through every key on the object,
464 value = callback( elems[ i ], i, arg );
466 if ( value != null ) {
472 // Flatten any nested arrays
473 return concat.apply( [], ret );
476 // A global GUID counter for objects
479 // Bind a function to a context, optionally partially applying any
481 proxy: function( fn, context ) {
482 var tmp, args, proxy;
484 if ( typeof context === "string" ) {
490 // Quick check to determine if target is callable, in the spec
491 // this throws a TypeError, but we will just return undefined.
492 if ( !jQuery.isFunction( fn ) ) {
497 args = slice.call( arguments, 2 );
499 return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
502 // Set the guid of unique handler to the same of original handler, so it can be removed
503 proxy.guid = fn.guid = fn.guid || jQuery.guid++;
510 // jQuery.support is not used in Core but other projects attach their
511 // properties to it so it needs to exist.
515 if ( typeof Symbol === "function" ) {
516 jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
519 // Populate the class2type map
520 jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
521 function( i, name ) {
522 class2type[ "[object " + name + "]" ] = name.toLowerCase();
525 function isArrayLike( obj ) {
527 // Support: real iOS 8.2 only (not reproducible in simulator)
528 // `in` check used to prevent JIT error (gh-2145)
529 // hasOwn isn't used here due to false negatives
530 // regarding Nodelist length in IE
531 var length = !!obj && "length" in obj && obj.length,
532 type = jQuery.type( obj );
534 if ( type === "function" || jQuery.isWindow( obj ) ) {
538 return type === "array" || length === 0 ||
539 typeof length === "number" && length > 0 && ( length - 1 ) in obj;
543 * Sizzle CSS Selector Engine v2.3.0
544 * https://sizzlejs.com/
546 * Copyright jQuery Foundation and other contributors
547 * Released under the MIT license
548 * http://jquery.org/license
552 (function( window ) {'use strict';
566 // Local document vars
576 // Instance-specific data
577 expando = "sizzle" + 1 * new Date(),
578 preferredDoc = window.document,
581 classCache = createCache(),
582 tokenCache = createCache(),
583 compilerCache = createCache(),
584 sortOrder = function( a, b ) {
592 hasOwn = ({}).hasOwnProperty,
595 push_native = arr.push,
598 // Use a stripped-down indexOf as it's faster than native
599 // https://jsperf.com/thor-indexof-vs-for/5
600 indexOf = function( list, elem ) {
603 for ( ; i < len; i++ ) {
604 if ( list[i] === elem ) {
611 booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
613 // Regular expressions
615 // http://www.w3.org/TR/css3-selectors/#whitespace
616 whitespace = "[\\x20\\t\\r\\n\\f]",
618 // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
619 identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",
621 // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
622 attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
623 // Operator (capture 2)
624 "*([*^$|!~]?=)" + whitespace +
625 // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
626 "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
629 pseudos = ":(" + identifier + ")(?:\\((" +
630 // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
631 // 1. quoted (capture 3; capture 4 or capture 5)
632 "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
633 // 2. simple (capture 6)
634 "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
635 // 3. anything else (capture 2)
639 // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
640 rwhitespace = new RegExp( whitespace + "+", "g" ),
641 rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
643 rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
644 rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
646 rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
648 rpseudo = new RegExp( pseudos ),
649 ridentifier = new RegExp( "^" + identifier + "$" ),
652 "ID": new RegExp( "^#(" + identifier + ")" ),
653 "CLASS": new RegExp( "^\\.(" + identifier + ")" ),
654 "TAG": new RegExp( "^(" + identifier + "|[*])" ),
655 "ATTR": new RegExp( "^" + attributes ),
656 "PSEUDO": new RegExp( "^" + pseudos ),
657 "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
658 "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
659 "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
660 "bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
661 // For use in libraries implementing .is()
662 // We use this for POS matching in `select`
663 "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
664 whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
667 rinputs = /^(?:input|select|textarea|button)$/i,
670 rnative = /^[^{]+\{\s*\[native \w/,
672 // Easily-parseable/retrievable ID or TAG or CLASS selectors
673 rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
678 // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
679 runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
680 funescape = function( _, escaped, escapedWhitespace ) {
681 var high = "0x" + escaped - 0x10000;
682 // NaN means non-codepoint
683 // Support: Firefox<24
684 // Workaround erroneous numeric interpretation of +"0x"
685 return high !== high || escapedWhitespace ?
689 String.fromCharCode( high + 0x10000 ) :
690 // Supplemental Plane codepoint (surrogate pair)
691 String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
694 // CSS string/identifier serialization
695 // https://drafts.csswg.org/cssom/#common-serializing-idioms
696 rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g,
697 fcssescape = function( ch, asCodePoint ) {
700 // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
705 // Control characters and (dependent upon position) numbers get escaped as code points
706 return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
709 // Other potentially-special ASCII characters get backslash-escaped
715 // Removing the function wrapper causes a "Permission Denied"
717 unloadHandler = function() {
721 disabledAncestor = addCombinator(
723 return elem.disabled === true;
725 { dir: "parentNode", next: "legend" }
728 // Optimize for push.apply( _, NodeList )
731 (arr = slice.call( preferredDoc.childNodes )),
732 preferredDoc.childNodes
734 // Support: Android<4.0
735 // Detect silently failing push.apply
736 arr[ preferredDoc.childNodes.length ].nodeType;
738 push = { apply: arr.length ?
740 // Leverage slice if possible
741 function( target, els ) {
742 push_native.apply( target, slice.call(els) );
746 // Otherwise append directly
747 function( target, els ) {
748 var j = target.length,
750 // Can't trust NodeList.length
751 while ( (target[j++] = els[i++]) ) {}
752 target.length = j - 1;
757 function Sizzle( selector, context, results, seed ) {
758 var m, i, elem, nid, match, groups, newSelector,
759 newContext = context && context.ownerDocument,
761 // nodeType defaults to 9, since context defaults to document
762 nodeType = context ? context.nodeType : 9;
764 results = results || [];
766 // Return early from calls with invalid selector or context
767 if ( typeof selector !== "string" || !selector ||
768 nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
773 // Try to shortcut find operations (as opposed to filters) in HTML documents
776 if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
777 setDocument( context );
779 context = context || document;
781 if ( documentIsHTML ) {
783 // If the selector is sufficiently simple, try using a "get*By*" DOM method
784 // (excepting DocumentFragment context, where the methods don't exist)
785 if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
788 if ( (m = match[1]) ) {
791 if ( nodeType === 9 ) {
792 if ( (elem = context.getElementById( m )) ) {
794 // Support: IE, Opera, Webkit
795 // TODO: identify versions
796 // getElementById can match elements by name instead of ID
797 if ( elem.id === m ) {
798 results.push( elem );
808 // Support: IE, Opera, Webkit
809 // TODO: identify versions
810 // getElementById can match elements by name instead of ID
811 if ( newContext && (elem = newContext.getElementById( m )) &&
812 contains( context, elem ) &&
815 results.push( elem );
821 } else if ( match[2] ) {
822 push.apply( results, context.getElementsByTagName( selector ) );
826 } else if ( (m = match[3]) && support.getElementsByClassName &&
827 context.getElementsByClassName ) {
829 push.apply( results, context.getElementsByClassName( m ) );
834 // Take advantage of querySelectorAll
836 !compilerCache[ selector + " " ] &&
837 (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
839 if ( nodeType !== 1 ) {
840 newContext = context;
841 newSelector = selector;
843 // qSA looks outside Element context, which is not what we want
844 // Thanks to Andrew Dupont for this workaround technique
846 // Exclude object elements
847 } else if ( context.nodeName.toLowerCase() !== "object" ) {
849 // Capture the context ID, setting it first if necessary
850 if ( (nid = context.getAttribute( "id" )) ) {
851 nid = nid.replace( rcssescape, fcssescape );
853 context.setAttribute( "id", (nid = expando) );
856 // Prefix every selector in the list
857 groups = tokenize( selector );
860 groups[i] = "#" + nid + " " + toSelector( groups[i] );
862 newSelector = groups.join( "," );
864 // Expand context for sibling selectors
865 newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
872 newContext.querySelectorAll( newSelector )
875 } catch ( qsaError ) {
877 if ( nid === expando ) {
878 context.removeAttribute( "id" );
887 return select( selector.replace( rtrim, "$1" ), context, results, seed );
891 * Create key-value caches of limited size
892 * @returns {function(string, object)} Returns the Object data after storing it on itself with
893 * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
894 * deleting the oldest entry
896 function createCache() {
899 function cache( key, value ) {
900 // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
901 if ( keys.push( key + " " ) > Expr.cacheLength ) {
902 // Only keep the most recent entries
903 delete cache[ keys.shift() ];
905 return (cache[ key + " " ] = value);
911 * Mark a function for special use by Sizzle
912 * @param {Function} fn The function to mark
914 function markFunction( fn ) {
915 fn[ expando ] = true;
920 * Support testing using an element
921 * @param {Function} fn Passed the created element and returns a boolean result
923 function assert( fn ) {
924 var el = document.createElement("fieldset");
931 // Remove from its parent by default
932 if ( el.parentNode ) {
933 el.parentNode.removeChild( el );
935 // release memory in IE
941 * Adds the same handler for all of the specified attrs
942 * @param {String} attrs Pipe-separated list of attributes
943 * @param {Function} handler The method that will be applied
945 function addHandle( attrs, handler ) {
946 var arr = attrs.split("|"),
950 Expr.attrHandle[ arr[i] ] = handler;
955 * Checks document order of two siblings
958 * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
960 function siblingCheck( a, b ) {
962 diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
963 a.sourceIndex - b.sourceIndex;
965 // Use IE sourceIndex if available on both nodes
970 // Check if b follows a
972 while ( (cur = cur.nextSibling) ) {
983 * Returns a function to use in pseudos for input types
984 * @param {String} type
986 function createInputPseudo( type ) {
987 return function( elem ) {
988 var name = elem.nodeName.toLowerCase();
989 return name === "input" && elem.type === type;
994 * Returns a function to use in pseudos for buttons
995 * @param {String} type
997 function createButtonPseudo( type ) {
998 return function( elem ) {
999 var name = elem.nodeName.toLowerCase();
1000 return (name === "input" || name === "button") && elem.type === type;
1005 * Returns a function to use in pseudos for :enabled/:disabled
1006 * @param {Boolean} disabled true for :disabled; false for :enabled
1008 function createDisabledPseudo( disabled ) {
1009 // Known :disabled false positives:
1010 // IE: *[disabled]:not(button, input, select, textarea, optgroup, option, menuitem, fieldset)
1011 // not IE: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
1012 return function( elem ) {
1014 // Check form elements and option elements for explicit disabling
1015 return "label" in elem && elem.disabled === disabled ||
1016 "form" in elem && elem.disabled === disabled ||
1018 // Check non-disabled form elements for fieldset[disabled] ancestors
1019 "form" in elem && elem.disabled === false && (
1021 // Ancestry is covered for us
1022 elem.isDisabled === disabled ||
1024 // Otherwise, assume any non-<option> under fieldset[disabled] is disabled
1026 elem.isDisabled !== !disabled &&
1027 ("label" in elem || !disabledAncestor( elem )) !== disabled
1033 * Returns a function to use in pseudos for positionals
1034 * @param {Function} fn
1036 function createPositionalPseudo( fn ) {
1037 return markFunction(function( argument ) {
1038 argument = +argument;
1039 return markFunction(function( seed, matches ) {
1041 matchIndexes = fn( [], seed.length, argument ),
1042 i = matchIndexes.length;
1044 // Match elements found at the specified indexes
1046 if ( seed[ (j = matchIndexes[i]) ] ) {
1047 seed[j] = !(matches[j] = seed[j]);
1055 * Checks a node for validity as a Sizzle context
1056 * @param {Element|Object=} context
1057 * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
1059 function testContext( context ) {
1060 return context && typeof context.getElementsByTagName !== "undefined" && context;
1063 // Expose support vars for convenience
1064 support = Sizzle.support = {};
1068 * @param {Element|Object} elem An element or a document
1069 * @returns {Boolean} True iff elem is a non-HTML XML node
1071 isXML = Sizzle.isXML = function( elem ) {
1072 // documentElement is verified for cases where it doesn't yet exist
1073 // (such as loading iframes in IE - #4833)
1074 var documentElement = elem && (elem.ownerDocument || elem).documentElement;
1075 return documentElement ? documentElement.nodeName !== "HTML" : false;
1079 * Sets document-related variables once based on the current document
1080 * @param {Element|Object} [doc] An element or document object to use to set the document
1081 * @returns {Object} Returns the current document
1083 setDocument = Sizzle.setDocument = function( node ) {
1084 var hasCompare, subWindow,
1085 doc = node ? node.ownerDocument || node : preferredDoc;
1087 // Return early if doc is invalid or already selected
1088 if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
1092 // Update global variables
1094 docElem = document.documentElement;
1095 documentIsHTML = !isXML( document );
1097 // Support: IE 9-11, Edge
1098 // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
1099 if ( preferredDoc !== document &&
1100 (subWindow = document.defaultView) && subWindow.top !== subWindow ) {
1102 // Support: IE 11, Edge
1103 if ( subWindow.addEventListener ) {
1104 subWindow.addEventListener( "unload", unloadHandler, false );
1106 // Support: IE 9 - 10 only
1107 } else if ( subWindow.attachEvent ) {
1108 subWindow.attachEvent( "onunload", unloadHandler );
1113 ---------------------------------------------------------------------- */
1116 // Verify that getAttribute really returns attributes and not properties
1117 // (excepting IE8 booleans)
1118 support.attributes = assert(function( el ) {
1120 return !el.getAttribute("className");
1124 ---------------------------------------------------------------------- */
1126 // Check if getElementsByTagName("*") returns only elements
1127 support.getElementsByTagName = assert(function( el ) {
1128 el.appendChild( document.createComment("") );
1129 return !el.getElementsByTagName("*").length;
1133 support.getElementsByClassName = rnative.test( document.getElementsByClassName );
1136 // Check if getElementById returns elements by name
1137 // The broken getElementById methods don't pick up programmatically-set names,
1138 // so use a roundabout getElementsByName test
1139 support.getById = assert(function( el ) {
1140 docElem.appendChild( el ).id = expando;
1141 return !document.getElementsByName || !document.getElementsByName( expando ).length;
1144 // ID find and filter
1145 if ( support.getById ) {
1146 Expr.find["ID"] = function( id, context ) {
1147 if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
1148 var m = context.getElementById( id );
1149 return m ? [ m ] : [];
1152 Expr.filter["ID"] = function( id ) {
1153 var attrId = id.replace( runescape, funescape );
1154 return function( elem ) {
1155 return elem.getAttribute("id") === attrId;
1160 // getElementById is not reliable as a find shortcut
1161 delete Expr.find["ID"];
1163 Expr.filter["ID"] = function( id ) {
1164 var attrId = id.replace( runescape, funescape );
1165 return function( elem ) {
1166 var node = typeof elem.getAttributeNode !== "undefined" &&
1167 elem.getAttributeNode("id");
1168 return node && node.value === attrId;
1174 Expr.find["TAG"] = support.getElementsByTagName ?
1175 function( tag, context ) {
1176 if ( typeof context.getElementsByTagName !== "undefined" ) {
1177 return context.getElementsByTagName( tag );
1179 // DocumentFragment nodes don't have gEBTN
1180 } else if ( support.qsa ) {
1181 return context.querySelectorAll( tag );
1185 function( tag, context ) {
1189 // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
1190 results = context.getElementsByTagName( tag );
1192 // Filter out possible comments
1193 if ( tag === "*" ) {
1194 while ( (elem = results[i++]) ) {
1195 if ( elem.nodeType === 1 ) {
1206 Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
1207 if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
1208 return context.getElementsByClassName( className );
1212 /* QSA/matchesSelector
1213 ---------------------------------------------------------------------- */
1215 // QSA and matchesSelector support
1217 // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
1220 // qSa(:focus) reports false when true (Chrome 21)
1221 // We allow this because of a bug in IE8/9 that throws an error
1222 // whenever `document.activeElement` is accessed on an iframe
1223 // So, we allow :focus to pass through QSA all the time to avoid the IE error
1224 // See https://bugs.jquery.com/ticket/13378
1227 if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
1229 // Regex strategy adopted from Diego Perini
1230 assert(function( el ) {
1231 // Select is set to empty string on purpose
1232 // This is to test IE's treatment of not explicitly
1233 // setting a boolean content attribute,
1234 // since its presence should be enough
1235 // https://bugs.jquery.com/ticket/12359
1236 docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" +
1237 "<select id='" + expando + "-\r\\' msallowcapture=''>" +
1238 "<option selected=''></option></select>";
1240 // Support: IE8, Opera 11-12.16
1241 // Nothing should be selected when empty strings follow ^= or $= or *=
1242 // The test attribute must be unknown in Opera but "safe" for WinRT
1243 // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
1244 if ( el.querySelectorAll("[msallowcapture^='']").length ) {
1245 rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
1249 // Boolean attributes and "value" are not treated correctly
1250 if ( !el.querySelectorAll("[selected]").length ) {
1251 rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
1254 // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
1255 if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
1256 rbuggyQSA.push("~=");
1259 // Webkit/Opera - :checked should return selected option elements
1260 // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
1261 // IE8 throws error here and will not see later tests
1262 if ( !el.querySelectorAll(":checked").length ) {
1263 rbuggyQSA.push(":checked");
1266 // Support: Safari 8+, iOS 8+
1267 // https://bugs.webkit.org/show_bug.cgi?id=136851
1268 // In-page `selector#id sibling-combinator selector` fails
1269 if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
1270 rbuggyQSA.push(".#.+[+~]");
1274 assert(function( el ) {
1275 el.innerHTML = "<a href='' disabled='disabled'></a>" +
1276 "<select disabled='disabled'><option/></select>";
1278 // Support: Windows 8 Native Apps
1279 // The type and name attributes are restricted during .innerHTML assignment
1280 var input = document.createElement("input");
1281 input.setAttribute( "type", "hidden" );
1282 el.appendChild( input ).setAttribute( "name", "D" );
1285 // Enforce case-sensitivity of name attribute
1286 if ( el.querySelectorAll("[name=d]").length ) {
1287 rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
1290 // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
1291 // IE8 throws error here and will not see later tests
1292 if ( el.querySelectorAll(":enabled").length !== 2 ) {
1293 rbuggyQSA.push( ":enabled", ":disabled" );
1297 // IE's :disabled selector does not pick up the children of disabled fieldsets
1298 docElem.appendChild( el ).disabled = true;
1299 if ( el.querySelectorAll(":disabled").length !== 2 ) {
1300 rbuggyQSA.push( ":enabled", ":disabled" );
1303 // Opera 10-11 does not throw on post-comma invalid pseudos
1304 el.querySelectorAll("*,:x");
1305 rbuggyQSA.push(",.*:");
1309 if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
1310 docElem.webkitMatchesSelector ||
1311 docElem.mozMatchesSelector ||
1312 docElem.oMatchesSelector ||
1313 docElem.msMatchesSelector) )) ) {
1315 assert(function( el ) {
1316 // Check to see if it's possible to do matchesSelector
1317 // on a disconnected node (IE 9)
1318 support.disconnectedMatch = matches.call( el, "*" );
1320 // This should fail with an exception
1321 // Gecko does not error, returns false instead
1322 matches.call( el, "[s!='']:x" );
1323 rbuggyMatches.push( "!=", pseudos );
1327 rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
1328 rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
1331 ---------------------------------------------------------------------- */
1332 hasCompare = rnative.test( docElem.compareDocumentPosition );
1334 // Element contains another
1335 // Purposefully self-exclusive
1336 // As in, an element does not contain itself
1337 contains = hasCompare || rnative.test( docElem.contains ) ?
1339 var adown = a.nodeType === 9 ? a.documentElement : a,
1340 bup = b && b.parentNode;
1341 return a === bup || !!( bup && bup.nodeType === 1 && (
1343 adown.contains( bup ) :
1344 a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
1349 while ( (b = b.parentNode) ) {
1359 ---------------------------------------------------------------------- */
1361 // Document order sorting
1362 sortOrder = hasCompare ?
1365 // Flag for duplicate removal
1367 hasDuplicate = true;
1371 // Sort on method existence if only one input has compareDocumentPosition
1372 var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
1377 // Calculate position if both inputs belong to the same document
1378 compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
1379 a.compareDocumentPosition( b ) :
1381 // Otherwise we know they are disconnected
1384 // Disconnected nodes
1386 (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
1388 // Choose the first element that is related to our preferred document
1389 if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
1392 if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
1396 // Maintain original order
1398 ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
1402 return compare & 4 ? -1 : 1;
1405 // Exit early if the nodes are identical
1407 hasDuplicate = true;
1418 // Parentless nodes are either documents or disconnected
1419 if ( !aup || !bup ) {
1420 return a === document ? -1 :
1421 b === document ? 1 :
1425 ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
1428 // If the nodes are siblings, we can do a quick check
1429 } else if ( aup === bup ) {
1430 return siblingCheck( a, b );
1433 // Otherwise we need full lists of their ancestors for comparison
1435 while ( (cur = cur.parentNode) ) {
1439 while ( (cur = cur.parentNode) ) {
1443 // Walk down the tree looking for a discrepancy
1444 while ( ap[i] === bp[i] ) {
1449 // Do a sibling check if the nodes have a common ancestor
1450 siblingCheck( ap[i], bp[i] ) :
1452 // Otherwise nodes in our document sort first
1453 ap[i] === preferredDoc ? -1 :
1454 bp[i] === preferredDoc ? 1 :
1461 Sizzle.matches = function( expr, elements ) {
1462 return Sizzle( expr, null, null, elements );
1465 Sizzle.matchesSelector = function( elem, expr ) {
1466 // Set document vars if needed
1467 if ( ( elem.ownerDocument || elem ) !== document ) {
1468 setDocument( elem );
1471 // Make sure that attribute selectors are quoted
1472 expr = expr.replace( rattributeQuotes, "='$1']" );
1474 if ( support.matchesSelector && documentIsHTML &&
1475 !compilerCache[ expr + " " ] &&
1476 ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
1477 ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
1480 var ret = matches.call( elem, expr );
1482 // IE 9's matchesSelector returns false on disconnected nodes
1483 if ( ret || support.disconnectedMatch ||
1484 // As well, disconnected nodes are said to be in a document
1486 elem.document && elem.document.nodeType !== 11 ) {
1492 return Sizzle( expr, document, null, [ elem ] ).length > 0;
1495 Sizzle.contains = function( context, elem ) {
1496 // Set document vars if needed
1497 if ( ( context.ownerDocument || context ) !== document ) {
1498 setDocument( context );
1500 return contains( context, elem );
1503 Sizzle.attr = function( elem, name ) {
1504 // Set document vars if needed
1505 if ( ( elem.ownerDocument || elem ) !== document ) {
1506 setDocument( elem );
1509 var fn = Expr.attrHandle[ name.toLowerCase() ],
1510 // Don't get fooled by Object.prototype properties (jQuery #13807)
1511 val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
1512 fn( elem, name, !documentIsHTML ) :
1515 return val !== undefined ?
1517 support.attributes || !documentIsHTML ?
1518 elem.getAttribute( name ) :
1519 (val = elem.getAttributeNode(name)) && val.specified ?
1524 Sizzle.escape = function( sel ) {
1525 return (sel + "").replace( rcssescape, fcssescape );
1528 Sizzle.error = function( msg ) {
1529 throw new Error( "Syntax error, unrecognized expression: " + msg );
1533 * Document sorting and removing duplicates
1534 * @param {ArrayLike} results
1536 Sizzle.uniqueSort = function( results ) {
1542 // Unless we *know* we can detect duplicates, assume their presence
1543 hasDuplicate = !support.detectDuplicates;
1544 sortInput = !support.sortStable && results.slice( 0 );
1545 results.sort( sortOrder );
1547 if ( hasDuplicate ) {
1548 while ( (elem = results[i++]) ) {
1549 if ( elem === results[ i ] ) {
1550 j = duplicates.push( i );
1554 results.splice( duplicates[ j ], 1 );
1558 // Clear input after sorting to release objects
1559 // See https://github.com/jquery/sizzle/pull/225
1566 * Utility function for retrieving the text value of an array of DOM nodes
1567 * @param {Array|Element} elem
1569 getText = Sizzle.getText = function( elem ) {
1573 nodeType = elem.nodeType;
1576 // If no nodeType, this is expected to be an array
1577 while ( (node = elem[i++]) ) {
1578 // Do not traverse comment nodes
1579 ret += getText( node );
1581 } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
1582 // Use textContent for elements
1583 // innerText usage removed for consistency of new lines (jQuery #11153)
1584 if ( typeof elem.textContent === "string" ) {
1585 return elem.textContent;
1587 // Traverse its children
1588 for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
1589 ret += getText( elem );
1592 } else if ( nodeType === 3 || nodeType === 4 ) {
1593 return elem.nodeValue;
1595 // Do not include comment or processing instruction nodes
1600 Expr = Sizzle.selectors = {
1602 // Can be adjusted by the user
1605 createPseudo: markFunction,
1614 ">": { dir: "parentNode", first: true },
1615 " ": { dir: "parentNode" },
1616 "+": { dir: "previousSibling", first: true },
1617 "~": { dir: "previousSibling" }
1621 "ATTR": function( match ) {
1622 match[1] = match[1].replace( runescape, funescape );
1624 // Move the given value to match[3] whether quoted or unquoted
1625 match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
1627 if ( match[2] === "~=" ) {
1628 match[3] = " " + match[3] + " ";
1631 return match.slice( 0, 4 );
1634 "CHILD": function( match ) {
1635 /* matches from matchExpr["CHILD"]
1636 1 type (only|nth|...)
1637 2 what (child|of-type)
1638 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
1639 4 xn-component of xn+y argument ([+-]?\d*n|)
1640 5 sign of xn-component
1642 7 sign of y-component
1645 match[1] = match[1].toLowerCase();
1647 if ( match[1].slice( 0, 3 ) === "nth" ) {
1648 // nth-* requires argument
1650 Sizzle.error( match[0] );
1653 // numeric x and y parameters for Expr.filter.CHILD
1654 // remember that false/true cast respectively to 0/1
1655 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
1656 match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
1658 // other types prohibit arguments
1659 } else if ( match[3] ) {
1660 Sizzle.error( match[0] );
1666 "PSEUDO": function( match ) {
1668 unquoted = !match[6] && match[2];
1670 if ( matchExpr["CHILD"].test( match[0] ) ) {
1674 // Accept quoted arguments as-is
1676 match[2] = match[4] || match[5] || "";
1678 // Strip excess characters from unquoted arguments
1679 } else if ( unquoted && rpseudo.test( unquoted ) &&
1680 // Get excess from tokenize (recursively)
1681 (excess = tokenize( unquoted, true )) &&
1682 // advance to the next closing parenthesis
1683 (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
1685 // excess is a negative index
1686 match[0] = match[0].slice( 0, excess );
1687 match[2] = unquoted.slice( 0, excess );
1690 // Return only captures needed by the pseudo filter method (type and argument)
1691 return match.slice( 0, 3 );
1697 "TAG": function( nodeNameSelector ) {
1698 var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
1699 return nodeNameSelector === "*" ?
1700 function() { return true; } :
1702 return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
1706 "CLASS": function( className ) {
1707 var pattern = classCache[ className + " " ];
1710 (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
1711 classCache( className, function( elem ) {
1712 return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
1716 "ATTR": function( name, operator, check ) {
1717 return function( elem ) {
1718 var result = Sizzle.attr( elem, name );
1720 if ( result == null ) {
1721 return operator === "!=";
1729 return operator === "=" ? result === check :
1730 operator === "!=" ? result !== check :
1731 operator === "^=" ? check && result.indexOf( check ) === 0 :
1732 operator === "*=" ? check && result.indexOf( check ) > -1 :
1733 operator === "$=" ? check && result.slice( -check.length ) === check :
1734 operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
1735 operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
1740 "CHILD": function( type, what, argument, first, last ) {
1741 var simple = type.slice( 0, 3 ) !== "nth",
1742 forward = type.slice( -4 ) !== "last",
1743 ofType = what === "of-type";
1745 return first === 1 && last === 0 ?
1747 // Shortcut for :nth-*(n)
1749 return !!elem.parentNode;
1752 function( elem, context, xml ) {
1753 var cache, uniqueCache, outerCache, node, nodeIndex, start,
1754 dir = simple !== forward ? "nextSibling" : "previousSibling",
1755 parent = elem.parentNode,
1756 name = ofType && elem.nodeName.toLowerCase(),
1757 useCache = !xml && !ofType,
1762 // :(first|last|only)-(child|of-type)
1766 while ( (node = node[ dir ]) ) {
1768 node.nodeName.toLowerCase() === name :
1769 node.nodeType === 1 ) {
1774 // Reverse direction for :only-* (if we haven't yet done so)
1775 start = dir = type === "only" && !start && "nextSibling";
1780 start = [ forward ? parent.firstChild : parent.lastChild ];
1782 // non-xml :nth-child(...) stores cache data on `parent`
1783 if ( forward && useCache ) {
1785 // Seek `elem` from a previously-cached index
1787 // ...in a gzip-friendly way
1789 outerCache = node[ expando ] || (node[ expando ] = {});
1791 // Support: IE <9 only
1792 // Defend against cloned attroperties (jQuery gh-1709)
1793 uniqueCache = outerCache[ node.uniqueID ] ||
1794 (outerCache[ node.uniqueID ] = {});
1796 cache = uniqueCache[ type ] || [];
1797 nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
1798 diff = nodeIndex && cache[ 2 ];
1799 node = nodeIndex && parent.childNodes[ nodeIndex ];
1801 while ( (node = ++nodeIndex && node && node[ dir ] ||
1803 // Fallback to seeking `elem` from the start
1804 (diff = nodeIndex = 0) || start.pop()) ) {
1806 // When found, cache indexes on `parent` and break
1807 if ( node.nodeType === 1 && ++diff && node === elem ) {
1808 uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
1814 // Use previously-cached element index if available
1816 // ...in a gzip-friendly way
1818 outerCache = node[ expando ] || (node[ expando ] = {});
1820 // Support: IE <9 only
1821 // Defend against cloned attroperties (jQuery gh-1709)
1822 uniqueCache = outerCache[ node.uniqueID ] ||
1823 (outerCache[ node.uniqueID ] = {});
1825 cache = uniqueCache[ type ] || [];
1826 nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
1830 // xml :nth-child(...)
1831 // or :nth-last-child(...) or :nth(-last)?-of-type(...)
1832 if ( diff === false ) {
1833 // Use the same loop as above to seek `elem` from the start
1834 while ( (node = ++nodeIndex && node && node[ dir ] ||
1835 (diff = nodeIndex = 0) || start.pop()) ) {
1838 node.nodeName.toLowerCase() === name :
1839 node.nodeType === 1 ) &&
1842 // Cache the index of each encountered element
1844 outerCache = node[ expando ] || (node[ expando ] = {});
1846 // Support: IE <9 only
1847 // Defend against cloned attroperties (jQuery gh-1709)
1848 uniqueCache = outerCache[ node.uniqueID ] ||
1849 (outerCache[ node.uniqueID ] = {});
1851 uniqueCache[ type ] = [ dirruns, diff ];
1854 if ( node === elem ) {
1862 // Incorporate the offset, then check against cycle size
1864 return diff === first || ( diff % first === 0 && diff / first >= 0 );
1869 "PSEUDO": function( pseudo, argument ) {
1870 // pseudo-class names are case-insensitive
1871 // http://www.w3.org/TR/selectors/#pseudo-classes
1872 // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
1873 // Remember that setFilters inherits from pseudos
1875 fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
1876 Sizzle.error( "unsupported pseudo: " + pseudo );
1878 // The user may use createPseudo to indicate that
1879 // arguments are needed to create the filter function
1880 // just as Sizzle does
1881 if ( fn[ expando ] ) {
1882 return fn( argument );
1885 // But maintain support for old signatures
1886 if ( fn.length > 1 ) {
1887 args = [ pseudo, pseudo, "", argument ];
1888 return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
1889 markFunction(function( seed, matches ) {
1891 matched = fn( seed, argument ),
1894 idx = indexOf( seed, matched[i] );
1895 seed[ idx ] = !( matches[ idx ] = matched[i] );
1899 return fn( elem, 0, args );
1908 // Potentially complex pseudos
1909 "not": markFunction(function( selector ) {
1910 // Trim the selector passed to compile
1911 // to avoid treating leading and trailing
1912 // spaces as combinators
1915 matcher = compile( selector.replace( rtrim, "$1" ) );
1917 return matcher[ expando ] ?
1918 markFunction(function( seed, matches, context, xml ) {
1920 unmatched = matcher( seed, null, xml, [] ),
1923 // Match elements unmatched by `matcher`
1925 if ( (elem = unmatched[i]) ) {
1926 seed[i] = !(matches[i] = elem);
1930 function( elem, context, xml ) {
1932 matcher( input, null, xml, results );
1933 // Don't keep the element (issue #299)
1935 return !results.pop();
1939 "has": markFunction(function( selector ) {
1940 return function( elem ) {
1941 return Sizzle( selector, elem ).length > 0;
1945 "contains": markFunction(function( text ) {
1946 text = text.replace( runescape, funescape );
1947 return function( elem ) {
1948 return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
1952 // "Whether an element is represented by a :lang() selector
1953 // is based solely on the element's language value
1954 // being equal to the identifier C,
1955 // or beginning with the identifier C immediately followed by "-".
1956 // The matching of C against the element's language value is performed case-insensitively.
1957 // The identifier C does not have to be a valid language name."
1958 // http://www.w3.org/TR/selectors/#lang-pseudo
1959 "lang": markFunction( function( lang ) {
1960 // lang value must be a valid identifier
1961 if ( !ridentifier.test(lang || "") ) {
1962 Sizzle.error( "unsupported lang: " + lang );
1964 lang = lang.replace( runescape, funescape ).toLowerCase();
1965 return function( elem ) {
1968 if ( (elemLang = documentIsHTML ?
1970 elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
1972 elemLang = elemLang.toLowerCase();
1973 return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
1975 } while ( (elem = elem.parentNode) && elem.nodeType === 1 );
1981 "target": function( elem ) {
1982 var hash = window.location && window.location.hash;
1983 return hash && hash.slice( 1 ) === elem.id;
1986 "root": function( elem ) {
1987 return elem === docElem;
1990 "focus": function( elem ) {
1991 return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
1994 // Boolean properties
1995 "enabled": createDisabledPseudo( false ),
1996 "disabled": createDisabledPseudo( true ),
1998 "checked": function( elem ) {
1999 // In CSS3, :checked should return both checked and selected elements
2000 // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
2001 var nodeName = elem.nodeName.toLowerCase();
2002 return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
2005 "selected": function( elem ) {
2006 // Accessing this property makes selected-by-default
2007 // options in Safari work properly
2008 if ( elem.parentNode ) {
2009 elem.parentNode.selectedIndex;
2012 return elem.selected === true;
2016 "empty": function( elem ) {
2017 // http://www.w3.org/TR/selectors/#empty-pseudo
2018 // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
2019 // but not by others (comment: 8; processing instruction: 7; etc.)
2020 // nodeType < 6 works because attributes (2) do not appear as children
2021 for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
2022 if ( elem.nodeType < 6 ) {
2029 "parent": function( elem ) {
2030 return !Expr.pseudos["empty"]( elem );
2033 // Element/input types
2034 "header": function( elem ) {
2035 return rheader.test( elem.nodeName );
2038 "input": function( elem ) {
2039 return rinputs.test( elem.nodeName );
2042 "button": function( elem ) {
2043 var name = elem.nodeName.toLowerCase();
2044 return name === "input" && elem.type === "button" || name === "button";
2047 "text": function( elem ) {
2049 return elem.nodeName.toLowerCase() === "input" &&
2050 elem.type === "text" &&
2053 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
2054 ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
2057 // Position-in-collection
2058 "first": createPositionalPseudo(function() {
2062 "last": createPositionalPseudo(function( matchIndexes, length ) {
2063 return [ length - 1 ];
2066 "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
2067 return [ argument < 0 ? argument + length : argument ];
2070 "even": createPositionalPseudo(function( matchIndexes, length ) {
2072 for ( ; i < length; i += 2 ) {
2073 matchIndexes.push( i );
2075 return matchIndexes;
2078 "odd": createPositionalPseudo(function( matchIndexes, length ) {
2080 for ( ; i < length; i += 2 ) {
2081 matchIndexes.push( i );
2083 return matchIndexes;
2086 "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
2087 var i = argument < 0 ? argument + length : argument;
2088 for ( ; --i >= 0; ) {
2089 matchIndexes.push( i );
2091 return matchIndexes;
2094 "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
2095 var i = argument < 0 ? argument + length : argument;
2096 for ( ; ++i < length; ) {
2097 matchIndexes.push( i );
2099 return matchIndexes;
2104 Expr.pseudos["nth"] = Expr.pseudos["eq"];
2106 // Add button/input type pseudos
2107 for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
2108 Expr.pseudos[ i ] = createInputPseudo( i );
2110 for ( i in { submit: true, reset: true } ) {
2111 Expr.pseudos[ i ] = createButtonPseudo( i );
2114 // Easy API for creating new setFilters
2115 function setFilters() {}
2116 setFilters.prototype = Expr.filters = Expr.pseudos;
2117 Expr.setFilters = new setFilters();
2119 tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
2120 var matched, match, tokens, type,
2121 soFar, groups, preFilters,
2122 cached = tokenCache[ selector + " " ];
2125 return parseOnly ? 0 : cached.slice( 0 );
2130 preFilters = Expr.preFilter;
2134 // Comma and first run
2135 if ( !matched || (match = rcomma.exec( soFar )) ) {
2137 // Don't consume trailing commas as valid
2138 soFar = soFar.slice( match[0].length ) || soFar;
2140 groups.push( (tokens = []) );
2146 if ( (match = rcombinators.exec( soFar )) ) {
2147 matched = match.shift();
2150 // Cast descendant combinators to space
2151 type: match[0].replace( rtrim, " " )
2153 soFar = soFar.slice( matched.length );
2157 for ( type in Expr.filter ) {
2158 if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
2159 (match = preFilters[ type ]( match ))) ) {
2160 matched = match.shift();
2166 soFar = soFar.slice( matched.length );
2175 // Return the length of the invalid excess
2176 // if we're just parsing
2177 // Otherwise, throw an error or return tokens
2181 Sizzle.error( selector ) :
2183 tokenCache( selector, groups ).slice( 0 );
2186 function toSelector( tokens ) {
2188 len = tokens.length,
2190 for ( ; i < len; i++ ) {
2191 selector += tokens[i].value;
2196 function addCombinator( matcher, combinator, base ) {
2197 var dir = combinator.dir,
2198 skip = combinator.next,
2200 checkNonElements = base && key === "parentNode",
2203 return combinator.first ?
2204 // Check against closest ancestor/preceding element
2205 function( elem, context, xml ) {
2206 while ( (elem = elem[ dir ]) ) {
2207 if ( elem.nodeType === 1 || checkNonElements ) {
2208 return matcher( elem, context, xml );
2213 // Check against all ancestor/preceding elements
2214 function( elem, context, xml ) {
2215 var oldCache, uniqueCache, outerCache,
2216 newCache = [ dirruns, doneName ];
2218 // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
2220 while ( (elem = elem[ dir ]) ) {
2221 if ( elem.nodeType === 1 || checkNonElements ) {
2222 if ( matcher( elem, context, xml ) ) {
2228 while ( (elem = elem[ dir ]) ) {
2229 if ( elem.nodeType === 1 || checkNonElements ) {
2230 outerCache = elem[ expando ] || (elem[ expando ] = {});
2232 // Support: IE <9 only
2233 // Defend against cloned attroperties (jQuery gh-1709)
2234 uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
2236 if ( skip && skip === elem.nodeName.toLowerCase() ) {
2237 elem = elem[ dir ] || elem;
2238 } else if ( (oldCache = uniqueCache[ key ]) &&
2239 oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
2241 // Assign to newCache so results back-propagate to previous elements
2242 return (newCache[ 2 ] = oldCache[ 2 ]);
2244 // Reuse newcache so results back-propagate to previous elements
2245 uniqueCache[ key ] = newCache;
2247 // A match means we're done; a fail means we have to keep checking
2248 if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
2258 function elementMatcher( matchers ) {
2259 return matchers.length > 1 ?
2260 function( elem, context, xml ) {
2261 var i = matchers.length;
2263 if ( !matchers[i]( elem, context, xml ) ) {
2272 function multipleContexts( selector, contexts, results ) {
2274 len = contexts.length;
2275 for ( ; i < len; i++ ) {
2276 Sizzle( selector, contexts[i], results );
2281 function condense( unmatched, map, filter, context, xml ) {
2285 len = unmatched.length,
2286 mapped = map != null;
2288 for ( ; i < len; i++ ) {
2289 if ( (elem = unmatched[i]) ) {
2290 if ( !filter || filter( elem, context, xml ) ) {
2291 newUnmatched.push( elem );
2299 return newUnmatched;
2302 function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
2303 if ( postFilter && !postFilter[ expando ] ) {
2304 postFilter = setMatcher( postFilter );
2306 if ( postFinder && !postFinder[ expando ] ) {
2307 postFinder = setMatcher( postFinder, postSelector );
2309 return markFunction(function( seed, results, context, xml ) {
2313 preexisting = results.length,
2315 // Get initial elements from seed or context
2316 elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
2318 // Prefilter to get matcher input, preserving a map for seed-results synchronization
2319 matcherIn = preFilter && ( seed || !selector ) ?
2320 condense( elems, preMap, preFilter, context, xml ) :
2323 matcherOut = matcher ?
2324 // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
2325 postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
2327 // ...intermediate processing is necessary
2330 // ...otherwise use results directly
2334 // Find primary matches
2336 matcher( matcherIn, matcherOut, context, xml );
2341 temp = condense( matcherOut, postMap );
2342 postFilter( temp, [], context, xml );
2344 // Un-match failing elements by moving them back to matcherIn
2347 if ( (elem = temp[i]) ) {
2348 matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
2354 if ( postFinder || preFilter ) {
2356 // Get the final matcherOut by condensing this intermediate into postFinder contexts
2358 i = matcherOut.length;
2360 if ( (elem = matcherOut[i]) ) {
2361 // Restore matcherIn since elem is not yet a final match
2362 temp.push( (matcherIn[i] = elem) );
2365 postFinder( null, (matcherOut = []), temp, xml );
2368 // Move matched elements from seed to results to keep them synchronized
2369 i = matcherOut.length;
2371 if ( (elem = matcherOut[i]) &&
2372 (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
2374 seed[temp] = !(results[temp] = elem);
2379 // Add elements to results, through postFinder if defined
2381 matcherOut = condense(
2382 matcherOut === results ?
2383 matcherOut.splice( preexisting, matcherOut.length ) :
2387 postFinder( null, results, matcherOut, xml );
2389 push.apply( results, matcherOut );
2395 function matcherFromTokens( tokens ) {
2396 var checkContext, matcher, j,
2397 len = tokens.length,
2398 leadingRelative = Expr.relative[ tokens[0].type ],
2399 implicitRelative = leadingRelative || Expr.relative[" "],
2400 i = leadingRelative ? 1 : 0,
2402 // The foundational matcher ensures that elements are reachable from top-level context(s)
2403 matchContext = addCombinator( function( elem ) {
2404 return elem === checkContext;
2405 }, implicitRelative, true ),
2406 matchAnyContext = addCombinator( function( elem ) {
2407 return indexOf( checkContext, elem ) > -1;
2408 }, implicitRelative, true ),
2409 matchers = [ function( elem, context, xml ) {
2410 var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
2411 (checkContext = context).nodeType ?
2412 matchContext( elem, context, xml ) :
2413 matchAnyContext( elem, context, xml ) );
2414 // Avoid hanging onto element (issue #299)
2415 checkContext = null;
2419 for ( ; i < len; i++ ) {
2420 if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
2421 matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
2423 matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
2425 // Return special upon seeing a positional matcher
2426 if ( matcher[ expando ] ) {
2427 // Find the next relative operator (if any) for proper handling
2429 for ( ; j < len; j++ ) {
2430 if ( Expr.relative[ tokens[j].type ] ) {
2435 i > 1 && elementMatcher( matchers ),
2436 i > 1 && toSelector(
2437 // If the preceding token was a descendant combinator, insert an implicit any-element `*`
2438 tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
2439 ).replace( rtrim, "$1" ),
2441 i < j && matcherFromTokens( tokens.slice( i, j ) ),
2442 j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
2443 j < len && toSelector( tokens )
2446 matchers.push( matcher );
2450 return elementMatcher( matchers );
2453 function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
2454 var bySet = setMatchers.length > 0,
2455 byElement = elementMatchers.length > 0,
2456 superMatcher = function( seed, context, xml, results, outermost ) {
2457 var elem, j, matcher,
2460 unmatched = seed && [],
2462 contextBackup = outermostContext,
2463 // We must always have either seed elements or outermost context
2464 elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
2465 // Use integer dirruns iff this is the outermost matcher
2466 dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
2470 outermostContext = context === document || context || outermost;
2473 // Add elements passing elementMatchers directly to results
2474 // Support: IE<9, Safari
2475 // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
2476 for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
2477 if ( byElement && elem ) {
2479 if ( !context && elem.ownerDocument !== document ) {
2480 setDocument( elem );
2481 xml = !documentIsHTML;
2483 while ( (matcher = elementMatchers[j++]) ) {
2484 if ( matcher( elem, context || document, xml) ) {
2485 results.push( elem );
2490 dirruns = dirrunsUnique;
2494 // Track unmatched elements for set filters
2496 // They will have gone through all possible matchers
2497 if ( (elem = !matcher && elem) ) {
2501 // Lengthen the array for every element, matched or not
2503 unmatched.push( elem );
2508 // `i` is now the count of elements visited above, and adding it to `matchedCount`
2509 // makes the latter nonnegative.
2512 // Apply set filters to unmatched elements
2513 // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
2514 // equals `i`), unless we didn't visit _any_ elements in the above loop because we have
2515 // no element matchers and no seed.
2516 // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
2517 // case, which will result in a "00" `matchedCount` that differs from `i` but is also
2518 // numerically zero.
2519 if ( bySet && i !== matchedCount ) {
2521 while ( (matcher = setMatchers[j++]) ) {
2522 matcher( unmatched, setMatched, context, xml );
2526 // Reintegrate element matches to eliminate the need for sorting
2527 if ( matchedCount > 0 ) {
2529 if ( !(unmatched[i] || setMatched[i]) ) {
2530 setMatched[i] = pop.call( results );
2535 // Discard index placeholder values to get only actual matches
2536 setMatched = condense( setMatched );
2539 // Add matches to results
2540 push.apply( results, setMatched );
2542 // Seedless set matches succeeding multiple successful matchers stipulate sorting
2543 if ( outermost && !seed && setMatched.length > 0 &&
2544 ( matchedCount + setMatchers.length ) > 1 ) {
2546 Sizzle.uniqueSort( results );
2550 // Override manipulation of globals by nested matchers
2552 dirruns = dirrunsUnique;
2553 outermostContext = contextBackup;
2560 markFunction( superMatcher ) :
2564 compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
2567 elementMatchers = [],
2568 cached = compilerCache[ selector + " " ];
2571 // Generate a function of recursive functions that can be used to check each element
2573 match = tokenize( selector );
2577 cached = matcherFromTokens( match[i] );
2578 if ( cached[ expando ] ) {
2579 setMatchers.push( cached );
2581 elementMatchers.push( cached );
2585 // Cache the compiled function
2586 cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
2588 // Save selector and tokenization
2589 cached.selector = selector;
2595 * A low-level selection function that works with Sizzle's compiled
2596 * selector functions
2597 * @param {String|Function} selector A selector or a pre-compiled
2598 * selector function built with Sizzle.compile
2599 * @param {Element} context
2600 * @param {Array} [results]
2601 * @param {Array} [seed] A set of elements to match against
2603 select = Sizzle.select = function( selector, context, results, seed ) {
2604 var i, tokens, token, type, find,
2605 compiled = typeof selector === "function" && selector,
2606 match = !seed && tokenize( (selector = compiled.selector || selector) );
2608 results = results || [];
2610 // Try to minimize operations if there is only one selector in the list and no seed
2611 // (the latter of which guarantees us context)
2612 if ( match.length === 1 ) {
2614 // Reduce context if the leading compound selector is an ID
2615 tokens = match[0] = match[0].slice( 0 );
2616 if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
2617 support.getById && context.nodeType === 9 && documentIsHTML &&
2618 Expr.relative[ tokens[1].type ] ) {
2620 context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
2624 // Precompiled matchers will still verify ancestry, so step up a level
2625 } else if ( compiled ) {
2626 context = context.parentNode;
2629 selector = selector.slice( tokens.shift().value.length );
2632 // Fetch a seed set for right-to-left matching
2633 i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
2637 // Abort if we hit a combinator
2638 if ( Expr.relative[ (type = token.type) ] ) {
2641 if ( (find = Expr.find[ type ]) ) {
2642 // Search, expanding context for leading sibling combinators
2644 token.matches[0].replace( runescape, funescape ),
2645 rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
2648 // If seed is empty or no tokens remain, we can return early
2649 tokens.splice( i, 1 );
2650 selector = seed.length && toSelector( tokens );
2652 push.apply( results, seed );
2662 // Compile and execute a filtering function if one is not provided
2663 // Provide `match` to avoid retokenization if we modified the selector above
2664 ( compiled || compile( selector, match ) )(
2669 !context || rsibling.test( selector ) && testContext( context.parentNode ) || context
2674 // One-time assignments
2677 support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
2679 // Support: Chrome 14-35+
2680 // Always assume duplicates if they aren't passed to the comparison function
2681 support.detectDuplicates = !!hasDuplicate;
2683 // Initialize against the default document
2686 // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
2687 // Detached nodes confoundingly follow *each other*
2688 support.sortDetached = assert(function( el ) {
2689 // Should return 1, but returns 4 (following)
2690 return el.compareDocumentPosition( document.createElement("fieldset") ) & 1;
2694 // Prevent attribute/property "interpolation"
2695 // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
2696 if ( !assert(function( el ) {
2697 el.innerHTML = "<a href='#'></a>";
2698 return el.firstChild.getAttribute("href") === "#" ;
2700 addHandle( "type|href|height|width", function( elem, name, isXML ) {
2702 return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
2708 // Use defaultValue in place of getAttribute("value")
2709 if ( !support.attributes || !assert(function( el ) {
2710 el.innerHTML = "<input/>";
2711 el.firstChild.setAttribute( "value", "" );
2712 return el.firstChild.getAttribute( "value" ) === "";
2714 addHandle( "value", function( elem, name, isXML ) {
2715 if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
2716 return elem.defaultValue;
2722 // Use getAttributeNode to fetch booleans when getAttribute lies
2723 if ( !assert(function( el ) {
2724 return el.getAttribute("disabled") == null;
2726 addHandle( booleans, function( elem, name, isXML ) {
2729 return elem[ name ] === true ? name.toLowerCase() :
2730 (val = elem.getAttributeNode( name )) && val.specified ?
2743 jQuery.find = Sizzle;
2744 jQuery.expr = Sizzle.selectors;
2747 jQuery.expr[ ":" ] = jQuery.expr.pseudos;
2748 jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
2749 jQuery.text = Sizzle.getText;
2750 jQuery.isXMLDoc = Sizzle.isXML;
2751 jQuery.contains = Sizzle.contains;
2752 jQuery.escapeSelector = Sizzle.escape;
2757 var dir = function( elem, dir, until ) {
2759 truncate = until !== undefined;
2761 while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
2762 if ( elem.nodeType === 1 ) {
2763 if ( truncate && jQuery( elem ).is( until ) ) {
2766 matched.push( elem );
2773 var siblings = function( n, elem ) {
2776 for ( ; n; n = n.nextSibling ) {
2777 if ( n.nodeType === 1 && n !== elem ) {
2786 var rneedsContext = jQuery.expr.match.needsContext;
2788 var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );
2792 var risSimple = /^.[^:#\[\.,]*$/;
2794 // Implement the identical functionality for filter and not
2795 function winnow( elements, qualifier, not ) {
2796 if ( jQuery.isFunction( qualifier ) ) {
2797 return jQuery.grep( elements, function( elem, i ) {
2798 return !!qualifier.call( elem, i, elem ) !== not;
2803 if ( qualifier.nodeType ) {
2804 return jQuery.grep( elements, function( elem ) {
2805 return ( elem === qualifier ) !== not;
2810 if ( typeof qualifier === "string" ) {
2811 if ( risSimple.test( qualifier ) ) {
2812 return jQuery.filter( qualifier, elements, not );
2815 qualifier = jQuery.filter( qualifier, elements );
2818 return jQuery.grep( elements, function( elem ) {
2819 return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1;
2823 jQuery.filter = function( expr, elems, not ) {
2824 var elem = elems[ 0 ];
2827 expr = ":not(" + expr + ")";
2830 return elems.length === 1 && elem.nodeType === 1 ?
2831 jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
2832 jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
2833 return elem.nodeType === 1;
2838 find: function( selector ) {
2843 if ( typeof selector !== "string" ) {
2844 return this.pushStack( jQuery( selector ).filter( function() {
2845 for ( i = 0; i < len; i++ ) {
2846 if ( jQuery.contains( self[ i ], this ) ) {
2853 ret = this.pushStack( [] );
2855 for ( i = 0; i < len; i++ ) {
2856 jQuery.find( selector, self[ i ], ret );
2859 return len > 1 ? jQuery.uniqueSort( ret ) : ret;
2861 filter: function( selector ) {
2862 return this.pushStack( winnow( this, selector || [], false ) );
2864 not: function( selector ) {
2865 return this.pushStack( winnow( this, selector || [], true ) );
2867 is: function( selector ) {
2871 // If this is a positional/relative selector, check membership in the returned set
2872 // so $("p:first").is("p:last") won't return true for a doc with two "p".
2873 typeof selector === "string" && rneedsContext.test( selector ) ?
2874 jQuery( selector ) :
2882 // Initialize a jQuery object
2885 // A central reference to the root jQuery(document)
2888 // A simple way to check for HTML strings
2889 // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
2890 // Strict HTML recognition (#11290: must start with <)
2891 // Shortcut simple #id case for speed
2892 rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
2894 init = jQuery.fn.init = function( selector, context, root ) {
2897 // HANDLE: $(""), $(null), $(undefined), $(false)
2902 // Method init() accepts an alternate rootjQuery
2903 // so migrate can support jQuery.sub (gh-2101)
2904 root = root || rootjQuery;
2906 // Handle HTML strings
2907 if ( typeof selector === "string" ) {
2908 if ( selector[ 0 ] === "<" &&
2909 selector[ selector.length - 1 ] === ">" &&
2910 selector.length >= 3 ) {
2912 // Assume that strings that start and end with <> are HTML and skip the regex check
2913 match = [ null, selector, null ];
2916 match = rquickExpr.exec( selector );
2919 // Match html or make sure no context is specified for #id
2920 if ( match && ( match[ 1 ] || !context ) ) {
2922 // HANDLE: $(html) -> $(array)
2924 context = context instanceof jQuery ? context[ 0 ] : context;
2926 // Option to run scripts is true for back-compat
2927 // Intentionally let the error be thrown if parseHTML is not present
2928 jQuery.merge( this, jQuery.parseHTML(
2930 context && context.nodeType ? context.ownerDocument || context : document,
2934 // HANDLE: $(html, props)
2935 if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
2936 for ( match in context ) {
2938 // Properties of context are called as methods if possible
2939 if ( jQuery.isFunction( this[ match ] ) ) {
2940 this[ match ]( context[ match ] );
2942 // ...and otherwise set as attributes
2944 this.attr( match, context[ match ] );
2953 elem = document.getElementById( match[ 2 ] );
2957 // Inject the element directly into the jQuery object
2964 // HANDLE: $(expr, $(...))
2965 } else if ( !context || context.jquery ) {
2966 return ( context || root ).find( selector );
2968 // HANDLE: $(expr, context)
2969 // (which is just equivalent to: $(context).find(expr)
2971 return this.constructor( context ).find( selector );
2974 // HANDLE: $(DOMElement)
2975 } else if ( selector.nodeType ) {
2976 this[ 0 ] = selector;
2980 // HANDLE: $(function)
2981 // Shortcut for document ready
2982 } else if ( jQuery.isFunction( selector ) ) {
2983 return root.ready !== undefined ?
2984 root.ready( selector ) :
2986 // Execute immediately if ready is not present
2990 return jQuery.makeArray( selector, this );
2993 // Give the init function the jQuery prototype for later instantiation
2994 init.prototype = jQuery.fn;
2996 // Initialize central reference
2997 rootjQuery = jQuery( document );
3000 var rparentsprev = /^(?:parents|prev(?:Until|All))/,
3002 // Methods guaranteed to produce a unique set when starting from a unique set
3003 guaranteedUnique = {
3011 has: function( target ) {
3012 var targets = jQuery( target, this ),
3015 return this.filter( function() {
3017 for ( ; i < l; i++ ) {
3018 if ( jQuery.contains( this, targets[ i ] ) ) {
3025 closest: function( selectors, context ) {
3030 targets = typeof selectors !== "string" && jQuery( selectors );
3032 // Positional selectors never match, since there's no _selection_ context
3033 if ( !rneedsContext.test( selectors ) ) {
3034 for ( ; i < l; i++ ) {
3035 for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
3037 // Always skip document fragments
3038 if ( cur.nodeType < 11 && ( targets ?
3039 targets.index( cur ) > -1 :
3041 // Don't pass non-elements to Sizzle
3042 cur.nodeType === 1 &&
3043 jQuery.find.matchesSelector( cur, selectors ) ) ) {
3045 matched.push( cur );
3052 return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
3055 // Determine the position of an element within the set
3056 index: function( elem ) {
3058 // No argument, return index in parent
3060 return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
3063 // Index in selector
3064 if ( typeof elem === "string" ) {
3065 return indexOf.call( jQuery( elem ), this[ 0 ] );
3068 // Locate the position of the desired element
3069 return indexOf.call( this,
3071 // If it receives a jQuery object, the first element is used
3072 elem.jquery ? elem[ 0 ] : elem
3076 add: function( selector, context ) {
3077 return this.pushStack(
3079 jQuery.merge( this.get(), jQuery( selector, context ) )
3084 addBack: function( selector ) {
3085 return this.add( selector == null ?
3086 this.prevObject : this.prevObject.filter( selector )
3091 function sibling( cur, dir ) {
3092 while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
3097 parent: function( elem ) {
3098 var parent = elem.parentNode;
3099 return parent && parent.nodeType !== 11 ? parent : null;
3101 parents: function( elem ) {
3102 return dir( elem, "parentNode" );
3104 parentsUntil: function( elem, i, until ) {
3105 return dir( elem, "parentNode", until );
3107 next: function( elem ) {
3108 return sibling( elem, "nextSibling" );
3110 prev: function( elem ) {
3111 return sibling( elem, "previousSibling" );
3113 nextAll: function( elem ) {
3114 return dir( elem, "nextSibling" );
3116 prevAll: function( elem ) {
3117 return dir( elem, "previousSibling" );
3119 nextUntil: function( elem, i, until ) {
3120 return dir( elem, "nextSibling", until );
3122 prevUntil: function( elem, i, until ) {
3123 return dir( elem, "previousSibling", until );
3125 siblings: function( elem ) {
3126 return siblings( ( elem.parentNode || {} ).firstChild, elem );
3128 children: function( elem ) {
3129 return siblings( elem.firstChild );
3131 contents: function( elem ) {
3132 return elem.contentDocument || jQuery.merge( [], elem.childNodes );
3134 }, function( name, fn ) {
3135 jQuery.fn[ name ] = function( until, selector ) {
3136 var matched = jQuery.map( this, fn, until );
3138 if ( name.slice( -5 ) !== "Until" ) {
3142 if ( selector && typeof selector === "string" ) {
3143 matched = jQuery.filter( selector, matched );
3146 if ( this.length > 1 ) {
3148 // Remove duplicates
3149 if ( !guaranteedUnique[ name ] ) {
3150 jQuery.uniqueSort( matched );
3153 // Reverse order for parents* and prev-derivatives
3154 if ( rparentsprev.test( name ) ) {
3159 return this.pushStack( matched );
3162 var rnotwhite = ( /\S+/g );
3166 // Convert String-formatted options into Object-formatted ones
3167 function createOptions( options ) {
3169 jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
3170 object[ flag ] = true;
3176 * Create a callback list using the following parameters:
3178 * options: an optional list of space-separated options that will change how
3179 * the callback list behaves or a more traditional option object
3181 * By default a callback list will act like an event callback list and can be
3182 * "fired" multiple times.
3186 * once: will ensure the callback list can only be fired once (like a Deferred)
3188 * memory: will keep track of previous values and will call any callback added
3189 * after the list has been fired right away with the latest "memorized"
3190 * values (like a Deferred)
3192 * unique: will ensure a callback can only be added once (no duplicate in the list)
3194 * stopOnFalse: interrupt callings when a callback returns false
3197 jQuery.Callbacks = function( options ) {
3199 // Convert options from String-formatted to Object-formatted if needed
3200 // (we check in cache first)
3201 options = typeof options === "string" ?
3202 createOptions( options ) :
3203 jQuery.extend( {}, options );
3205 var // Flag to know if list is currently firing
3208 // Last fire value for non-forgettable lists
3211 // Flag to know if list was already fired
3214 // Flag to prevent firing
3217 // Actual callback list
3220 // Queue of execution data for repeatable lists
3223 // Index of currently firing callback (modified by add/remove as needed)
3229 // Enforce single-firing
3230 locked = options.once;
3232 // Execute callbacks for all pending executions,
3233 // respecting firingIndex overrides and runtime changes
3234 fired = firing = true;
3235 for ( ; queue.length; firingIndex = -1 ) {
3236 memory = queue.shift();
3237 while ( ++firingIndex < list.length ) {
3239 // Run callback and check for early termination
3240 if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
3241 options.stopOnFalse ) {
3243 // Jump to end and forget the data so .add doesn't re-fire
3244 firingIndex = list.length;
3250 // Forget the data if we're done with it
3251 if ( !options.memory ) {
3257 // Clean up if we're done firing for good
3260 // Keep an empty list if we have data for future add calls
3264 // Otherwise, this object is spent
3271 // Actual Callbacks object
3274 // Add a callback or a collection of callbacks to the list
3278 // If we have memory from a past run, we should fire after adding
3279 if ( memory && !firing ) {
3280 firingIndex = list.length - 1;
3281 queue.push( memory );
3284 ( function add( args ) {
3285 jQuery.each( args, function( _, arg ) {
3286 if ( jQuery.isFunction( arg ) ) {
3287 if ( !options.unique || !self.has( arg ) ) {
3290 } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {
3292 // Inspect recursively
3298 if ( memory && !firing ) {
3305 // Remove a callback from the list
3306 remove: function() {
3307 jQuery.each( arguments, function( _, arg ) {
3309 while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
3310 list.splice( index, 1 );
3312 // Handle firing indexes
3313 if ( index <= firingIndex ) {
3321 // Check if a given callback is in the list.
3322 // If no argument is given, return whether or not list has callbacks attached.
3323 has: function( fn ) {
3325 jQuery.inArray( fn, list ) > -1 :
3329 // Remove all callbacks from the list
3337 // Disable .fire and .add
3338 // Abort any current/pending executions
3339 // Clear all callbacks and values
3340 disable: function() {
3341 locked = queue = [];
3345 disabled: function() {
3350 // Also disable .add unless we have memory (since it would have no effect)
3351 // Abort any pending executions
3353 locked = queue = [];
3354 if ( !memory && !firing ) {
3359 locked: function() {
3363 // Call all callbacks with the given context and arguments
3364 fireWith: function( context, args ) {
3367 args = [ context, args.slice ? args.slice() : args ];
3376 // Call all the callbacks with the given arguments
3378 self.fireWith( this, arguments );
3382 // To know if the callbacks have already been called at least once
3392 function Identity( v ) {
3395 function Thrower( ex ) {
3399 function adoptValue( value, resolve, reject ) {
3404 // Check for promise aspect first to privilege synchronous behavior
3405 if ( value && jQuery.isFunction( ( method = value.promise ) ) ) {
3406 method.call( value ).done( resolve ).fail( reject );
3409 } else if ( value && jQuery.isFunction( ( method = value.then ) ) ) {
3410 method.call( value, resolve, reject );
3412 // Other non-thenables
3415 // Support: Android 4.0 only
3416 // Strict mode functions invoked without .call/.apply get global-object context
3417 resolve.call( undefined, value );
3420 // For Promises/A+, convert exceptions into rejections
3421 // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
3422 // Deferred#then to conditionally suppress rejection.
3425 // Support: Android 4.0 only
3426 // Strict mode functions invoked without .call/.apply get global-object context
3427 reject.call( undefined, value );
3433 Deferred: function( func ) {
3436 // action, add listener, callbacks,
3437 // ... .then handlers, argument index, [final state]
3438 [ "notify", "progress", jQuery.Callbacks( "memory" ),
3439 jQuery.Callbacks( "memory" ), 2 ],
3440 [ "resolve", "done", jQuery.Callbacks( "once memory" ),
3441 jQuery.Callbacks( "once memory" ), 0, "resolved" ],
3442 [ "reject", "fail", jQuery.Callbacks( "once memory" ),
3443 jQuery.Callbacks( "once memory" ), 1, "rejected" ]
3450 always: function() {
3451 deferred.done( arguments ).fail( arguments );
3454 "catch": function( fn ) {
3455 return promise.then( null, fn );
3458 // Keep pipe for back-compat
3459 pipe: function( /* fnDone, fnFail, fnProgress */ ) {
3460 var fns = arguments;
3462 return jQuery.Deferred( function( newDefer ) {
3463 jQuery.each( tuples, function( i, tuple ) {
3465 // Map tuples (progress, done, fail) to arguments (done, fail, progress)
3466 var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];
3468 // deferred.progress(function() { bind to newDefer or newDefer.notify })
3469 // deferred.done(function() { bind to newDefer or newDefer.resolve })
3470 // deferred.fail(function() { bind to newDefer or newDefer.reject })
3471 deferred[ tuple[ 1 ] ]( function() {
3472 var returned = fn && fn.apply( this, arguments );
3473 if ( returned && jQuery.isFunction( returned.promise ) ) {
3475 .progress( newDefer.notify )
3476 .done( newDefer.resolve )
3477 .fail( newDefer.reject );
3479 newDefer[ tuple[ 0 ] + "With" ](
3481 fn ? [ returned ] : arguments
3489 then: function( onFulfilled, onRejected, onProgress ) {
3491 function resolve( depth, deferred, handler, special ) {
3495 mightThrow = function() {
3498 // Support: Promises/A+ section 2.3.3.3.3
3499 // https://promisesaplus.com/#point-59
3500 // Ignore double-resolution attempts
3501 if ( depth < maxDepth ) {
3505 returned = handler.apply( that, args );
3507 // Support: Promises/A+ section 2.3.1
3508 // https://promisesaplus.com/#point-48
3509 if ( returned === deferred.promise() ) {
3510 throw new TypeError( "Thenable self-resolution" );
3513 // Support: Promises/A+ sections 2.3.3.1, 3.5
3514 // https://promisesaplus.com/#point-54
3515 // https://promisesaplus.com/#point-75
3516 // Retrieve `then` only once
3519 // Support: Promises/A+ section 2.3.4
3520 // https://promisesaplus.com/#point-64
3521 // Only check objects and functions for thenability
3522 ( typeof returned === "object" ||
3523 typeof returned === "function" ) &&
3526 // Handle a returned thenable
3527 if ( jQuery.isFunction( then ) ) {
3529 // Special processors (notify) just wait for resolution
3533 resolve( maxDepth, deferred, Identity, special ),
3534 resolve( maxDepth, deferred, Thrower, special )
3537 // Normal processors (resolve) also hook into progress
3540 // ...and disregard older resolution values
3545 resolve( maxDepth, deferred, Identity, special ),
3546 resolve( maxDepth, deferred, Thrower, special ),
3547 resolve( maxDepth, deferred, Identity,
3548 deferred.notifyWith )
3552 // Handle all other returned values
3555 // Only substitute handlers pass on context
3556 // and multiple values (non-spec behavior)
3557 if ( handler !== Identity ) {
3559 args = [ returned ];
3562 // Process the value(s)
3563 // Default process is resolve
3564 ( special || deferred.resolveWith )( that, args );
3568 // Only normal processors (resolve) catch and reject exceptions
3576 if ( jQuery.Deferred.exceptionHook ) {
3577 jQuery.Deferred.exceptionHook( e,
3578 process.stackTrace );
3581 // Support: Promises/A+ section 2.3.3.3.4.1
3582 // https://promisesaplus.com/#point-61
3583 // Ignore post-resolution exceptions
3584 if ( depth + 1 >= maxDepth ) {
3586 // Only substitute handlers pass on context
3587 // and multiple values (non-spec behavior)
3588 if ( handler !== Thrower ) {
3593 deferred.rejectWith( that, args );
3598 // Support: Promises/A+ section 2.3.3.3.1
3599 // https://promisesaplus.com/#point-57
3600 // Re-resolve promises immediately to dodge false rejection from
3601 // subsequent errors
3606 // Call an optional hook to record the stack, in case of exception
3607 // since it's otherwise lost when execution goes async
3608 if ( jQuery.Deferred.getStackHook ) {
3609 process.stackTrace = jQuery.Deferred.getStackHook();
3611 window.setTimeout( process );
3616 return jQuery.Deferred( function( newDefer ) {
3618 // progress_handlers.add( ... )
3619 tuples[ 0 ][ 3 ].add(
3623 jQuery.isFunction( onProgress ) ?
3630 // fulfilled_handlers.add( ... )
3631 tuples[ 1 ][ 3 ].add(
3635 jQuery.isFunction( onFulfilled ) ?
3641 // rejected_handlers.add( ... )
3642 tuples[ 2 ][ 3 ].add(
3646 jQuery.isFunction( onRejected ) ?
3654 // Get a promise for this deferred
3655 // If obj is provided, the promise aspect is added to the object
3656 promise: function( obj ) {
3657 return obj != null ? jQuery.extend( obj, promise ) : promise;
3662 // Add list-specific methods
3663 jQuery.each( tuples, function( i, tuple ) {
3664 var list = tuple[ 2 ],
3665 stateString = tuple[ 5 ];
3667 // promise.progress = list.add
3668 // promise.done = list.add
3669 // promise.fail = list.add
3670 promise[ tuple[ 1 ] ] = list.add;
3673 if ( stateString ) {
3677 // state = "resolved" (i.e., fulfilled)
3678 // state = "rejected"
3679 state = stateString;
3682 // rejected_callbacks.disable
3683 // fulfilled_callbacks.disable
3684 tuples[ 3 - i ][ 2 ].disable,
3686 // progress_callbacks.lock
3687 tuples[ 0 ][ 2 ].lock
3691 // progress_handlers.fire
3692 // fulfilled_handlers.fire
3693 // rejected_handlers.fire
3694 list.add( tuple[ 3 ].fire );
3696 // deferred.notify = function() { deferred.notifyWith(...) }
3697 // deferred.resolve = function() { deferred.resolveWith(...) }
3698 // deferred.reject = function() { deferred.rejectWith(...) }
3699 deferred[ tuple[ 0 ] ] = function() {
3700 deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments );
3704 // deferred.notifyWith = list.fireWith
3705 // deferred.resolveWith = list.fireWith
3706 // deferred.rejectWith = list.fireWith
3707 deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
3710 // Make the deferred a promise
3711 promise.promise( deferred );
3713 // Call given func if any
3715 func.call( deferred, deferred );
3723 when: function( singleValue ) {
3726 // count of uncompleted subordinates
3727 remaining = arguments.length,
3729 // count of unprocessed arguments
3732 // subordinate fulfillment data
3733 resolveContexts = Array( i ),
3734 resolveValues = slice.call( arguments ),
3736 // the master Deferred
3737 master = jQuery.Deferred(),
3739 // subordinate callback factory
3740 updateFunc = function( i ) {
3741 return function( value ) {
3742 resolveContexts[ i ] = this;
3743 resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
3744 if ( !( --remaining ) ) {
3745 master.resolveWith( resolveContexts, resolveValues );
3750 // Single- and empty arguments are adopted like Promise.resolve
3751 if ( remaining <= 1 ) {
3752 adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject );
3754 // Use .then() to unwrap secondary thenables (cf. gh-3000)
3755 if ( master.state() === "pending" ||
3756 jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {
3758 return master.then();
3762 // Multiple arguments are aggregated like Promise.all array elements
3764 adoptValue( resolveValues[ i ], updateFunc( i ), master.reject );
3767 return master.promise();
3772 // These usually indicate a programmer mistake during development,
3773 // warn about them ASAP rather than swallowing them by default.
3774 var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;
3776 jQuery.Deferred.exceptionHook = function( error, stack ) {
3778 // Support: IE 8 - 9 only
3779 // Console exists when dev tools are open, which can happen at any time
3780 if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) {
3781 window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack );
3788 jQuery.readyException = function( error ) {
3789 window.setTimeout( function() {
3797 // The deferred used on DOM ready
3798 var readyList = jQuery.Deferred();
3800 jQuery.fn.ready = function( fn ) {
3805 // Wrap jQuery.readyException in a function so that the lookup
3806 // happens at the time of error handling instead of callback
3808 .catch( function( error ) {
3809 jQuery.readyException( error );
3817 // Is the DOM ready to be used? Set to true once it occurs.
3820 // A counter to track how many items to wait for before
3821 // the ready event fires. See #6781
3824 // Hold (or release) the ready event
3825 holdReady: function( hold ) {
3829 jQuery.ready( true );
3833 // Handle when the DOM is ready
3834 ready: function( wait ) {
3836 // Abort if there are pending holds or we're already ready
3837 if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
3841 // Remember that the DOM is ready
3842 jQuery.isReady = true;
3844 // If a normal DOM Ready event fired, decrement, and wait if need be
3845 if ( wait !== true && --jQuery.readyWait > 0 ) {
3849 // If there are functions bound, to execute
3850 readyList.resolveWith( document, [ jQuery ] );
3854 jQuery.ready.then = readyList.then;
3856 // The ready event handler and self cleanup method
3857 function completed() {
3858 document.removeEventListener( "DOMContentLoaded", completed );
3859 window.removeEventListener( "load", completed );
3863 // Catch cases where $(document).ready() is called
3864 // after the browser event has already occurred.
3865 // Support: IE <=9 - 10 only
3866 // Older IE sometimes signals "interactive" too soon
3867 if ( document.readyState === "complete" ||
3868 ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
3870 // Handle it asynchronously to allow scripts the opportunity to delay ready
3871 window.setTimeout( jQuery.ready );
3875 // Use the handy event callback
3876 document.addEventListener( "DOMContentLoaded", completed );
3878 // A fallback to window.onload, that will always work
3879 window.addEventListener( "load", completed );
3885 // Multifunctional method to get and set values of a collection
3886 // The value/s can optionally be executed if it's a function
3887 var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
3893 if ( jQuery.type( key ) === "object" ) {
3896 access( elems, fn, i, key[ i ], true, emptyGet, raw );
3900 } else if ( value !== undefined ) {
3903 if ( !jQuery.isFunction( value ) ) {
3909 // Bulk operations run against the entire set
3911 fn.call( elems, value );
3914 // ...except when executing function values
3917 fn = function( elem, key, value ) {
3918 return bulk.call( jQuery( elem ), value );
3924 for ( ; i < len; i++ ) {
3926 elems[ i ], key, raw ?
3928 value.call( elems[ i ], i, fn( elems[ i ], key ) )
3940 len ? fn( elems[ 0 ], key ) : emptyGet;
3942 var acceptData = function( owner ) {
3946 // - Node.ELEMENT_NODE
3947 // - Node.DOCUMENT_NODE
3950 return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
3957 this.expando = jQuery.expando + Data.uid++;
3964 cache: function( owner ) {
3966 // Check if the owner object already has a cache
3967 var value = owner[ this.expando ];
3969 // If not, create one
3973 // We can accept data for non-element nodes in modern browsers,
3974 // but we should not, see #8335.
3975 // Always return an empty object.
3976 if ( acceptData( owner ) ) {
3978 // If it is a node unlikely to be stringify-ed or looped over
3979 // use plain assignment
3980 if ( owner.nodeType ) {
3981 owner[ this.expando ] = value;
3983 // Otherwise secure it in a non-enumerable property
3984 // configurable must be true to allow the property to be
3985 // deleted when data is removed
3987 Object.defineProperty( owner, this.expando, {
3997 set: function( owner, data, value ) {
3999 cache = this.cache( owner );
4001 // Handle: [ owner, key, value ] args
4002 // Always use camelCase key (gh-2257)
4003 if ( typeof data === "string" ) {
4004 cache[ jQuery.camelCase( data ) ] = value;
4006 // Handle: [ owner, { properties } ] args
4009 // Copy the properties one-by-one to the cache object
4010 for ( prop in data ) {
4011 cache[ jQuery.camelCase( prop ) ] = data[ prop ];
4016 get: function( owner, key ) {
4017 return key === undefined ?
4018 this.cache( owner ) :
4020 // Always use camelCase key (gh-2257)
4021 owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ];
4023 access: function( owner, key, value ) {
4025 // In cases where either:
4027 // 1. No key was specified
4028 // 2. A string key was specified, but no value provided
4030 // Take the "read" path and allow the get method to determine
4031 // which value to return, respectively either:
4033 // 1. The entire cache object
4034 // 2. The data stored at the key
4036 if ( key === undefined ||
4037 ( ( key && typeof key === "string" ) && value === undefined ) ) {
4039 return this.get( owner, key );
4042 // When the key is not a string, or both a key and value
4043 // are specified, set or extend (existing objects) with either:
4045 // 1. An object of properties
4046 // 2. A key and value
4048 this.set( owner, key, value );
4050 // Since the "set" path can have two possible entry points
4051 // return the expected data based on which path was taken[*]
4052 return value !== undefined ? value : key;
4054 remove: function( owner, key ) {
4056 cache = owner[ this.expando ];
4058 if ( cache === undefined ) {
4062 if ( key !== undefined ) {
4064 // Support array or space separated string of keys
4065 if ( jQuery.isArray( key ) ) {
4067 // If key is an array of keys...
4068 // We always set camelCase keys, so remove that.
4069 key = key.map( jQuery.camelCase );
4071 key = jQuery.camelCase( key );
4073 // If a key with the spaces exists, use it.
4074 // Otherwise, create an array by matching non-whitespace
4075 key = key in cache ?
4077 ( key.match( rnotwhite ) || [] );
4083 delete cache[ key[ i ] ];
4087 // Remove the expando if there's no more data
4088 if ( key === undefined || jQuery.isEmptyObject( cache ) ) {
4090 // Support: Chrome <=35 - 45
4091 // Webkit & Blink performance suffers when deleting properties
4092 // from DOM nodes, so set to undefined instead
4093 // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
4094 if ( owner.nodeType ) {
4095 owner[ this.expando ] = undefined;
4097 delete owner[ this.expando ];
4101 hasData: function( owner ) {
4102 var cache = owner[ this.expando ];
4103 return cache !== undefined && !jQuery.isEmptyObject( cache );
4106 var dataPriv = new Data();
4108 var dataUser = new Data();
4112 // Implementation Summary
4114 // 1. Enforce API surface and semantic compatibility with 1.9.x branch
4115 // 2. Improve the module's maintainability by reducing the storage
4116 // paths to a single mechanism.
4117 // 3. Use the same single mechanism to support "private" and "user" data.
4118 // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
4119 // 5. Avoid exposing implementation details on user objects (eg. expando properties)
4120 // 6. Provide a clear path for implementation upgrade to WeakMap in 2014
4122 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
4123 rmultiDash = /[A-Z]/g;
4125 function dataAttr( elem, key, data ) {
4128 // If nothing was found internally, try to fetch any
4129 // data from the HTML5 data-* attribute
4130 if ( data === undefined && elem.nodeType === 1 ) {
4131 name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase();
4132 data = elem.getAttribute( name );
4134 if ( typeof data === "string" ) {
4136 data = data === "true" ? true :
4137 data === "false" ? false :
4138 data === "null" ? null :
4140 // Only convert to a number if it doesn't change the string
4141 +data + "" === data ? +data :
4142 rbrace.test( data ) ? JSON.parse( data ) :
4146 // Make sure we set the data so it isn't changed later
4147 dataUser.set( elem, key, data );
4156 hasData: function( elem ) {
4157 return dataUser.hasData( elem ) || dataPriv.hasData( elem );
4160 data: function( elem, name, data ) {
4161 return dataUser.access( elem, name, data );
4164 removeData: function( elem, name ) {
4165 dataUser.remove( elem, name );
4168 // TODO: Now that all calls to _data and _removeData have been replaced
4169 // with direct calls to dataPriv methods, these can be deprecated.
4170 _data: function( elem, name, data ) {
4171 return dataPriv.access( elem, name, data );
4174 _removeData: function( elem, name ) {
4175 dataPriv.remove( elem, name );
4180 data: function( key, value ) {
4183 attrs = elem && elem.attributes;
4186 if ( key === undefined ) {
4187 if ( this.length ) {
4188 data = dataUser.get( elem );
4190 if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
4194 // Support: IE 11 only
4195 // The attrs elements can be null (#14894)
4197 name = attrs[ i ].name;
4198 if ( name.indexOf( "data-" ) === 0 ) {
4199 name = jQuery.camelCase( name.slice( 5 ) );
4200 dataAttr( elem, name, data[ name ] );
4204 dataPriv.set( elem, "hasDataAttrs", true );
4211 // Sets multiple values
4212 if ( typeof key === "object" ) {
4213 return this.each( function() {
4214 dataUser.set( this, key );
4218 return access( this, function( value ) {
4221 // The calling jQuery object (element matches) is not empty
4222 // (and therefore has an element appears at this[ 0 ]) and the
4223 // `value` parameter was not undefined. An empty jQuery object
4224 // will result in `undefined` for elem = this[ 0 ] which will
4225 // throw an exception if an attempt to read a data cache is made.
4226 if ( elem && value === undefined ) {
4228 // Attempt to get data from the cache
4229 // The key will always be camelCased in Data
4230 data = dataUser.get( elem, key );
4231 if ( data !== undefined ) {
4235 // Attempt to "discover" the data in
4236 // HTML5 custom data-* attrs
4237 data = dataAttr( elem, key );
4238 if ( data !== undefined ) {
4242 // We tried really hard, but the data doesn't exist.
4247 this.each( function() {
4249 // We always store the camelCased key
4250 dataUser.set( this, key, value );
4252 }, null, value, arguments.length > 1, null, true );
4255 removeData: function( key ) {
4256 return this.each( function() {
4257 dataUser.remove( this, key );
4264 queue: function( elem, type, data ) {
4268 type = ( type || "fx" ) + "queue";
4269 queue = dataPriv.get( elem, type );
4271 // Speed up dequeue by getting out quickly if this is just a lookup
4273 if ( !queue || jQuery.isArray( data ) ) {
4274 queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
4283 dequeue: function( elem, type ) {
4284 type = type || "fx";
4286 var queue = jQuery.queue( elem, type ),
4287 startLength = queue.length,
4289 hooks = jQuery._queueHooks( elem, type ),
4291 jQuery.dequeue( elem, type );
4294 // If the fx queue is dequeued, always remove the progress sentinel
4295 if ( fn === "inprogress" ) {
4302 // Add a progress sentinel to prevent the fx queue from being
4303 // automatically dequeued
4304 if ( type === "fx" ) {
4305 queue.unshift( "inprogress" );
4308 // Clear up the last queue stop function
4310 fn.call( elem, next, hooks );
4313 if ( !startLength && hooks ) {
4318 // Not public - generate a queueHooks object, or return the current one
4319 _queueHooks: function( elem, type ) {
4320 var key = type + "queueHooks";
4321 return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
4322 empty: jQuery.Callbacks( "once memory" ).add( function() {
4323 dataPriv.remove( elem, [ type + "queue", key ] );
4330 queue: function( type, data ) {
4333 if ( typeof type !== "string" ) {
4339 if ( arguments.length < setter ) {
4340 return jQuery.queue( this[ 0 ], type );
4343 return data === undefined ?
4345 this.each( function() {
4346 var queue = jQuery.queue( this, type, data );
4348 // Ensure a hooks for this queue
4349 jQuery._queueHooks( this, type );
4351 if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
4352 jQuery.dequeue( this, type );
4356 dequeue: function( type ) {
4357 return this.each( function() {
4358 jQuery.dequeue( this, type );
4361 clearQueue: function( type ) {
4362 return this.queue( type || "fx", [] );
4365 // Get a promise resolved when queues of a certain type
4366 // are emptied (fx is the type by default)
4367 promise: function( type, obj ) {
4370 defer = jQuery.Deferred(),
4373 resolve = function() {
4374 if ( !( --count ) ) {
4375 defer.resolveWith( elements, [ elements ] );
4379 if ( typeof type !== "string" ) {
4383 type = type || "fx";
4386 tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
4387 if ( tmp && tmp.empty ) {
4389 tmp.empty.add( resolve );
4393 return defer.promise( obj );
4396 var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
4398 var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
4401 var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
4403 var isHiddenWithinTree = function( elem, el ) {
4405 // isHiddenWithinTree might be called from jQuery#filter function;
4406 // in that case, element will be second argument
4409 // Inline style trumps all
4410 return elem.style.display === "none" ||
4411 elem.style.display === "" &&
4413 // Otherwise, check computed style
4414 // Support: Firefox <=43 - 45
4415 // Disconnected elements can have computed display: none, so first confirm that elem is
4417 jQuery.contains( elem.ownerDocument, elem ) &&
4419 jQuery.css( elem, "display" ) === "none";
4422 var swap = function( elem, options, callback, args ) {
4426 // Remember the old values, and insert the new ones
4427 for ( name in options ) {
4428 old[ name ] = elem.style[ name ];
4429 elem.style[ name ] = options[ name ];
4432 ret = callback.apply( elem, args || [] );
4434 // Revert the old values
4435 for ( name in options ) {
4436 elem.style[ name ] = old[ name ];
4445 function adjustCSS( elem, prop, valueParts, tween ) {
4449 currentValue = tween ?
4454 return jQuery.css( elem, prop, "" );
4456 initial = currentValue(),
4457 unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
4459 // Starting value computation is required for potential unit mismatches
4460 initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
4461 rcssNum.exec( jQuery.css( elem, prop ) );
4463 if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
4465 // Trust units reported by jQuery.css
4466 unit = unit || initialInUnit[ 3 ];
4468 // Make sure we update the tween properties later on
4469 valueParts = valueParts || [];
4471 // Iteratively approximate from a nonzero starting point
4472 initialInUnit = +initial || 1;
4476 // If previous iteration zeroed out, double until we get *something*.
4477 // Use string for doubling so we don't accidentally see scale as unchanged below
4478 scale = scale || ".5";
4481 initialInUnit = initialInUnit / scale;
4482 jQuery.style( elem, prop, initialInUnit + unit );
4484 // Update scale, tolerating zero or NaN from tween.cur()
4485 // Break the loop if scale is unchanged or perfect, or if we've just had enough.
4487 scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations
4492 initialInUnit = +initialInUnit || +initial || 0;
4494 // Apply relative offset (+=/-=) if specified
4495 adjusted = valueParts[ 1 ] ?
4496 initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
4500 tween.start = initialInUnit;
4501 tween.end = adjusted;
4508 var defaultDisplayMap = {};
4510 function getDefaultDisplay( elem ) {
4512 doc = elem.ownerDocument,
4513 nodeName = elem.nodeName,
4514 display = defaultDisplayMap[ nodeName ];
4520 temp = doc.body.appendChild( doc.createElement( nodeName ) ),
4521 display = jQuery.css( temp, "display" );
4523 temp.parentNode.removeChild( temp );
4525 if ( display === "none" ) {
4528 defaultDisplayMap[ nodeName ] = display;
4533 function showHide( elements, show ) {
4537 length = elements.length;
4539 // Determine new display value for elements that need to change
4540 for ( ; index < length; index++ ) {
4541 elem = elements[ index ];
4542 if ( !elem.style ) {
4546 display = elem.style.display;
4549 // Since we force visibility upon cascade-hidden elements, an immediate (and slow)
4550 // check is required in this first loop unless we have a nonempty display value (either
4551 // inline or about-to-be-restored)
4552 if ( display === "none" ) {
4553 values[ index ] = dataPriv.get( elem, "display" ) || null;
4554 if ( !values[ index ] ) {
4555 elem.style.display = "";
4558 if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
4559 values[ index ] = getDefaultDisplay( elem );
4562 if ( display !== "none" ) {
4563 values[ index ] = "none";
4565 // Remember what we're overwriting
4566 dataPriv.set( elem, "display", display );
4571 // Set the display of the elements in a second loop to avoid constant reflow
4572 for ( index = 0; index < length; index++ ) {
4573 if ( values[ index ] != null ) {
4574 elements[ index ].style.display = values[ index ];
4583 return showHide( this, true );
4586 return showHide( this );
4588 toggle: function( state ) {
4589 if ( typeof state === "boolean" ) {
4590 return state ? this.show() : this.hide();
4593 return this.each( function() {
4594 if ( isHiddenWithinTree( this ) ) {
4595 jQuery( this ).show();
4597 jQuery( this ).hide();
4602 var rcheckableType = ( /^(?:checkbox|radio)$/i );
4604 var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i );
4606 var rscriptType = ( /^$|\/(?:java|ecma)script/i );
4610 // We have to close these tags to support XHTML (#13200)
4613 // Support: IE <=9 only
4614 option: [ 1, "<select multiple='multiple'>", "</select>" ],
4616 // XHTML parsers do not magically insert elements in the
4617 // same way that tag soup parsers do. So we cannot shorten
4618 // this by omitting <tbody> or other required elements.
4619 thead: [ 1, "<table>", "</table>" ],
4620 col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
4621 tr: [ 2, "<table><tbody>", "</tbody></table>" ],
4622 td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
4624 _default: [ 0, "", "" ]
4627 // Support: IE <=9 only
4628 wrapMap.optgroup = wrapMap.option;
4630 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
4631 wrapMap.th = wrapMap.td;
4634 function getAll( context, tag ) {
4636 // Support: IE <=9 - 11 only
4637 // Use typeof to avoid zero-argument method invocation on host objects (#15151)
4638 var ret = typeof context.getElementsByTagName !== "undefined" ?
4639 context.getElementsByTagName( tag || "*" ) :
4640 typeof context.querySelectorAll !== "undefined" ?
4641 context.querySelectorAll( tag || "*" ) :
4644 return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
4645 jQuery.merge( [ context ], ret ) :
4650 // Mark scripts as having already been evaluated
4651 function setGlobalEval( elems, refElements ) {
4655 for ( ; i < l; i++ ) {
4659 !refElements || dataPriv.get( refElements[ i ], "globalEval" )
4665 var rhtml = /<|&#?\w+;/;
4667 function buildFragment( elems, context, scripts, selection, ignored ) {
4668 var elem, tmp, tag, wrap, contains, j,
4669 fragment = context.createDocumentFragment(),
4674 for ( ; i < l; i++ ) {
4677 if ( elem || elem === 0 ) {
4679 // Add nodes directly
4680 if ( jQuery.type( elem ) === "object" ) {
4682 // Support: Android <=4.0 only, PhantomJS 1 only
4683 // push.apply(_, arraylike) throws on ancient WebKit
4684 jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
4686 // Convert non-html into a text node
4687 } else if ( !rhtml.test( elem ) ) {
4688 nodes.push( context.createTextNode( elem ) );
4690 // Convert html into DOM nodes
4692 tmp = tmp || fragment.appendChild( context.createElement( "div" ) );
4694 // Deserialize a standard representation
4695 tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
4696 wrap = wrapMap[ tag ] || wrapMap._default;
4697 tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];
4699 // Descend through wrappers to the right content
4702 tmp = tmp.lastChild;
4705 // Support: Android <=4.0 only, PhantomJS 1 only
4706 // push.apply(_, arraylike) throws on ancient WebKit
4707 jQuery.merge( nodes, tmp.childNodes );
4709 // Remember the top-level container
4710 tmp = fragment.firstChild;
4712 // Ensure the created nodes are orphaned (#12392)
4713 tmp.textContent = "";
4718 // Remove wrapper from fragment
4719 fragment.textContent = "";
4722 while ( ( elem = nodes[ i++ ] ) ) {
4724 // Skip elements already in the context collection (trac-4087)
4725 if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
4727 ignored.push( elem );
4732 contains = jQuery.contains( elem.ownerDocument, elem );
4734 // Append to fragment
4735 tmp = getAll( fragment.appendChild( elem ), "script" );
4737 // Preserve script evaluation history
4739 setGlobalEval( tmp );
4742 // Capture executables
4745 while ( ( elem = tmp[ j++ ] ) ) {
4746 if ( rscriptType.test( elem.type || "" ) ) {
4747 scripts.push( elem );
4758 var fragment = document.createDocumentFragment(),
4759 div = fragment.appendChild( document.createElement( "div" ) ),
4760 input = document.createElement( "input" );
4762 // Support: Android 4.0 - 4.3 only
4763 // Check state lost if the name is set (#11217)
4764 // Support: Windows Web Apps (WWA)
4765 // `name` and `type` must use .setAttribute for WWA (#14901)
4766 input.setAttribute( "type", "radio" );
4767 input.setAttribute( "checked", "checked" );
4768 input.setAttribute( "name", "t" );
4770 div.appendChild( input );
4772 // Support: Android <=4.1 only
4773 // Older WebKit doesn't clone checked state correctly in fragments
4774 support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
4776 // Support: IE <=11 only
4777 // Make sure textarea (and checkbox) defaultValue is properly cloned
4778 div.innerHTML = "<textarea>x</textarea>";
4779 support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
4781 var documentElement = document.documentElement;
4787 rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
4788 rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
4790 function returnTrue() {
4794 function returnFalse() {
4798 // Support: IE <=9 only
4799 // See #13393 for more info
4800 function safeActiveElement() {
4802 return document.activeElement;
4806 function on( elem, types, selector, data, fn, one ) {
4809 // Types can be a map of types/handlers
4810 if ( typeof types === "object" ) {
4812 // ( types-Object, selector, data )
4813 if ( typeof selector !== "string" ) {
4815 // ( types-Object, data )
4816 data = data || selector;
4817 selector = undefined;
4819 for ( type in types ) {
4820 on( elem, type, selector, data, types[ type ], one );
4825 if ( data == null && fn == null ) {
4829 data = selector = undefined;
4830 } else if ( fn == null ) {
4831 if ( typeof selector === "string" ) {
4833 // ( types, selector, fn )
4838 // ( types, data, fn )
4841 selector = undefined;
4844 if ( fn === false ) {
4852 fn = function( event ) {
4854 // Can use an empty set, since event contains the info
4855 jQuery().off( event );
4856 return origFn.apply( this, arguments );
4859 // Use same guid so caller can remove using origFn
4860 fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
4862 return elem.each( function() {
4863 jQuery.event.add( this, types, fn, data, selector );
4868 * Helper functions for managing events -- not part of the public interface.
4869 * Props to Dean Edwards' addEvent library for many of the ideas.
4875 add: function( elem, types, handler, data, selector ) {
4877 var handleObjIn, eventHandle, tmp,
4878 events, t, handleObj,
4879 special, handlers, type, namespaces, origType,
4880 elemData = dataPriv.get( elem );
4882 // Don't attach events to noData or text/comment nodes (but allow plain objects)
4887 // Caller can pass in an object of custom data in lieu of the handler
4888 if ( handler.handler ) {
4889 handleObjIn = handler;
4890 handler = handleObjIn.handler;
4891 selector = handleObjIn.selector;
4894 // Ensure that invalid selectors throw exceptions at attach time
4895 // Evaluate against documentElement in case elem is a non-element node (e.g., document)
4897 jQuery.find.matchesSelector( documentElement, selector );
4900 // Make sure that the handler has a unique ID, used to find/remove it later
4901 if ( !handler.guid ) {
4902 handler.guid = jQuery.guid++;
4905 // Init the element's event structure and main handler, if this is the first
4906 if ( !( events = elemData.events ) ) {
4907 events = elemData.events = {};
4909 if ( !( eventHandle = elemData.handle ) ) {
4910 eventHandle = elemData.handle = function( e ) {
4912 // Discard the second event of a jQuery.event.trigger() and
4913 // when an event is called after a page has unloaded
4914 return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
4915 jQuery.event.dispatch.apply( elem, arguments ) : undefined;
4919 // Handle multiple events separated by a space
4920 types = ( types || "" ).match( rnotwhite ) || [ "" ];
4923 tmp = rtypenamespace.exec( types[ t ] ) || [];
4924 type = origType = tmp[ 1 ];
4925 namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
4927 // There *must* be a type, no attaching namespace-only handlers
4932 // If event changes its type, use the special event handlers for the changed type
4933 special = jQuery.event.special[ type ] || {};
4935 // If selector defined, determine special event api type, otherwise given type
4936 type = ( selector ? special.delegateType : special.bindType ) || type;
4938 // Update special based on newly reset type
4939 special = jQuery.event.special[ type ] || {};
4941 // handleObj is passed to all event handlers
4942 handleObj = jQuery.extend( {
4949 needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
4950 namespace: namespaces.join( "." )
4953 // Init the event handler queue if we're the first
4954 if ( !( handlers = events[ type ] ) ) {
4955 handlers = events[ type ] = [];
4956 handlers.delegateCount = 0;
4958 // Only use addEventListener if the special events handler returns false
4959 if ( !special.setup ||
4960 special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
4962 if ( elem.addEventListener ) {
4963 elem.addEventListener( type, eventHandle );
4968 if ( special.add ) {
4969 special.add.call( elem, handleObj );
4971 if ( !handleObj.handler.guid ) {
4972 handleObj.handler.guid = handler.guid;
4976 // Add to the element's handler list, delegates in front
4978 handlers.splice( handlers.delegateCount++, 0, handleObj );
4980 handlers.push( handleObj );
4983 // Keep track of which events have ever been used, for event optimization
4984 jQuery.event.global[ type ] = true;
4989 // Detach an event or set of events from an element
4990 remove: function( elem, types, handler, selector, mappedTypes ) {
4992 var j, origCount, tmp,
4993 events, t, handleObj,
4994 special, handlers, type, namespaces, origType,
4995 elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );
4997 if ( !elemData || !( events = elemData.events ) ) {
5001 // Once for each type.namespace in types; type may be omitted
5002 types = ( types || "" ).match( rnotwhite ) || [ "" ];
5005 tmp = rtypenamespace.exec( types[ t ] ) || [];
5006 type = origType = tmp[ 1 ];
5007 namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
5009 // Unbind all events (on this namespace, if provided) for the element
5011 for ( type in events ) {
5012 jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
5017 special = jQuery.event.special[ type ] || {};
5018 type = ( selector ? special.delegateType : special.bindType ) || type;
5019 handlers = events[ type ] || [];
5021 new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );
5023 // Remove matching events
5024 origCount = j = handlers.length;
5026 handleObj = handlers[ j ];
5028 if ( ( mappedTypes || origType === handleObj.origType ) &&
5029 ( !handler || handler.guid === handleObj.guid ) &&
5030 ( !tmp || tmp.test( handleObj.namespace ) ) &&
5031 ( !selector || selector === handleObj.selector ||
5032 selector === "**" && handleObj.selector ) ) {
5033 handlers.splice( j, 1 );
5035 if ( handleObj.selector ) {
5036 handlers.delegateCount--;
5038 if ( special.remove ) {
5039 special.remove.call( elem, handleObj );
5044 // Remove generic event handler if we removed something and no more handlers exist
5045 // (avoids potential for endless recursion during removal of special event handlers)
5046 if ( origCount && !handlers.length ) {
5047 if ( !special.teardown ||
5048 special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
5050 jQuery.removeEvent( elem, type, elemData.handle );
5053 delete events[ type ];
5057 // Remove data and the expando if it's no longer used
5058 if ( jQuery.isEmptyObject( events ) ) {
5059 dataPriv.remove( elem, "handle events" );
5063 dispatch: function( nativeEvent ) {
5065 // Make a writable jQuery.Event from the native event object
5066 var event = jQuery.event.fix( nativeEvent );
5068 var i, j, ret, matched, handleObj, handlerQueue,
5069 args = new Array( arguments.length ),
5070 handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [],
5071 special = jQuery.event.special[ event.type ] || {};
5073 // Use the fix-ed jQuery.Event rather than the (read-only) native event
5076 for ( i = 1; i < arguments.length; i++ ) {
5077 args[ i ] = arguments[ i ];
5080 event.delegateTarget = this;
5082 // Call the preDispatch hook for the mapped type, and let it bail if desired
5083 if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
5087 // Determine handlers
5088 handlerQueue = jQuery.event.handlers.call( this, event, handlers );
5090 // Run delegates first; they may want to stop propagation beneath us
5092 while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
5093 event.currentTarget = matched.elem;
5096 while ( ( handleObj = matched.handlers[ j++ ] ) &&
5097 !event.isImmediatePropagationStopped() ) {
5099 // Triggered event must either 1) have no namespace, or 2) have namespace(s)
5100 // a subset or equal to those in the bound event (both can have no namespace).
5101 if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) {
5103 event.handleObj = handleObj;
5104 event.data = handleObj.data;
5106 ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
5107 handleObj.handler ).apply( matched.elem, args );
5109 if ( ret !== undefined ) {
5110 if ( ( event.result = ret ) === false ) {
5111 event.preventDefault();
5112 event.stopPropagation();
5119 // Call the postDispatch hook for the mapped type
5120 if ( special.postDispatch ) {
5121 special.postDispatch.call( this, event );
5124 return event.result;
5127 handlers: function( event, handlers ) {
5128 var i, matches, sel, handleObj,
5130 delegateCount = handlers.delegateCount,
5134 // Find delegate handlers
5135 // Black-hole SVG <use> instance trees (#13180)
5137 // Support: Firefox <=42
5138 // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343)
5139 if ( delegateCount && cur.nodeType &&
5140 ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) {
5142 for ( ; cur !== this; cur = cur.parentNode || this ) {
5144 // Don't check non-elements (#13208)
5145 // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
5146 if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) {
5148 for ( i = 0; i < delegateCount; i++ ) {
5149 handleObj = handlers[ i ];
5151 // Don't conflict with Object.prototype properties (#13203)
5152 sel = handleObj.selector + " ";
5154 if ( matches[ sel ] === undefined ) {
5155 matches[ sel ] = handleObj.needsContext ?
5156 jQuery( sel, this ).index( cur ) > -1 :
5157 jQuery.find( sel, this, null, [ cur ] ).length;
5159 if ( matches[ sel ] ) {
5160 matches.push( handleObj );
5163 if ( matches.length ) {
5164 handlerQueue.push( { elem: cur, handlers: matches } );
5170 // Add the remaining (directly-bound) handlers
5171 if ( delegateCount < handlers.length ) {
5172 handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } );
5175 return handlerQueue;
5178 addProp: function( name, hook ) {
5179 Object.defineProperty( jQuery.Event.prototype, name, {
5183 get: jQuery.isFunction( hook ) ?
5185 if ( this.originalEvent ) {
5186 return hook( this.originalEvent );
5190 if ( this.originalEvent ) {
5191 return this.originalEvent[ name ];
5195 set: function( value ) {
5196 Object.defineProperty( this, name, {
5206 fix: function( originalEvent ) {
5207 return originalEvent[ jQuery.expando ] ?
5209 new jQuery.Event( originalEvent );
5215 // Prevent triggered image.load events from bubbling to window.load
5220 // Fire native event if possible so blur/focus sequence is correct
5221 trigger: function() {
5222 if ( this !== safeActiveElement() && this.focus ) {
5227 delegateType: "focusin"
5230 trigger: function() {
5231 if ( this === safeActiveElement() && this.blur ) {
5236 delegateType: "focusout"
5240 // For checkbox, fire native event so checked state will be right
5241 trigger: function() {
5242 if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
5248 // For cross-browser consistency, don't fire native .click() on links
5249 _default: function( event ) {
5250 return jQuery.nodeName( event.target, "a" );
5255 postDispatch: function( event ) {
5257 // Support: Firefox 20+
5258 // Firefox doesn't alert if the returnValue field is not set.
5259 if ( event.result !== undefined && event.originalEvent ) {
5260 event.originalEvent.returnValue = event.result;
5267 jQuery.removeEvent = function( elem, type, handle ) {
5269 // This "if" is needed for plain objects
5270 if ( elem.removeEventListener ) {
5271 elem.removeEventListener( type, handle );
5275 jQuery.Event = function( src, props ) {
5277 // Allow instantiation without the 'new' keyword
5278 if ( !( this instanceof jQuery.Event ) ) {
5279 return new jQuery.Event( src, props );
5283 if ( src && src.type ) {
5284 this.originalEvent = src;
5285 this.type = src.type;
5287 // Events bubbling up the document may have been marked as prevented
5288 // by a handler lower down the tree; reflect the correct value.
5289 this.isDefaultPrevented = src.defaultPrevented ||
5290 src.defaultPrevented === undefined &&
5292 // Support: Android <=2.3 only
5293 src.returnValue === false ?
5297 // Create target properties
5298 // Support: Safari <=6 - 7 only
5299 // Target should not be a text node (#504, #13143)
5300 this.target = ( src.target && src.target.nodeType === 3 ) ?
5301 src.target.parentNode :
5304 this.currentTarget = src.currentTarget;
5305 this.relatedTarget = src.relatedTarget;
5312 // Put explicitly provided properties onto the event object
5314 jQuery.extend( this, props );
5317 // Create a timestamp if incoming event doesn't have one
5318 this.timeStamp = src && src.timeStamp || jQuery.now();
5321 this[ jQuery.expando ] = true;
5324 // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
5325 // https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
5326 jQuery.Event.prototype = {
5327 constructor: jQuery.Event,
5328 isDefaultPrevented: returnFalse,
5329 isPropagationStopped: returnFalse,
5330 isImmediatePropagationStopped: returnFalse,
5333 preventDefault: function() {
5334 var e = this.originalEvent;
5336 this.isDefaultPrevented = returnTrue;
5338 if ( e && !this.isSimulated ) {
5342 stopPropagation: function() {
5343 var e = this.originalEvent;
5345 this.isPropagationStopped = returnTrue;
5347 if ( e && !this.isSimulated ) {
5348 e.stopPropagation();
5351 stopImmediatePropagation: function() {
5352 var e = this.originalEvent;
5354 this.isImmediatePropagationStopped = returnTrue;
5356 if ( e && !this.isSimulated ) {
5357 e.stopImmediatePropagation();
5360 this.stopPropagation();
5364 // Includes all common event props including KeyEvent and MouseEvent specific props
5369 changedTouches: true,
5392 targetTouches: true,
5396 which: function( event ) {
5397 var button = event.button;
5399 // Add which for key events
5400 if ( event.which == null && rkeyEvent.test( event.type ) ) {
5401 return event.charCode != null ? event.charCode : event.keyCode;
5404 // Add which for click: 1 === left; 2 === middle; 3 === right
5405 if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) {
5406 return ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
5411 }, jQuery.event.addProp );
5413 // Create mouseenter/leave events using mouseover/out and event-time checks
5414 // so that event delegation works in jQuery.
5415 // Do the same for pointerenter/pointerleave and pointerover/pointerout
5417 // Support: Safari 7 only
5418 // Safari sends mouseenter too often; see:
5419 // https://bugs.chromium.org/p/chromium/issues/detail?id=470258
5420 // for the description of the bug (it existed in older Chrome versions as well).
5422 mouseenter: "mouseover",
5423 mouseleave: "mouseout",
5424 pointerenter: "pointerover",
5425 pointerleave: "pointerout"
5426 }, function( orig, fix ) {
5427 jQuery.event.special[ orig ] = {
5431 handle: function( event ) {
5434 related = event.relatedTarget,
5435 handleObj = event.handleObj;
5437 // For mouseenter/leave call the handler if related is outside the target.
5438 // NB: No relatedTarget if the mouse left/entered the browser window
5439 if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
5440 event.type = handleObj.origType;
5441 ret = handleObj.handler.apply( this, arguments );
5451 on: function( types, selector, data, fn ) {
5452 return on( this, types, selector, data, fn );
5454 one: function( types, selector, data, fn ) {
5455 return on( this, types, selector, data, fn, 1 );
5457 off: function( types, selector, fn ) {
5458 var handleObj, type;
5459 if ( types && types.preventDefault && types.handleObj ) {
5461 // ( event ) dispatched jQuery.Event
5462 handleObj = types.handleObj;
5463 jQuery( types.delegateTarget ).off(
5464 handleObj.namespace ?
5465 handleObj.origType + "." + handleObj.namespace :
5472 if ( typeof types === "object" ) {
5474 // ( types-object [, selector] )
5475 for ( type in types ) {
5476 this.off( type, selector, types[ type ] );
5480 if ( selector === false || typeof selector === "function" ) {
5484 selector = undefined;
5486 if ( fn === false ) {
5489 return this.each( function() {
5490 jQuery.event.remove( this, types, fn, selector );
5498 /* eslint-disable max-len */
5500 // See https://github.com/eslint/eslint/issues/3229
5501 rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,
5505 // Support: IE <=10 - 11, Edge 12 - 13
5506 // In IE/Edge using regex groups here causes severe slowdowns.
5507 // See https://connect.microsoft.com/IE/feedback/details/1736512/
5508 rnoInnerhtml = /<script|<style|<link/i,
5510 // checked="checked" or checked
5511 rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
5512 rscriptTypeMasked = /^true\/(.*)/,
5513 rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
5515 function manipulationTarget( elem, content ) {
5516 if ( jQuery.nodeName( elem, "table" ) &&
5517 jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {
5519 return elem.getElementsByTagName( "tbody" )[ 0 ] || elem;
5525 // Replace/restore the type attribute of script elements for safe DOM manipulation
5526 function disableScript( elem ) {
5527 elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
5530 function restoreScript( elem ) {
5531 var match = rscriptTypeMasked.exec( elem.type );
5534 elem.type = match[ 1 ];
5536 elem.removeAttribute( "type" );
5542 function cloneCopyEvent( src, dest ) {
5543 var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
5545 if ( dest.nodeType !== 1 ) {
5549 // 1. Copy private data: events, handlers, etc.
5550 if ( dataPriv.hasData( src ) ) {
5551 pdataOld = dataPriv.access( src );
5552 pdataCur = dataPriv.set( dest, pdataOld );
5553 events = pdataOld.events;
5556 delete pdataCur.handle;
5557 pdataCur.events = {};
5559 for ( type in events ) {
5560 for ( i = 0, l = events[ type ].length; i < l; i++ ) {
5561 jQuery.event.add( dest, type, events[ type ][ i ] );
5567 // 2. Copy user data
5568 if ( dataUser.hasData( src ) ) {
5569 udataOld = dataUser.access( src );
5570 udataCur = jQuery.extend( {}, udataOld );
5572 dataUser.set( dest, udataCur );
5576 // Fix IE bugs, see support tests
5577 function fixInput( src, dest ) {
5578 var nodeName = dest.nodeName.toLowerCase();
5580 // Fails to persist the checked state of a cloned checkbox or radio button.
5581 if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
5582 dest.checked = src.checked;
5584 // Fails to return the selected option to the default selected state when cloning options
5585 } else if ( nodeName === "input" || nodeName === "textarea" ) {
5586 dest.defaultValue = src.defaultValue;
5590 function domManip( collection, args, callback, ignored ) {
5592 // Flatten any nested arrays
5593 args = concat.apply( [], args );
5595 var fragment, first, scripts, hasScripts, node, doc,
5597 l = collection.length,
5600 isFunction = jQuery.isFunction( value );
5602 // We can't cloneNode fragments that contain checked, in WebKit
5604 ( l > 1 && typeof value === "string" &&
5605 !support.checkClone && rchecked.test( value ) ) ) {
5606 return collection.each( function( index ) {
5607 var self = collection.eq( index );
5609 args[ 0 ] = value.call( this, index, self.html() );
5611 domManip( self, args, callback, ignored );
5616 fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
5617 first = fragment.firstChild;
5619 if ( fragment.childNodes.length === 1 ) {
5623 // Require either new content or an interest in ignored elements to invoke the callback
5624 if ( first || ignored ) {
5625 scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
5626 hasScripts = scripts.length;
5628 // Use the original fragment for the last item
5629 // instead of the first because it can end up
5630 // being emptied incorrectly in certain situations (#8070).
5631 for ( ; i < l; i++ ) {
5634 if ( i !== iNoClone ) {
5635 node = jQuery.clone( node, true, true );
5637 // Keep references to cloned scripts for later restoration
5640 // Support: Android <=4.0 only, PhantomJS 1 only
5641 // push.apply(_, arraylike) throws on ancient WebKit
5642 jQuery.merge( scripts, getAll( node, "script" ) );
5646 callback.call( collection[ i ], node, i );
5650 doc = scripts[ scripts.length - 1 ].ownerDocument;
5653 jQuery.map( scripts, restoreScript );
5655 // Evaluate executable scripts on first document insertion
5656 for ( i = 0; i < hasScripts; i++ ) {
5657 node = scripts[ i ];
5658 if ( rscriptType.test( node.type || "" ) &&
5659 !dataPriv.access( node, "globalEval" ) &&
5660 jQuery.contains( doc, node ) ) {
5664 // Optional AJAX dependency, but won't run scripts if not present
5665 if ( jQuery._evalUrl ) {
5666 jQuery._evalUrl( node.src );
5669 DOMEval( node.textContent.replace( rcleanScript, "" ), doc );
5680 function remove( elem, selector, keepData ) {
5682 nodes = selector ? jQuery.filter( selector, elem ) : elem,
5685 for ( ; ( node = nodes[ i ] ) != null; i++ ) {
5686 if ( !keepData && node.nodeType === 1 ) {
5687 jQuery.cleanData( getAll( node ) );
5690 if ( node.parentNode ) {
5691 if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
5692 setGlobalEval( getAll( node, "script" ) );
5694 node.parentNode.removeChild( node );
5702 htmlPrefilter: function( html ) {
5703 return html.replace( rxhtmlTag, "<$1></$2>" );
5706 clone: function( elem, dataAndEvents, deepDataAndEvents ) {
5707 var i, l, srcElements, destElements,
5708 clone = elem.cloneNode( true ),
5709 inPage = jQuery.contains( elem.ownerDocument, elem );
5711 // Fix IE cloning issues
5712 if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
5713 !jQuery.isXMLDoc( elem ) ) {
5715 // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
5716 destElements = getAll( clone );
5717 srcElements = getAll( elem );
5719 for ( i = 0, l = srcElements.length; i < l; i++ ) {
5720 fixInput( srcElements[ i ], destElements[ i ] );
5724 // Copy the events from the original to the clone
5725 if ( dataAndEvents ) {
5726 if ( deepDataAndEvents ) {
5727 srcElements = srcElements || getAll( elem );
5728 destElements = destElements || getAll( clone );
5730 for ( i = 0, l = srcElements.length; i < l; i++ ) {
5731 cloneCopyEvent( srcElements[ i ], destElements[ i ] );
5734 cloneCopyEvent( elem, clone );
5738 // Preserve script evaluation history
5739 destElements = getAll( clone, "script" );
5740 if ( destElements.length > 0 ) {
5741 setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
5744 // Return the cloned set
5748 cleanData: function( elems ) {
5749 var data, elem, type,
5750 special = jQuery.event.special,
5753 for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
5754 if ( acceptData( elem ) ) {
5755 if ( ( data = elem[ dataPriv.expando ] ) ) {
5756 if ( data.events ) {
5757 for ( type in data.events ) {
5758 if ( special[ type ] ) {
5759 jQuery.event.remove( elem, type );
5761 // This is a shortcut to avoid jQuery.event.remove's overhead
5763 jQuery.removeEvent( elem, type, data.handle );
5768 // Support: Chrome <=35 - 45+
5769 // Assign undefined instead of using delete, see Data#remove
5770 elem[ dataPriv.expando ] = undefined;
5772 if ( elem[ dataUser.expando ] ) {
5774 // Support: Chrome <=35 - 45+
5775 // Assign undefined instead of using delete, see Data#remove
5776 elem[ dataUser.expando ] = undefined;
5784 detach: function( selector ) {
5785 return remove( this, selector, true );
5788 remove: function( selector ) {
5789 return remove( this, selector );
5792 text: function( value ) {
5793 return access( this, function( value ) {
5794 return value === undefined ?
5795 jQuery.text( this ) :
5796 this.empty().each( function() {
5797 if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
5798 this.textContent = value;
5801 }, null, value, arguments.length );
5804 append: function() {
5805 return domManip( this, arguments, function( elem ) {
5806 if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
5807 var target = manipulationTarget( this, elem );
5808 target.appendChild( elem );
5813 prepend: function() {
5814 return domManip( this, arguments, function( elem ) {
5815 if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
5816 var target = manipulationTarget( this, elem );
5817 target.insertBefore( elem, target.firstChild );
5822 before: function() {
5823 return domManip( this, arguments, function( elem ) {
5824 if ( this.parentNode ) {
5825 this.parentNode.insertBefore( elem, this );
5831 return domManip( this, arguments, function( elem ) {
5832 if ( this.parentNode ) {
5833 this.parentNode.insertBefore( elem, this.nextSibling );
5842 for ( ; ( elem = this[ i ] ) != null; i++ ) {
5843 if ( elem.nodeType === 1 ) {
5845 // Prevent memory leaks
5846 jQuery.cleanData( getAll( elem, false ) );
5848 // Remove any remaining nodes
5849 elem.textContent = "";
5856 clone: function( dataAndEvents, deepDataAndEvents ) {
5857 dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
5858 deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
5860 return this.map( function() {
5861 return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
5865 html: function( value ) {
5866 return access( this, function( value ) {
5867 var elem = this[ 0 ] || {},
5871 if ( value === undefined && elem.nodeType === 1 ) {
5872 return elem.innerHTML;
5875 // See if we can take a shortcut and just use innerHTML
5876 if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
5877 !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
5879 value = jQuery.htmlPrefilter( value );
5882 for ( ; i < l; i++ ) {
5883 elem = this[ i ] || {};
5885 // Remove element nodes and prevent memory leaks
5886 if ( elem.nodeType === 1 ) {
5887 jQuery.cleanData( getAll( elem, false ) );
5888 elem.innerHTML = value;
5894 // If using innerHTML throws an exception, use the fallback method
5899 this.empty().append( value );
5901 }, null, value, arguments.length );
5904 replaceWith: function() {
5907 // Make the changes, replacing each non-ignored context element with the new content
5908 return domManip( this, arguments, function( elem ) {
5909 var parent = this.parentNode;
5911 if ( jQuery.inArray( this, ignored ) < 0 ) {
5912 jQuery.cleanData( getAll( this ) );
5914 parent.replaceChild( elem, this );
5918 // Force callback invocation
5925 prependTo: "prepend",
5926 insertBefore: "before",
5927 insertAfter: "after",
5928 replaceAll: "replaceWith"
5929 }, function( name, original ) {
5930 jQuery.fn[ name ] = function( selector ) {
5933 insert = jQuery( selector ),
5934 last = insert.length - 1,
5937 for ( ; i <= last; i++ ) {
5938 elems = i === last ? this : this.clone( true );
5939 jQuery( insert[ i ] )[ original ]( elems );
5941 // Support: Android <=4.0 only, PhantomJS 1 only
5942 // .get() because push.apply(_, arraylike) throws on ancient WebKit
5943 push.apply( ret, elems.get() );
5946 return this.pushStack( ret );
5949 var rmargin = ( /^margin/ );
5951 var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
5953 var getStyles = function( elem ) {
5955 // Support: IE <=11 only, Firefox <=30 (#15098, #14150)
5956 // IE throws on elements created in popups
5957 // FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
5958 var view = elem.ownerDocument.defaultView;
5960 if ( !view || !view.opener ) {
5964 return view.getComputedStyle( elem );
5971 // Executing both pixelPosition & boxSizingReliable tests require only one layout
5972 // so they're executed at the same time to save the second computation.
5973 function computeStyleTests() {
5975 // This is a singleton, we need to execute it only once
5981 "box-sizing:border-box;" +
5982 "position:relative;display:block;" +
5983 "margin:auto;border:1px;padding:1px;" +
5986 documentElement.appendChild( container );
5988 var divStyle = window.getComputedStyle( div );
5989 pixelPositionVal = divStyle.top !== "1%";
5991 // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
5992 reliableMarginLeftVal = divStyle.marginLeft === "2px";
5993 boxSizingReliableVal = divStyle.width === "4px";
5995 // Support: Android 4.0 - 4.3 only
5996 // Some styles come back with percentage values, even though they shouldn't
5997 div.style.marginRight = "50%";
5998 pixelMarginRightVal = divStyle.marginRight === "4px";
6000 documentElement.removeChild( container );
6002 // Nullify the div so it wouldn't be stored in the memory and
6003 // it will also be a sign that checks already performed
6007 var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal,
6008 container = document.createElement( "div" ),
6009 div = document.createElement( "div" );
6011 // Finish early in limited (non-browser) environments
6016 // Support: IE <=9 - 11 only
6017 // Style of cloned element affects source element cloned (#8908)
6018 div.style.backgroundClip = "content-box";
6019 div.cloneNode( true ).style.backgroundClip = "";
6020 support.clearCloneStyle = div.style.backgroundClip === "content-box";
6022 container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" +
6023 "padding:0;margin-top:1px;position:absolute";
6024 container.appendChild( div );
6026 jQuery.extend( support, {
6027 pixelPosition: function() {
6028 computeStyleTests();
6029 return pixelPositionVal;
6031 boxSizingReliable: function() {
6032 computeStyleTests();
6033 return boxSizingReliableVal;
6035 pixelMarginRight: function() {
6036 computeStyleTests();
6037 return pixelMarginRightVal;
6039 reliableMarginLeft: function() {
6040 computeStyleTests();
6041 return reliableMarginLeftVal;
6047 function curCSS( elem, name, computed ) {
6048 var width, minWidth, maxWidth, ret,
6051 computed = computed || getStyles( elem );
6053 // Support: IE <=9 only
6054 // getPropertyValue is only needed for .css('filter') (#12537)
6056 ret = computed.getPropertyValue( name ) || computed[ name ];
6058 if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
6059 ret = jQuery.style( elem, name );
6062 // A tribute to the "awesome hack by Dean Edwards"
6063 // Android Browser returns percentage for some values,
6064 // but width seems to be reliably pixels.
6065 // This is against the CSSOM draft spec:
6066 // https://drafts.csswg.org/cssom/#resolved-values
6067 if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) {
6069 // Remember the original values
6070 width = style.width;
6071 minWidth = style.minWidth;
6072 maxWidth = style.maxWidth;
6074 // Put in the new values to get a computed value out
6075 style.minWidth = style.maxWidth = style.width = ret;
6076 ret = computed.width;
6078 // Revert the changed values
6079 style.width = width;
6080 style.minWidth = minWidth;
6081 style.maxWidth = maxWidth;
6085 return ret !== undefined ?
6087 // Support: IE <=9 - 11 only
6088 // IE returns zIndex value as an integer.
6094 function addGetHookIf( conditionFn, hookFn ) {
6096 // Define the hook, we'll check on the first run if it's really needed.
6099 if ( conditionFn() ) {
6101 // Hook not needed (or it's not possible to use it due
6102 // to missing dependency), remove it.
6107 // Hook needed; redefine it so that the support test is not executed again.
6108 return ( this.get = hookFn ).apply( this, arguments );
6116 // Swappable if display is none or starts with table
6117 // except "table", "table-cell", or "table-caption"
6118 // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
6119 rdisplayswap = /^(none|table(?!-c[ea]).+)/,
6120 cssShow = { position: "absolute", visibility: "hidden", display: "block" },
6121 cssNormalTransform = {
6126 cssPrefixes = [ "Webkit", "Moz", "ms" ],
6127 emptyStyle = document.createElement( "div" ).style;
6129 // Return a css property mapped to a potentially vendor prefixed property
6130 function vendorPropName( name ) {
6132 // Shortcut for names that are not vendor prefixed
6133 if ( name in emptyStyle ) {
6137 // Check for vendor prefixed names
6138 var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
6139 i = cssPrefixes.length;
6142 name = cssPrefixes[ i ] + capName;
6143 if ( name in emptyStyle ) {
6149 function setPositiveNumber( elem, value, subtract ) {
6151 // Any relative (+/-) values have already been
6152 // normalized at this point
6153 var matches = rcssNum.exec( value );
6156 // Guard against undefined "subtract", e.g., when used as in cssHooks
6157 Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
6161 function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
6162 var i = extra === ( isBorderBox ? "border" : "content" ) ?
6164 // If we already have the right measurement, avoid augmentation
6167 // Otherwise initialize for horizontal or vertical properties
6168 name === "width" ? 1 : 0,
6172 for ( ; i < 4; i += 2 ) {
6174 // Both box models exclude margin, so add it if we want it
6175 if ( extra === "margin" ) {
6176 val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
6179 if ( isBorderBox ) {
6181 // border-box includes padding, so remove it if we want content
6182 if ( extra === "content" ) {
6183 val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
6186 // At this point, extra isn't border nor margin, so remove border
6187 if ( extra !== "margin" ) {
6188 val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
6192 // At this point, extra isn't content, so add padding
6193 val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
6195 // At this point, extra isn't content nor padding, so add border
6196 if ( extra !== "padding" ) {
6197 val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
6205 function getWidthOrHeight( elem, name, extra ) {
6207 // Start with offset property, which is equivalent to the border-box value
6209 valueIsBorderBox = true,
6210 styles = getStyles( elem ),
6211 isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
6213 // Support: IE <=11 only
6214 // Running getBoundingClientRect on a disconnected node
6215 // in IE throws an error.
6216 if ( elem.getClientRects().length ) {
6217 val = elem.getBoundingClientRect()[ name ];
6220 // Some non-html elements return undefined for offsetWidth, so check for null/undefined
6221 // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
6222 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
6223 if ( val <= 0 || val == null ) {
6225 // Fall back to computed then uncomputed css if necessary
6226 val = curCSS( elem, name, styles );
6227 if ( val < 0 || val == null ) {
6228 val = elem.style[ name ];
6231 // Computed unit is not pixels. Stop here and return.
6232 if ( rnumnonpx.test( val ) ) {
6236 // Check for style in case a browser which returns unreliable values
6237 // for getComputedStyle silently falls back to the reliable elem.style
6238 valueIsBorderBox = isBorderBox &&
6239 ( support.boxSizingReliable() || val === elem.style[ name ] );
6241 // Normalize "", auto, and prepare for extra
6242 val = parseFloat( val ) || 0;
6245 // Use the active box-sizing model to add/subtract irrelevant styles
6247 augmentWidthOrHeight(
6250 extra || ( isBorderBox ? "border" : "content" ),
6259 // Add in style property hooks for overriding the default
6260 // behavior of getting and setting a style property
6263 get: function( elem, computed ) {
6266 // We should always get a number back from opacity
6267 var ret = curCSS( elem, "opacity" );
6268 return ret === "" ? "1" : ret;
6274 // Don't automatically add "px" to these possibly-unitless properties
6276 "animationIterationCount": true,
6277 "columnCount": true,
6278 "fillOpacity": true,
6291 // Add in properties whose names you wish to fix before
6292 // setting or getting the value
6297 // Get and set the style property on a DOM Node
6298 style: function( elem, name, value, extra ) {
6300 // Don't set styles on text and comment nodes
6301 if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
6305 // Make sure that we're working with the right name
6306 var ret, type, hooks,
6307 origName = jQuery.camelCase( name ),
6310 name = jQuery.cssProps[ origName ] ||
6311 ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );
6313 // Gets hook for the prefixed version, then unprefixed version
6314 hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
6316 // Check if we're setting a value
6317 if ( value !== undefined ) {
6318 type = typeof value;
6320 // Convert "+=" or "-=" to relative numbers (#7345)
6321 if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
6322 value = adjustCSS( elem, name, ret );
6328 // Make sure that null and NaN values aren't set (#7116)
6329 if ( value == null || value !== value ) {
6333 // If a number was passed in, add the unit (except for certain CSS properties)
6334 if ( type === "number" ) {
6335 value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
6338 // background-* props affect original clone's values
6339 if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
6340 style[ name ] = "inherit";
6343 // If a hook was provided, use that value, otherwise just set the specified value
6344 if ( !hooks || !( "set" in hooks ) ||
6345 ( value = hooks.set( elem, value, extra ) ) !== undefined ) {
6347 style[ name ] = value;
6352 // If a hook was provided get the non-computed value from there
6353 if ( hooks && "get" in hooks &&
6354 ( ret = hooks.get( elem, false, extra ) ) !== undefined ) {
6359 // Otherwise just get the value from the style object
6360 return style[ name ];
6364 css: function( elem, name, extra, styles ) {
6365 var val, num, hooks,
6366 origName = jQuery.camelCase( name );
6368 // Make sure that we're working with the right name
6369 name = jQuery.cssProps[ origName ] ||
6370 ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );
6372 // Try prefixed name followed by the unprefixed name
6373 hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
6375 // If a hook was provided get the computed value from there
6376 if ( hooks && "get" in hooks ) {
6377 val = hooks.get( elem, true, extra );
6380 // Otherwise, if a way to get the computed value exists, use that
6381 if ( val === undefined ) {
6382 val = curCSS( elem, name, styles );
6385 // Convert "normal" to computed value
6386 if ( val === "normal" && name in cssNormalTransform ) {
6387 val = cssNormalTransform[ name ];
6390 // Make numeric if forced or a qualifier was provided and val looks numeric
6391 if ( extra === "" || extra ) {
6392 num = parseFloat( val );
6393 return extra === true || isFinite( num ) ? num || 0 : val;
6399 jQuery.each( [ "height", "width" ], function( i, name ) {
6400 jQuery.cssHooks[ name ] = {
6401 get: function( elem, computed, extra ) {
6404 // Certain elements can have dimension info if we invisibly show them
6405 // but it must have a current display style that would benefit
6406 return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
6408 // Support: Safari 8+
6409 // Table columns in Safari have non-zero offsetWidth & zero
6410 // getBoundingClientRect().width unless display is changed.
6411 // Support: IE <=11 only
6412 // Running getBoundingClientRect on a disconnected node
6413 // in IE throws an error.
6414 ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
6415 swap( elem, cssShow, function() {
6416 return getWidthOrHeight( elem, name, extra );
6418 getWidthOrHeight( elem, name, extra );
6422 set: function( elem, value, extra ) {
6424 styles = extra && getStyles( elem ),
6425 subtract = extra && augmentWidthOrHeight(
6429 jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
6433 // Convert to pixels if value adjustment is needed
6434 if ( subtract && ( matches = rcssNum.exec( value ) ) &&
6435 ( matches[ 3 ] || "px" ) !== "px" ) {
6437 elem.style[ name ] = value;
6438 value = jQuery.css( elem, name );
6441 return setPositiveNumber( elem, value, subtract );
6446 jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
6447 function( elem, computed ) {
6449 return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
6450 elem.getBoundingClientRect().left -
6451 swap( elem, { marginLeft: 0 }, function() {
6452 return elem.getBoundingClientRect().left;
6459 // These hooks are used by animate to expand properties
6464 }, function( prefix, suffix ) {
6465 jQuery.cssHooks[ prefix + suffix ] = {
6466 expand: function( value ) {
6470 // Assumes a single number if not a string
6471 parts = typeof value === "string" ? value.split( " " ) : [ value ];
6473 for ( ; i < 4; i++ ) {
6474 expanded[ prefix + cssExpand[ i ] + suffix ] =
6475 parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
6482 if ( !rmargin.test( prefix ) ) {
6483 jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
6488 css: function( name, value ) {
6489 return access( this, function( elem, name, value ) {
6494 if ( jQuery.isArray( name ) ) {
6495 styles = getStyles( elem );
6498 for ( ; i < len; i++ ) {
6499 map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
6505 return value !== undefined ?
6506 jQuery.style( elem, name, value ) :
6507 jQuery.css( elem, name );
6508 }, name, value, arguments.length > 1 );
6513 function Tween( elem, options, prop, end, easing ) {
6514 return new Tween.prototype.init( elem, options, prop, end, easing );
6516 jQuery.Tween = Tween;
6520 init: function( elem, options, prop, end, easing, unit ) {
6523 this.easing = easing || jQuery.easing._default;
6524 this.options = options;
6525 this.start = this.now = this.cur();
6527 this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
6530 var hooks = Tween.propHooks[ this.prop ];
6532 return hooks && hooks.get ?
6534 Tween.propHooks._default.get( this );
6536 run: function( percent ) {
6538 hooks = Tween.propHooks[ this.prop ];
6540 if ( this.options.duration ) {
6541 this.pos = eased = jQuery.easing[ this.easing ](
6542 percent, this.options.duration * percent, 0, 1, this.options.duration
6545 this.pos = eased = percent;
6547 this.now = ( this.end - this.start ) * eased + this.start;
6549 if ( this.options.step ) {
6550 this.options.step.call( this.elem, this.now, this );
6553 if ( hooks && hooks.set ) {
6556 Tween.propHooks._default.set( this );
6562 Tween.prototype.init.prototype = Tween.prototype;
6566 get: function( tween ) {
6569 // Use a property on the element directly when it is not a DOM element,
6570 // or when there is no matching style property that exists.
6571 if ( tween.elem.nodeType !== 1 ||
6572 tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
6573 return tween.elem[ tween.prop ];
6576 // Passing an empty string as a 3rd parameter to .css will automatically
6577 // attempt a parseFloat and fallback to a string if the parse fails.
6578 // Simple values such as "10px" are parsed to Float;
6579 // complex values such as "rotate(1rad)" are returned as-is.
6580 result = jQuery.css( tween.elem, tween.prop, "" );
6582 // Empty strings, null, undefined and "auto" are converted to 0.
6583 return !result || result === "auto" ? 0 : result;
6585 set: function( tween ) {
6587 // Use step hook for back compat.
6588 // Use cssHook if its there.
6589 // Use .style if available and use plain properties where available.
6590 if ( jQuery.fx.step[ tween.prop ] ) {
6591 jQuery.fx.step[ tween.prop ]( tween );
6592 } else if ( tween.elem.nodeType === 1 &&
6593 ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null ||
6594 jQuery.cssHooks[ tween.prop ] ) ) {
6595 jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
6597 tween.elem[ tween.prop ] = tween.now;
6603 // Support: IE <=9 only
6604 // Panic based approach to setting things on disconnected nodes
6605 Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
6606 set: function( tween ) {
6607 if ( tween.elem.nodeType && tween.elem.parentNode ) {
6608 tween.elem[ tween.prop ] = tween.now;
6614 linear: function( p ) {
6617 swing: function( p ) {
6618 return 0.5 - Math.cos( p * Math.PI ) / 2;
6623 jQuery.fx = Tween.prototype.init;
6625 // Back compat <1.8 extension point
6626 jQuery.fx.step = {};
6633 rfxtypes = /^(?:toggle|show|hide)$/,
6634 rrun = /queueHooks$/;
6638 window.requestAnimationFrame( raf );
6643 // Animations created synchronously will run synchronously
6644 function createFxNow() {
6645 window.setTimeout( function() {
6648 return ( fxNow = jQuery.now() );
6651 // Generate parameters to create a standard animation
6652 function genFx( type, includeWidth ) {
6655 attrs = { height: type };
6657 // If we include width, step value is 1 to do all cssExpand values,
6658 // otherwise step value is 2 to skip over Left and Right
6659 includeWidth = includeWidth ? 1 : 0;
6660 for ( ; i < 4; i += 2 - includeWidth ) {
6661 which = cssExpand[ i ];
6662 attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
6665 if ( includeWidth ) {
6666 attrs.opacity = attrs.width = type;
6672 function createTween( value, prop, animation ) {
6674 collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
6676 length = collection.length;
6677 for ( ; index < length; index++ ) {
6678 if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {
6680 // We're done with this property
6686 function defaultPrefilter( elem, props, opts ) {
6687 var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
6688 isBox = "width" in props || "height" in props,
6692 hidden = elem.nodeType && isHiddenWithinTree( elem ),
6693 dataShow = dataPriv.get( elem, "fxshow" );
6695 // Queue-skipping animations hijack the fx hooks
6696 if ( !opts.queue ) {
6697 hooks = jQuery._queueHooks( elem, "fx" );
6698 if ( hooks.unqueued == null ) {
6700 oldfire = hooks.empty.fire;
6701 hooks.empty.fire = function() {
6702 if ( !hooks.unqueued ) {
6709 anim.always( function() {
6711 // Ensure the complete handler is called before this completes
6712 anim.always( function() {
6714 if ( !jQuery.queue( elem, "fx" ).length ) {
6721 // Detect show/hide animations
6722 for ( prop in props ) {
6723 value = props[ prop ];
6724 if ( rfxtypes.test( value ) ) {
6725 delete props[ prop ];
6726 toggle = toggle || value === "toggle";
6727 if ( value === ( hidden ? "hide" : "show" ) ) {
6729 // Pretend to be hidden if this is a "show" and
6730 // there is still data from a stopped show/hide
6731 if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
6734 // Ignore all other no-op show/hide data
6739 orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
6743 // Bail out if this is a no-op like .hide().hide()
6744 propTween = !jQuery.isEmptyObject( props );
6745 if ( !propTween && jQuery.isEmptyObject( orig ) ) {
6749 // Restrict "overflow" and "display" styles during box animations
6750 if ( isBox && elem.nodeType === 1 ) {
6752 // Support: IE <=9 - 11, Edge 12 - 13
6753 // Record all 3 overflow attributes because IE does not infer the shorthand
6754 // from identically-valued overflowX and overflowY
6755 opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
6757 // Identify a display type, preferring old show/hide data over the CSS cascade
6758 restoreDisplay = dataShow && dataShow.display;
6759 if ( restoreDisplay == null ) {
6760 restoreDisplay = dataPriv.get( elem, "display" );
6762 display = jQuery.css( elem, "display" );
6763 if ( display === "none" ) {
6764 if ( restoreDisplay ) {
6765 display = restoreDisplay;
6768 // Get nonempty value(s) by temporarily forcing visibility
6769 showHide( [ elem ], true );
6770 restoreDisplay = elem.style.display || restoreDisplay;
6771 display = jQuery.css( elem, "display" );
6772 showHide( [ elem ] );
6776 // Animate inline elements as inline-block
6777 if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) {
6778 if ( jQuery.css( elem, "float" ) === "none" ) {
6780 // Restore the original display value at the end of pure show/hide animations
6782 anim.done( function() {
6783 style.display = restoreDisplay;
6785 if ( restoreDisplay == null ) {
6786 display = style.display;
6787 restoreDisplay = display === "none" ? "" : display;
6790 style.display = "inline-block";
6795 if ( opts.overflow ) {
6796 style.overflow = "hidden";
6797 anim.always( function() {
6798 style.overflow = opts.overflow[ 0 ];
6799 style.overflowX = opts.overflow[ 1 ];
6800 style.overflowY = opts.overflow[ 2 ];
6804 // Implement show/hide animations
6806 for ( prop in orig ) {
6808 // General show/hide setup for this element animation
6811 if ( "hidden" in dataShow ) {
6812 hidden = dataShow.hidden;
6815 dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
6818 // Store hidden/visible for toggle so `.stop().toggle()` "reverses"
6820 dataShow.hidden = !hidden;
6823 // Show elements before animating them
6825 showHide( [ elem ], true );
6828 /* eslint-disable no-loop-func */
6830 anim.done( function() {
6832 /* eslint-enable no-loop-func */
6834 // The final step of a "hide" animation is actually hiding the element
6836 showHide( [ elem ] );
6838 dataPriv.remove( elem, "fxshow" );
6839 for ( prop in orig ) {
6840 jQuery.style( elem, prop, orig[ prop ] );
6845 // Per-property setup
6846 propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
6847 if ( !( prop in dataShow ) ) {
6848 dataShow[ prop ] = propTween.start;
6850 propTween.end = propTween.start;
6851 propTween.start = 0;
6857 function propFilter( props, specialEasing ) {
6858 var index, name, easing, value, hooks;
6860 // camelCase, specialEasing and expand cssHook pass
6861 for ( index in props ) {
6862 name = jQuery.camelCase( index );
6863 easing = specialEasing[ name ];
6864 value = props[ index ];
6865 if ( jQuery.isArray( value ) ) {
6866 easing = value[ 1 ];
6867 value = props[ index ] = value[ 0 ];
6870 if ( index !== name ) {
6871 props[ name ] = value;
6872 delete props[ index ];
6875 hooks = jQuery.cssHooks[ name ];
6876 if ( hooks && "expand" in hooks ) {
6877 value = hooks.expand( value );
6878 delete props[ name ];
6880 // Not quite $.extend, this won't overwrite existing keys.
6881 // Reusing 'index' because we have the correct "name"
6882 for ( index in value ) {
6883 if ( !( index in props ) ) {
6884 props[ index ] = value[ index ];
6885 specialEasing[ index ] = easing;
6889 specialEasing[ name ] = easing;
6894 function Animation( elem, properties, options ) {
6898 length = Animation.prefilters.length,
6899 deferred = jQuery.Deferred().always( function() {
6901 // Don't match elem in the :animated selector
6908 var currentTime = fxNow || createFxNow(),
6909 remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
6911 // Support: Android 2.3 only
6912 // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
6913 temp = remaining / animation.duration || 0,
6916 length = animation.tweens.length;
6918 for ( ; index < length; index++ ) {
6919 animation.tweens[ index ].run( percent );
6922 deferred.notifyWith( elem, [ animation, percent, remaining ] );
6924 if ( percent < 1 && length ) {
6927 deferred.resolveWith( elem, [ animation ] );
6931 animation = deferred.promise( {
6933 props: jQuery.extend( {}, properties ),
6934 opts: jQuery.extend( true, {
6936 easing: jQuery.easing._default
6938 originalProperties: properties,
6939 originalOptions: options,
6940 startTime: fxNow || createFxNow(),
6941 duration: options.duration,
6943 createTween: function( prop, end ) {
6944 var tween = jQuery.Tween( elem, animation.opts, prop, end,
6945 animation.opts.specialEasing[ prop ] || animation.opts.easing );
6946 animation.tweens.push( tween );
6949 stop: function( gotoEnd ) {
6952 // If we are going to the end, we want to run all the tweens
6953 // otherwise we skip this part
6954 length = gotoEnd ? animation.tweens.length : 0;
6959 for ( ; index < length; index++ ) {
6960 animation.tweens[ index ].run( 1 );
6963 // Resolve when we played the last frame; otherwise, reject
6965 deferred.notifyWith( elem, [ animation, 1, 0 ] );
6966 deferred.resolveWith( elem, [ animation, gotoEnd ] );
6968 deferred.rejectWith( elem, [ animation, gotoEnd ] );
6973 props = animation.props;
6975 propFilter( props, animation.opts.specialEasing );
6977 for ( ; index < length; index++ ) {
6978 result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
6980 if ( jQuery.isFunction( result.stop ) ) {
6981 jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
6982 jQuery.proxy( result.stop, result );
6988 jQuery.map( props, createTween, animation );
6990 if ( jQuery.isFunction( animation.opts.start ) ) {
6991 animation.opts.start.call( elem, animation );
6995 jQuery.extend( tick, {
6998 queue: animation.opts.queue
7002 // attach callbacks from options
7003 return animation.progress( animation.opts.progress )
7004 .done( animation.opts.done, animation.opts.complete )
7005 .fail( animation.opts.fail )
7006 .always( animation.opts.always );
7009 jQuery.Animation = jQuery.extend( Animation, {
7012 "*": [ function( prop, value ) {
7013 var tween = this.createTween( prop, value );
7014 adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
7019 tweener: function( props, callback ) {
7020 if ( jQuery.isFunction( props ) ) {
7024 props = props.match( rnotwhite );
7029 length = props.length;
7031 for ( ; index < length; index++ ) {
7032 prop = props[ index ];
7033 Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
7034 Animation.tweeners[ prop ].unshift( callback );
7038 prefilters: [ defaultPrefilter ],
7040 prefilter: function( callback, prepend ) {
7042 Animation.prefilters.unshift( callback );
7044 Animation.prefilters.push( callback );
7049 jQuery.speed = function( speed, easing, fn ) {
7050 var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
7051 complete: fn || !fn && easing ||
7052 jQuery.isFunction( speed ) && speed,
7054 easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
7057 // Go to the end state if fx are off or if document is hidden
7058 if ( jQuery.fx.off || document.hidden ) {
7062 opt.duration = typeof opt.duration === "number" ?
7063 opt.duration : opt.duration in jQuery.fx.speeds ?
7064 jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
7067 // Normalize opt.queue - true/undefined/null -> "fx"
7068 if ( opt.queue == null || opt.queue === true ) {
7073 opt.old = opt.complete;
7075 opt.complete = function() {
7076 if ( jQuery.isFunction( opt.old ) ) {
7077 opt.old.call( this );
7081 jQuery.dequeue( this, opt.queue );
7089 fadeTo: function( speed, to, easing, callback ) {
7091 // Show any hidden elements after setting opacity to 0
7092 return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show()
7094 // Animate to the value specified
7095 .end().animate( { opacity: to }, speed, easing, callback );
7097 animate: function( prop, speed, easing, callback ) {
7098 var empty = jQuery.isEmptyObject( prop ),
7099 optall = jQuery.speed( speed, easing, callback ),
7100 doAnimation = function() {
7102 // Operate on a copy of prop so per-property easing won't be lost
7103 var anim = Animation( this, jQuery.extend( {}, prop ), optall );
7105 // Empty animations, or finishing resolves immediately
7106 if ( empty || dataPriv.get( this, "finish" ) ) {
7110 doAnimation.finish = doAnimation;
7112 return empty || optall.queue === false ?
7113 this.each( doAnimation ) :
7114 this.queue( optall.queue, doAnimation );
7116 stop: function( type, clearQueue, gotoEnd ) {
7117 var stopQueue = function( hooks ) {
7118 var stop = hooks.stop;
7123 if ( typeof type !== "string" ) {
7124 gotoEnd = clearQueue;
7128 if ( clearQueue && type !== false ) {
7129 this.queue( type || "fx", [] );
7132 return this.each( function() {
7134 index = type != null && type + "queueHooks",
7135 timers = jQuery.timers,
7136 data = dataPriv.get( this );
7139 if ( data[ index ] && data[ index ].stop ) {
7140 stopQueue( data[ index ] );
7143 for ( index in data ) {
7144 if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
7145 stopQueue( data[ index ] );
7150 for ( index = timers.length; index--; ) {
7151 if ( timers[ index ].elem === this &&
7152 ( type == null || timers[ index ].queue === type ) ) {
7154 timers[ index ].anim.stop( gotoEnd );
7156 timers.splice( index, 1 );
7160 // Start the next in the queue if the last step wasn't forced.
7161 // Timers currently will call their complete callbacks, which
7162 // will dequeue but only if they were gotoEnd.
7163 if ( dequeue || !gotoEnd ) {
7164 jQuery.dequeue( this, type );
7168 finish: function( type ) {
7169 if ( type !== false ) {
7170 type = type || "fx";
7172 return this.each( function() {
7174 data = dataPriv.get( this ),
7175 queue = data[ type + "queue" ],
7176 hooks = data[ type + "queueHooks" ],
7177 timers = jQuery.timers,
7178 length = queue ? queue.length : 0;
7180 // Enable finishing flag on private data
7183 // Empty the queue first
7184 jQuery.queue( this, type, [] );
7186 if ( hooks && hooks.stop ) {
7187 hooks.stop.call( this, true );
7190 // Look for any active animations, and finish them
7191 for ( index = timers.length; index--; ) {
7192 if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
7193 timers[ index ].anim.stop( true );
7194 timers.splice( index, 1 );
7198 // Look for any animations in the old queue and finish them
7199 for ( index = 0; index < length; index++ ) {
7200 if ( queue[ index ] && queue[ index ].finish ) {
7201 queue[ index ].finish.call( this );
7205 // Turn off finishing flag
7211 jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) {
7212 var cssFn = jQuery.fn[ name ];
7213 jQuery.fn[ name ] = function( speed, easing, callback ) {
7214 return speed == null || typeof speed === "boolean" ?
7215 cssFn.apply( this, arguments ) :
7216 this.animate( genFx( name, true ), speed, easing, callback );
7220 // Generate shortcuts for custom animations
7222 slideDown: genFx( "show" ),
7223 slideUp: genFx( "hide" ),
7224 slideToggle: genFx( "toggle" ),
7225 fadeIn: { opacity: "show" },
7226 fadeOut: { opacity: "hide" },
7227 fadeToggle: { opacity: "toggle" }
7228 }, function( name, props ) {
7229 jQuery.fn[ name ] = function( speed, easing, callback ) {
7230 return this.animate( props, speed, easing, callback );
7235 jQuery.fx.tick = function() {
7238 timers = jQuery.timers;
7240 fxNow = jQuery.now();
7242 for ( ; i < timers.length; i++ ) {
7243 timer = timers[ i ];
7245 // Checks the timer has not already been removed
7246 if ( !timer() && timers[ i ] === timer ) {
7247 timers.splice( i--, 1 );
7251 if ( !timers.length ) {
7257 jQuery.fx.timer = function( timer ) {
7258 jQuery.timers.push( timer );
7262 jQuery.timers.pop();
7266 jQuery.fx.interval = 13;
7267 jQuery.fx.start = function() {
7269 timerId = window.requestAnimationFrame ?
7270 window.requestAnimationFrame( raf ) :
7271 window.setInterval( jQuery.fx.tick, jQuery.fx.interval );
7275 jQuery.fx.stop = function() {
7276 if ( window.cancelAnimationFrame ) {
7277 window.cancelAnimationFrame( timerId );
7279 window.clearInterval( timerId );
7285 jQuery.fx.speeds = {
7294 // Based off of the plugin by Clint Helfers, with permission.
7295 // https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
7296 jQuery.fn.delay = function( time, type ) {
7297 time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
7298 type = type || "fx";
7300 return this.queue( type, function( next, hooks ) {
7301 var timeout = window.setTimeout( next, time );
7302 hooks.stop = function() {
7303 window.clearTimeout( timeout );
7310 var input = document.createElement( "input" ),
7311 select = document.createElement( "select" ),
7312 opt = select.appendChild( document.createElement( "option" ) );
7314 input.type = "checkbox";
7316 // Support: Android <=4.3 only
7317 // Default value for a checkbox should be "on"
7318 support.checkOn = input.value !== "";
7320 // Support: IE <=11 only
7321 // Must access selectedIndex to make default options select
7322 support.optSelected = opt.selected;
7324 // Support: IE <=11 only
7325 // An input loses its value after becoming a radio
7326 input = document.createElement( "input" );
7328 input.type = "radio";
7329 support.radioValue = input.value === "t";
7334 attrHandle = jQuery.expr.attrHandle;
7337 attr: function( name, value ) {
7338 return access( this, jQuery.attr, name, value, arguments.length > 1 );
7341 removeAttr: function( name ) {
7342 return this.each( function() {
7343 jQuery.removeAttr( this, name );
7349 attr: function( elem, name, value ) {
7351 nType = elem.nodeType;
7353 // Don't get/set attributes on text, comment and attribute nodes
7354 if ( nType === 3 || nType === 8 || nType === 2 ) {
7358 // Fallback to prop when attributes are not supported
7359 if ( typeof elem.getAttribute === "undefined" ) {
7360 return jQuery.prop( elem, name, value );
7363 // Attribute hooks are determined by the lowercase version
7364 // Grab necessary hook if one is defined
7365 if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
7366 hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
7367 ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
7370 if ( value !== undefined ) {
7371 if ( value === null ) {
7372 jQuery.removeAttr( elem, name );
7376 if ( hooks && "set" in hooks &&
7377 ( ret = hooks.set( elem, value, name ) ) !== undefined ) {
7381 elem.setAttribute( name, value + "" );
7385 if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
7389 ret = jQuery.find.attr( elem, name );
7391 // Non-existent attributes return null, we normalize to undefined
7392 return ret == null ? undefined : ret;
7397 set: function( elem, value ) {
7398 if ( !support.radioValue && value === "radio" &&
7399 jQuery.nodeName( elem, "input" ) ) {
7400 var val = elem.value;
7401 elem.setAttribute( "type", value );
7411 removeAttr: function( elem, value ) {
7414 attrNames = value && value.match( rnotwhite );
7416 if ( attrNames && elem.nodeType === 1 ) {
7417 while ( ( name = attrNames[ i++ ] ) ) {
7418 elem.removeAttribute( name );
7424 // Hooks for boolean attributes
7426 set: function( elem, value, name ) {
7427 if ( value === false ) {
7429 // Remove boolean attributes when set to false
7430 jQuery.removeAttr( elem, name );
7432 elem.setAttribute( name, name );
7438 jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
7439 var getter = attrHandle[ name ] || jQuery.find.attr;
7441 attrHandle[ name ] = function( elem, name, isXML ) {
7443 lowercaseName = name.toLowerCase();
7447 // Avoid an infinite loop by temporarily removing this function from the getter
7448 handle = attrHandle[ lowercaseName ];
7449 attrHandle[ lowercaseName ] = ret;
7450 ret = getter( elem, name, isXML ) != null ?
7453 attrHandle[ lowercaseName ] = handle;
7462 var rfocusable = /^(?:input|select|textarea|button)$/i,
7463 rclickable = /^(?:a|area)$/i;
7466 prop: function( name, value ) {
7467 return access( this, jQuery.prop, name, value, arguments.length > 1 );
7470 removeProp: function( name ) {
7471 return this.each( function() {
7472 delete this[ jQuery.propFix[ name ] || name ];
7478 prop: function( elem, name, value ) {
7480 nType = elem.nodeType;
7482 // Don't get/set properties on text, comment and attribute nodes
7483 if ( nType === 3 || nType === 8 || nType === 2 ) {
7487 if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
7489 // Fix name and attach hooks
7490 name = jQuery.propFix[ name ] || name;
7491 hooks = jQuery.propHooks[ name ];
7494 if ( value !== undefined ) {
7495 if ( hooks && "set" in hooks &&
7496 ( ret = hooks.set( elem, value, name ) ) !== undefined ) {
7500 return ( elem[ name ] = value );
7503 if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
7507 return elem[ name ];
7512 get: function( elem ) {
7514 // Support: IE <=9 - 11 only
7515 // elem.tabIndex doesn't always return the
7516 // correct value when it hasn't been explicitly set
7517 // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
7518 // Use proper attribute retrieval(#12072)
7519 var tabindex = jQuery.find.attr( elem, "tabindex" );
7522 parseInt( tabindex, 10 ) :
7523 rfocusable.test( elem.nodeName ) ||
7524 rclickable.test( elem.nodeName ) && elem.href ?
7533 "class": "className"
7537 // Support: IE <=11 only
7538 // Accessing the selectedIndex property
7539 // forces the browser to respect setting selected
7541 // The getter ensures a default option is selected
7542 // when in an optgroup
7543 if ( !support.optSelected ) {
7544 jQuery.propHooks.selected = {
7545 get: function( elem ) {
7546 var parent = elem.parentNode;
7547 if ( parent && parent.parentNode ) {
7548 parent.parentNode.selectedIndex;
7552 set: function( elem ) {
7553 var parent = elem.parentNode;
7555 parent.selectedIndex;
7557 if ( parent.parentNode ) {
7558 parent.parentNode.selectedIndex;
7577 jQuery.propFix[ this.toLowerCase() ] = this;
7583 var rclass = /[\t\r\n\f]/g;
7585 function getClass( elem ) {
7586 return elem.getAttribute && elem.getAttribute( "class" ) || "";
7590 addClass: function( value ) {
7591 var classes, elem, cur, curValue, clazz, j, finalValue,
7594 if ( jQuery.isFunction( value ) ) {
7595 return this.each( function( j ) {
7596 jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
7600 if ( typeof value === "string" && value ) {
7601 classes = value.match( rnotwhite ) || [];
7603 while ( ( elem = this[ i++ ] ) ) {
7604 curValue = getClass( elem );
7605 cur = elem.nodeType === 1 &&
7606 ( " " + curValue + " " ).replace( rclass, " " );
7610 while ( ( clazz = classes[ j++ ] ) ) {
7611 if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
7616 // Only assign if different to avoid unneeded rendering.
7617 finalValue = jQuery.trim( cur );
7618 if ( curValue !== finalValue ) {
7619 elem.setAttribute( "class", finalValue );
7628 removeClass: function( value ) {
7629 var classes, elem, cur, curValue, clazz, j, finalValue,
7632 if ( jQuery.isFunction( value ) ) {
7633 return this.each( function( j ) {
7634 jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
7638 if ( !arguments.length ) {
7639 return this.attr( "class", "" );
7642 if ( typeof value === "string" && value ) {
7643 classes = value.match( rnotwhite ) || [];
7645 while ( ( elem = this[ i++ ] ) ) {
7646 curValue = getClass( elem );
7648 // This expression is here for better compressibility (see addClass)
7649 cur = elem.nodeType === 1 &&
7650 ( " " + curValue + " " ).replace( rclass, " " );
7654 while ( ( clazz = classes[ j++ ] ) ) {
7656 // Remove *all* instances
7657 while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
7658 cur = cur.replace( " " + clazz + " ", " " );
7662 // Only assign if different to avoid unneeded rendering.
7663 finalValue = jQuery.trim( cur );
7664 if ( curValue !== finalValue ) {
7665 elem.setAttribute( "class", finalValue );
7674 toggleClass: function( value, stateVal ) {
7675 var type = typeof value;
7677 if ( typeof stateVal === "boolean" && type === "string" ) {
7678 return stateVal ? this.addClass( value ) : this.removeClass( value );
7681 if ( jQuery.isFunction( value ) ) {
7682 return this.each( function( i ) {
7683 jQuery( this ).toggleClass(
7684 value.call( this, i, getClass( this ), stateVal ),
7690 return this.each( function() {
7691 var className, i, self, classNames;
7693 if ( type === "string" ) {
7695 // Toggle individual class names
7697 self = jQuery( this );
7698 classNames = value.match( rnotwhite ) || [];
7700 while ( ( className = classNames[ i++ ] ) ) {
7702 // Check each className given, space separated list
7703 if ( self.hasClass( className ) ) {
7704 self.removeClass( className );
7706 self.addClass( className );
7710 // Toggle whole class name
7711 } else if ( value === undefined || type === "boolean" ) {
7712 className = getClass( this );
7715 // Store className if set
7716 dataPriv.set( this, "__className__", className );
7719 // If the element has a class name or if we're passed `false`,
7720 // then remove the whole classname (if there was one, the above saved it).
7721 // Otherwise bring back whatever was previously saved (if anything),
7722 // falling back to the empty string if nothing was stored.
7723 if ( this.setAttribute ) {
7724 this.setAttribute( "class",
7725 className || value === false ?
7727 dataPriv.get( this, "__className__" ) || ""
7734 hasClass: function( selector ) {
7735 var className, elem,
7738 className = " " + selector + " ";
7739 while ( ( elem = this[ i++ ] ) ) {
7740 if ( elem.nodeType === 1 &&
7741 ( " " + getClass( elem ) + " " ).replace( rclass, " " )
7742 .indexOf( className ) > -1
7755 var rreturn = /\r/g,
7756 rspaces = /[\x20\t\r\n\f]+/g;
7759 val: function( value ) {
7760 var hooks, ret, isFunction,
7763 if ( !arguments.length ) {
7765 hooks = jQuery.valHooks[ elem.type ] ||
7766 jQuery.valHooks[ elem.nodeName.toLowerCase() ];
7770 ( ret = hooks.get( elem, "value" ) ) !== undefined
7777 return typeof ret === "string" ?
7779 // Handle most common string cases
7780 ret.replace( rreturn, "" ) :
7782 // Handle cases where value is null/undef or number
7783 ret == null ? "" : ret;
7789 isFunction = jQuery.isFunction( value );
7791 return this.each( function( i ) {
7794 if ( this.nodeType !== 1 ) {
7799 val = value.call( this, i, jQuery( this ).val() );
7804 // Treat null/undefined as ""; convert numbers to string
7805 if ( val == null ) {
7808 } else if ( typeof val === "number" ) {
7811 } else if ( jQuery.isArray( val ) ) {
7812 val = jQuery.map( val, function( value ) {
7813 return value == null ? "" : value + "";
7817 hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
7819 // If set returns undefined, fall back to normal setting
7820 if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
7830 get: function( elem ) {
7832 var val = jQuery.find.attr( elem, "value" );
7833 return val != null ?
7836 // Support: IE <=10 - 11 only
7837 // option.text throws exceptions (#14686, #14858)
7838 // Strip and collapse whitespace
7839 // https://html.spec.whatwg.org/#strip-and-collapse-whitespace
7840 jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " );
7844 get: function( elem ) {
7846 options = elem.options,
7847 index = elem.selectedIndex,
7848 one = elem.type === "select-one",
7849 values = one ? null : [],
7850 max = one ? index + 1 : options.length,
7855 // Loop through all the selected options
7856 for ( ; i < max; i++ ) {
7857 option = options[ i ];
7859 // Support: IE <=9 only
7860 // IE8-9 doesn't update selected after form reset (#2551)
7861 if ( ( option.selected || i === index ) &&
7863 // Don't return options that are disabled or in a disabled optgroup
7865 ( !option.parentNode.disabled ||
7866 !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
7868 // Get the specific value for the option
7869 value = jQuery( option ).val();
7871 // We don't need an array for one selects
7876 // Multi-Selects return an array
7877 values.push( value );
7884 set: function( elem, value ) {
7885 var optionSet, option,
7886 options = elem.options,
7887 values = jQuery.makeArray( value ),
7891 option = options[ i ];
7893 /* eslint-disable no-cond-assign */
7895 if ( option.selected =
7896 jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
7901 /* eslint-enable no-cond-assign */
7904 // Force browsers to behave consistently when non-matching value is set
7906 elem.selectedIndex = -1;
7914 // Radios and checkboxes getter/setter
7915 jQuery.each( [ "radio", "checkbox" ], function() {
7916 jQuery.valHooks[ this ] = {
7917 set: function( elem, value ) {
7918 if ( jQuery.isArray( value ) ) {
7919 return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
7923 if ( !support.checkOn ) {
7924 jQuery.valHooks[ this ].get = function( elem ) {
7925 return elem.getAttribute( "value" ) === null ? "on" : elem.value;
7933 // Return jQuery for attributes-only inclusion
7936 var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/;
7938 jQuery.extend( jQuery.event, {
7940 trigger: function( event, data, elem, onlyHandlers ) {
7942 var i, cur, tmp, bubbleType, ontype, handle, special,
7943 eventPath = [ elem || document ],
7944 type = hasOwn.call( event, "type" ) ? event.type : event,
7945 namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];
7947 cur = tmp = elem = elem || document;
7949 // Don't do events on text and comment nodes
7950 if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
7954 // focus/blur morphs to focusin/out; ensure we're not firing them right now
7955 if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
7959 if ( type.indexOf( "." ) > -1 ) {
7961 // Namespaced trigger; create a regexp to match event type in handle()
7962 namespaces = type.split( "." );
7963 type = namespaces.shift();
7966 ontype = type.indexOf( ":" ) < 0 && "on" + type;
7968 // Caller can pass in a jQuery.Event object, Object, or just an event type string
7969 event = event[ jQuery.expando ] ?
7971 new jQuery.Event( type, typeof event === "object" && event );
7973 // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
7974 event.isTrigger = onlyHandlers ? 2 : 3;
7975 event.namespace = namespaces.join( "." );
7976 event.rnamespace = event.namespace ?
7977 new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
7980 // Clean up the event in case it is being reused
7981 event.result = undefined;
7982 if ( !event.target ) {
7983 event.target = elem;
7986 // Clone any incoming data and prepend the event, creating the handler arg list
7987 data = data == null ?
7989 jQuery.makeArray( data, [ event ] );
7991 // Allow special events to draw outside the lines
7992 special = jQuery.event.special[ type ] || {};
7993 if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
7997 // Determine event propagation path in advance, per W3C events spec (#9951)
7998 // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
7999 if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
8001 bubbleType = special.delegateType || type;
8002 if ( !rfocusMorph.test( bubbleType + type ) ) {
8003 cur = cur.parentNode;
8005 for ( ; cur; cur = cur.parentNode ) {
8006 eventPath.push( cur );
8010 // Only add window if we got to document (e.g., not plain obj or detached DOM)
8011 if ( tmp === ( elem.ownerDocument || document ) ) {
8012 eventPath.push( tmp.defaultView || tmp.parentWindow || window );
8016 // Fire handlers on the event path
8018 while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
8020 event.type = i > 1 ?
8022 special.bindType || type;
8025 handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] &&
8026 dataPriv.get( cur, "handle" );
8028 handle.apply( cur, data );
8032 handle = ontype && cur[ ontype ];
8033 if ( handle && handle.apply && acceptData( cur ) ) {
8034 event.result = handle.apply( cur, data );
8035 if ( event.result === false ) {
8036 event.preventDefault();
8042 // If nobody prevented the default action, do it now
8043 if ( !onlyHandlers && !event.isDefaultPrevented() ) {
8045 if ( ( !special._default ||
8046 special._default.apply( eventPath.pop(), data ) === false ) &&
8047 acceptData( elem ) ) {
8049 // Call a native DOM method on the target with the same name as the event.
8050 // Don't do default actions on window, that's where global variables be (#6170)
8051 if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
8053 // Don't re-trigger an onFOO event when we call its FOO() method
8054 tmp = elem[ ontype ];
8057 elem[ ontype ] = null;
8060 // Prevent re-triggering of the same event, since we already bubbled it above
8061 jQuery.event.triggered = type;
8063 jQuery.event.triggered = undefined;
8066 elem[ ontype ] = tmp;
8072 return event.result;
8075 // Piggyback on a donor event to simulate a different one
8076 // Used only for `focus(in | out)` events
8077 simulate: function( type, elem, event ) {
8078 var e = jQuery.extend(
8087 jQuery.event.trigger( e, null, elem );
8094 trigger: function( type, data ) {
8095 return this.each( function() {
8096 jQuery.event.trigger( type, data, this );
8099 triggerHandler: function( type, data ) {
8100 var elem = this[ 0 ];
8102 return jQuery.event.trigger( type, data, elem, true );
8108 jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
8109 "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
8110 "change select submit keydown keypress keyup contextmenu" ).split( " " ),
8111 function( i, name ) {
8113 // Handle event binding
8114 jQuery.fn[ name ] = function( data, fn ) {
8115 return arguments.length > 0 ?
8116 this.on( name, null, data, fn ) :
8117 this.trigger( name );
8122 hover: function( fnOver, fnOut ) {
8123 return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
8130 support.focusin = "onfocusin" in window;
8133 // Support: Firefox <=44
8134 // Firefox doesn't have focus(in | out) events
8135 // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
8137 // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
8138 // focus(in | out) events fire after focus & blur events,
8139 // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
8140 // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
8141 if ( !support.focusin ) {
8142 jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {
8144 // Attach a single capturing handler on the document while someone wants focusin/focusout
8145 var handler = function( event ) {
8146 jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
8149 jQuery.event.special[ fix ] = {
8151 var doc = this.ownerDocument || this,
8152 attaches = dataPriv.access( doc, fix );
8155 doc.addEventListener( orig, handler, true );
8157 dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
8159 teardown: function() {
8160 var doc = this.ownerDocument || this,
8161 attaches = dataPriv.access( doc, fix ) - 1;
8164 doc.removeEventListener( orig, handler, true );
8165 dataPriv.remove( doc, fix );
8168 dataPriv.access( doc, fix, attaches );
8174 var location = window.location;
8176 var nonce = jQuery.now();
8178 var rquery = ( /\?/ );
8182 // Cross-browser xml parsing
8183 jQuery.parseXML = function( data ) {
8185 if ( !data || typeof data !== "string" ) {
8189 // Support: IE 9 - 11 only
8190 // IE throws on parseFromString with invalid input.
8192 xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
8197 if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
8198 jQuery.error( "Invalid XML: " + data );
8207 rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
8208 rsubmittable = /^(?:input|select|textarea|keygen)/i;
8210 function buildParams( prefix, obj, traditional, add ) {
8213 if ( jQuery.isArray( obj ) ) {
8215 // Serialize array item.
8216 jQuery.each( obj, function( i, v ) {
8217 if ( traditional || rbracket.test( prefix ) ) {
8219 // Treat each array item as a scalar.
8224 // Item is non-scalar (array or object), encode its numeric index.
8226 prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
8234 } else if ( !traditional && jQuery.type( obj ) === "object" ) {
8236 // Serialize object item.
8237 for ( name in obj ) {
8238 buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
8243 // Serialize scalar item.
8248 // Serialize an array of form elements or a set of
8249 // key/values into a query string
8250 jQuery.param = function( a, traditional ) {
8253 add = function( key, valueOrFunction ) {
8255 // If value is a function, invoke it and use its return value
8256 var value = jQuery.isFunction( valueOrFunction ) ?
8260 s[ s.length ] = encodeURIComponent( key ) + "=" +
8261 encodeURIComponent( value == null ? "" : value );
8264 // If an array was passed in, assume that it is an array of form elements.
8265 if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
8267 // Serialize the form elements
8268 jQuery.each( a, function() {
8269 add( this.name, this.value );
8274 // If traditional, encode the "old" way (the way 1.3.2 or older
8275 // did it), otherwise encode params recursively.
8276 for ( prefix in a ) {
8277 buildParams( prefix, a[ prefix ], traditional, add );
8281 // Return the resulting serialization
8282 return s.join( "&" );
8286 serialize: function() {
8287 return jQuery.param( this.serializeArray() );
8289 serializeArray: function() {
8290 return this.map( function() {
8292 // Can add propHook for "elements" to filter or add form elements
8293 var elements = jQuery.prop( this, "elements" );
8294 return elements ? jQuery.makeArray( elements ) : this;
8296 .filter( function() {
8297 var type = this.type;
8299 // Use .is( ":disabled" ) so that fieldset[disabled] works
8300 return this.name && !jQuery( this ).is( ":disabled" ) &&
8301 rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
8302 ( this.checked || !rcheckableType.test( type ) );
8304 .map( function( i, elem ) {
8305 var val = jQuery( this ).val();
8307 return val == null ?
8309 jQuery.isArray( val ) ?
8310 jQuery.map( val, function( val ) {
8311 return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
8313 { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
8322 rts = /([?&])_=[^&]*/,
8323 rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
8325 // #7653, #8125, #8152: local protocol detection
8326 rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
8327 rnoContent = /^(?:GET|HEAD)$/,
8328 rprotocol = /^\/\//,
8331 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
8332 * 2) These are called:
8333 * - BEFORE asking for a transport
8334 * - AFTER param serialization (s.data is a string if s.processData is true)
8335 * 3) key is the dataType
8336 * 4) the catchall symbol "*" can be used
8337 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
8341 /* Transports bindings
8342 * 1) key is the dataType
8343 * 2) the catchall symbol "*" can be used
8344 * 3) selection will start with transport dataType and THEN go to "*" if needed
8348 // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
8349 allTypes = "*/".concat( "*" ),
8351 // Anchor tag for parsing the document origin
8352 originAnchor = document.createElement( "a" );
8353 originAnchor.href = location.href;
8355 // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
8356 function addToPrefiltersOrTransports( structure ) {
8358 // dataTypeExpression is optional and defaults to "*"
8359 return function( dataTypeExpression, func ) {
8361 if ( typeof dataTypeExpression !== "string" ) {
8362 func = dataTypeExpression;
8363 dataTypeExpression = "*";
8368 dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
8370 if ( jQuery.isFunction( func ) ) {
8372 // For each dataType in the dataTypeExpression
8373 while ( ( dataType = dataTypes[ i++ ] ) ) {
8375 // Prepend if requested
8376 if ( dataType[ 0 ] === "+" ) {
8377 dataType = dataType.slice( 1 ) || "*";
8378 ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );
8382 ( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
8389 // Base inspection function for prefilters and transports
8390 function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
8393 seekingTransport = ( structure === transports );
8395 function inspect( dataType ) {
8397 inspected[ dataType ] = true;
8398 jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
8399 var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
8400 if ( typeof dataTypeOrTransport === "string" &&
8401 !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
8403 options.dataTypes.unshift( dataTypeOrTransport );
8404 inspect( dataTypeOrTransport );
8406 } else if ( seekingTransport ) {
8407 return !( selected = dataTypeOrTransport );
8413 return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
8416 // A special extend for ajax options
8417 // that takes "flat" options (not to be deep extended)
8419 function ajaxExtend( target, src ) {
8421 flatOptions = jQuery.ajaxSettings.flatOptions || {};
8423 for ( key in src ) {
8424 if ( src[ key ] !== undefined ) {
8425 ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
8429 jQuery.extend( true, target, deep );
8435 /* Handles responses to an ajax request:
8436 * - finds the right dataType (mediates between content-type and expected dataType)
8437 * - returns the corresponding response
8439 function ajaxHandleResponses( s, jqXHR, responses ) {
8441 var ct, type, finalDataType, firstDataType,
8442 contents = s.contents,
8443 dataTypes = s.dataTypes;
8445 // Remove auto dataType and get content-type in the process
8446 while ( dataTypes[ 0 ] === "*" ) {
8448 if ( ct === undefined ) {
8449 ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
8453 // Check if we're dealing with a known content-type
8455 for ( type in contents ) {
8456 if ( contents[ type ] && contents[ type ].test( ct ) ) {
8457 dataTypes.unshift( type );
8463 // Check to see if we have a response for the expected dataType
8464 if ( dataTypes[ 0 ] in responses ) {
8465 finalDataType = dataTypes[ 0 ];
8468 // Try convertible dataTypes
8469 for ( type in responses ) {
8470 if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
8471 finalDataType = type;
8474 if ( !firstDataType ) {
8475 firstDataType = type;
8479 // Or just use first one
8480 finalDataType = finalDataType || firstDataType;
8483 // If we found a dataType
8484 // We add the dataType to the list if needed
8485 // and return the corresponding response
8486 if ( finalDataType ) {
8487 if ( finalDataType !== dataTypes[ 0 ] ) {
8488 dataTypes.unshift( finalDataType );
8490 return responses[ finalDataType ];
8494 /* Chain conversions given the request and the original response
8495 * Also sets the responseXXX fields on the jqXHR instance
8497 function ajaxConvert( s, response, jqXHR, isSuccess ) {
8498 var conv2, current, conv, tmp, prev,
8501 // Work with a copy of dataTypes in case we need to modify it for conversion
8502 dataTypes = s.dataTypes.slice();
8504 // Create converters map with lowercased keys
8505 if ( dataTypes[ 1 ] ) {
8506 for ( conv in s.converters ) {
8507 converters[ conv.toLowerCase() ] = s.converters[ conv ];
8511 current = dataTypes.shift();
8513 // Convert to each sequential dataType
8516 if ( s.responseFields[ current ] ) {
8517 jqXHR[ s.responseFields[ current ] ] = response;
8520 // Apply the dataFilter if provided
8521 if ( !prev && isSuccess && s.dataFilter ) {
8522 response = s.dataFilter( response, s.dataType );
8526 current = dataTypes.shift();
8530 // There's only work to do if current dataType is non-auto
8531 if ( current === "*" ) {
8535 // Convert response if prev dataType is non-auto and differs from current
8536 } else if ( prev !== "*" && prev !== current ) {
8538 // Seek a direct converter
8539 conv = converters[ prev + " " + current ] || converters[ "* " + current ];
8541 // If none found, seek a pair
8543 for ( conv2 in converters ) {
8545 // If conv2 outputs current
8546 tmp = conv2.split( " " );
8547 if ( tmp[ 1 ] === current ) {
8549 // If prev can be converted to accepted input
8550 conv = converters[ prev + " " + tmp[ 0 ] ] ||
8551 converters[ "* " + tmp[ 0 ] ];
8554 // Condense equivalence converters
8555 if ( conv === true ) {
8556 conv = converters[ conv2 ];
8558 // Otherwise, insert the intermediate dataType
8559 } else if ( converters[ conv2 ] !== true ) {
8561 dataTypes.unshift( tmp[ 1 ] );
8569 // Apply converter (if not an equivalence)
8570 if ( conv !== true ) {
8572 // Unless errors are allowed to bubble, catch and return them
8573 if ( conv && s.throws ) {
8574 response = conv( response );
8577 response = conv( response );
8580 state: "parsererror",
8581 error: conv ? e : "No conversion from " + prev + " to " + current
8590 return { state: "success", data: response };
8595 // Counter for holding the number of active queries
8598 // Last-Modified header cache for next request
8605 isLocal: rlocalProtocol.test( location.protocol ),
8609 contentType: "application/x-www-form-urlencoded; charset=UTF-8",
8627 xml: "application/xml, text/xml",
8628 json: "application/json, text/javascript"
8639 text: "responseText",
8640 json: "responseJSON"
8644 // Keys separate source (or catchall "*") and destination types with a single space
8647 // Convert anything to text
8650 // Text to html (true = no transformation)
8653 // Evaluate text as a json expression
8654 "text json": JSON.parse,
8656 // Parse text as xml
8657 "text xml": jQuery.parseXML
8660 // For options that shouldn't be deep extended:
8661 // you can add your own custom options here if
8662 // and when you create one that shouldn't be
8663 // deep extended (see ajaxExtend)
8670 // Creates a full fledged settings object into target
8671 // with both ajaxSettings and settings fields.
8672 // If target is omitted, writes into ajaxSettings.
8673 ajaxSetup: function( target, settings ) {
8676 // Building a settings object
8677 ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
8679 // Extending ajaxSettings
8680 ajaxExtend( jQuery.ajaxSettings, target );
8683 ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
8684 ajaxTransport: addToPrefiltersOrTransports( transports ),
8687 ajax: function( url, options ) {
8689 // If url is an object, simulate pre-1.5 signature
8690 if ( typeof url === "object" ) {
8695 // Force options to be an object
8696 options = options || {};
8700 // URL without anti-cache param
8704 responseHeadersString,
8713 // Request state (becomes false upon send and true upon completion)
8716 // To know if global events are to be dispatched
8722 // uncached part of the url
8725 // Create the final options object
8726 s = jQuery.ajaxSetup( {}, options ),
8728 // Callbacks context
8729 callbackContext = s.context || s,
8731 // Context for global events is callbackContext if it is a DOM node or jQuery collection
8732 globalEventContext = s.context &&
8733 ( callbackContext.nodeType || callbackContext.jquery ) ?
8734 jQuery( callbackContext ) :
8738 deferred = jQuery.Deferred(),
8739 completeDeferred = jQuery.Callbacks( "once memory" ),
8741 // Status-dependent callbacks
8742 statusCode = s.statusCode || {},
8744 // Headers (they are sent all at once)
8745 requestHeaders = {},
8746 requestHeadersNames = {},
8748 // Default abort message
8749 strAbort = "canceled",
8755 // Builds headers hashtable if needed
8756 getResponseHeader: function( key ) {
8759 if ( !responseHeaders ) {
8760 responseHeaders = {};
8761 while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
8762 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
8765 match = responseHeaders[ key.toLowerCase() ];
8767 return match == null ? null : match;
8771 getAllResponseHeaders: function() {
8772 return completed ? responseHeadersString : null;
8775 // Caches the header
8776 setRequestHeader: function( name, value ) {
8777 if ( completed == null ) {
8778 name = requestHeadersNames[ name.toLowerCase() ] =
8779 requestHeadersNames[ name.toLowerCase() ] || name;
8780 requestHeaders[ name ] = value;
8785 // Overrides response content-type header
8786 overrideMimeType: function( type ) {
8787 if ( completed == null ) {
8793 // Status-dependent callbacks
8794 statusCode: function( map ) {
8799 // Execute the appropriate callbacks
8800 jqXHR.always( map[ jqXHR.status ] );
8803 // Lazy-add the new callbacks in a way that preserves old ones
8804 for ( code in map ) {
8805 statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
8812 // Cancel the request
8813 abort: function( statusText ) {
8814 var finalText = statusText || strAbort;
8816 transport.abort( finalText );
8818 done( 0, finalText );
8824 deferred.promise( jqXHR );
8826 // Add protocol if not provided (prefilters might expect it)
8827 // Handle falsy url in the settings object (#10093: consistency with old signature)
8828 // We also use the url parameter if available
8829 s.url = ( ( url || s.url || location.href ) + "" )
8830 .replace( rprotocol, location.protocol + "//" );
8832 // Alias method option to type as per ticket #12004
8833 s.type = options.method || options.type || s.method || s.type;
8835 // Extract dataTypes list
8836 s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
8838 // A cross-domain request is in order when the origin doesn't match the current origin.
8839 if ( s.crossDomain == null ) {
8840 urlAnchor = document.createElement( "a" );
8842 // Support: IE <=8 - 11, Edge 12 - 13
8843 // IE throws exception on accessing the href property if url is malformed,
8844 // e.g. http://example.com:80x/
8846 urlAnchor.href = s.url;
8848 // Support: IE <=8 - 11 only
8849 // Anchor's host property isn't correctly set when s.url is relative
8850 urlAnchor.href = urlAnchor.href;
8851 s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
8852 urlAnchor.protocol + "//" + urlAnchor.host;
8855 // If there is an error parsing the URL, assume it is crossDomain,
8856 // it can be rejected by the transport if it is invalid
8857 s.crossDomain = true;
8861 // Convert data if not already a string
8862 if ( s.data && s.processData && typeof s.data !== "string" ) {
8863 s.data = jQuery.param( s.data, s.traditional );
8867 inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
8869 // If request was aborted inside a prefilter, stop there
8874 // We can fire global events as of now if asked to
8875 // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
8876 fireGlobals = jQuery.event && s.global;
8878 // Watch for a new set of requests
8879 if ( fireGlobals && jQuery.active++ === 0 ) {
8880 jQuery.event.trigger( "ajaxStart" );
8883 // Uppercase the type
8884 s.type = s.type.toUpperCase();
8886 // Determine if request has content
8887 s.hasContent = !rnoContent.test( s.type );
8889 // Save the URL in case we're toying with the If-Modified-Since
8890 // and/or If-None-Match header later on
8891 // Remove hash to simplify url manipulation
8892 cacheURL = s.url.replace( rhash, "" );
8894 // More options handling for requests with no content
8895 if ( !s.hasContent ) {
8897 // Remember the hash so we can put it back
8898 uncached = s.url.slice( cacheURL.length );
8900 // If data is available, append data to url
8902 cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;
8904 // #9682: remove data so that it's not used in an eventual retry
8908 // Add anti-cache in uncached url if needed
8909 if ( s.cache === false ) {
8910 cacheURL = cacheURL.replace( rts, "" );
8911 uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached;
8914 // Put hash and anti-cache on the URL that will be requested (gh-1732)
8915 s.url = cacheURL + uncached;
8917 // Change '%20' to '+' if this is encoded form body content (gh-2658)
8918 } else if ( s.data && s.processData &&
8919 ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
8920 s.data = s.data.replace( r20, "+" );
8923 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
8924 if ( s.ifModified ) {
8925 if ( jQuery.lastModified[ cacheURL ] ) {
8926 jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
8928 if ( jQuery.etag[ cacheURL ] ) {
8929 jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
8933 // Set the correct header, if data is being sent
8934 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
8935 jqXHR.setRequestHeader( "Content-Type", s.contentType );
8938 // Set the Accepts header for the server, depending on the dataType
8939 jqXHR.setRequestHeader(
8941 s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
8942 s.accepts[ s.dataTypes[ 0 ] ] +
8943 ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
8947 // Check for headers option
8948 for ( i in s.headers ) {
8949 jqXHR.setRequestHeader( i, s.headers[ i ] );
8952 // Allow custom headers/mimetypes and early abort
8953 if ( s.beforeSend &&
8954 ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) {
8956 // Abort if not done already and return
8957 return jqXHR.abort();
8960 // Aborting is no longer a cancellation
8963 // Install callbacks on deferreds
8964 completeDeferred.add( s.complete );
8965 jqXHR.done( s.success );
8966 jqXHR.fail( s.error );
8969 transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
8971 // If no transport, we auto-abort
8973 done( -1, "No Transport" );
8975 jqXHR.readyState = 1;
8977 // Send global event
8978 if ( fireGlobals ) {
8979 globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
8982 // If request was aborted inside ajaxSend, stop there
8988 if ( s.async && s.timeout > 0 ) {
8989 timeoutTimer = window.setTimeout( function() {
8990 jqXHR.abort( "timeout" );
8996 transport.send( requestHeaders, done );
8999 // Rethrow post-completion exceptions
9004 // Propagate others as results
9009 // Callback for when everything is done
9010 function done( status, nativeStatusText, responses, headers ) {
9011 var isSuccess, success, error, response, modified,
9012 statusText = nativeStatusText;
9014 // Ignore repeat invocations
9021 // Clear timeout if it exists
9022 if ( timeoutTimer ) {
9023 window.clearTimeout( timeoutTimer );
9026 // Dereference transport for early garbage collection
9027 // (no matter how long the jqXHR object will be used)
9028 transport = undefined;
9030 // Cache response headers
9031 responseHeadersString = headers || "";
9034 jqXHR.readyState = status > 0 ? 4 : 0;
9036 // Determine if successful
9037 isSuccess = status >= 200 && status < 300 || status === 304;
9039 // Get response data
9041 response = ajaxHandleResponses( s, jqXHR, responses );
9044 // Convert no matter what (that way responseXXX fields are always set)
9045 response = ajaxConvert( s, response, jqXHR, isSuccess );
9047 // If successful, handle type chaining
9050 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
9051 if ( s.ifModified ) {
9052 modified = jqXHR.getResponseHeader( "Last-Modified" );
9054 jQuery.lastModified[ cacheURL ] = modified;
9056 modified = jqXHR.getResponseHeader( "etag" );
9058 jQuery.etag[ cacheURL ] = modified;
9063 if ( status === 204 || s.type === "HEAD" ) {
9064 statusText = "nocontent";
9067 } else if ( status === 304 ) {
9068 statusText = "notmodified";
9070 // If we have data, let's convert it
9072 statusText = response.state;
9073 success = response.data;
9074 error = response.error;
9079 // Extract error from statusText and normalize for non-aborts
9081 if ( status || !statusText ) {
9082 statusText = "error";
9089 // Set data for the fake xhr object
9090 jqXHR.status = status;
9091 jqXHR.statusText = ( nativeStatusText || statusText ) + "";
9095 deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
9097 deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
9100 // Status-dependent callbacks
9101 jqXHR.statusCode( statusCode );
9102 statusCode = undefined;
9104 if ( fireGlobals ) {
9105 globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
9106 [ jqXHR, s, isSuccess ? success : error ] );
9110 completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
9112 if ( fireGlobals ) {
9113 globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
9115 // Handle the global AJAX counter
9116 if ( !( --jQuery.active ) ) {
9117 jQuery.event.trigger( "ajaxStop" );
9125 getJSON: function( url, data, callback ) {
9126 return jQuery.get( url, data, callback, "json" );
9129 getScript: function( url, callback ) {
9130 return jQuery.get( url, undefined, callback, "script" );
9134 jQuery.each( [ "get", "post" ], function( i, method ) {
9135 jQuery[ method ] = function( url, data, callback, type ) {
9137 // Shift arguments if data argument was omitted
9138 if ( jQuery.isFunction( data ) ) {
9139 type = type || callback;
9144 // The url can be an options object (which then must have .url)
9145 return jQuery.ajax( jQuery.extend( {
9151 }, jQuery.isPlainObject( url ) && url ) );
9156 jQuery._evalUrl = function( url ) {
9157 return jQuery.ajax( {
9160 // Make this explicit, since user can override this through ajaxSetup (#11264)
9172 wrapAll: function( html ) {
9176 if ( jQuery.isFunction( html ) ) {
9177 html = html.call( this[ 0 ] );
9180 // The elements to wrap the target around
9181 wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
9183 if ( this[ 0 ].parentNode ) {
9184 wrap.insertBefore( this[ 0 ] );
9187 wrap.map( function() {
9190 while ( elem.firstElementChild ) {
9191 elem = elem.firstElementChild;
9201 wrapInner: function( html ) {
9202 if ( jQuery.isFunction( html ) ) {
9203 return this.each( function( i ) {
9204 jQuery( this ).wrapInner( html.call( this, i ) );
9208 return this.each( function() {
9209 var self = jQuery( this ),
9210 contents = self.contents();
9212 if ( contents.length ) {
9213 contents.wrapAll( html );
9216 self.append( html );
9221 wrap: function( html ) {
9222 var isFunction = jQuery.isFunction( html );
9224 return this.each( function( i ) {
9225 jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html );
9229 unwrap: function( selector ) {
9230 this.parent( selector ).not( "body" ).each( function() {
9231 jQuery( this ).replaceWith( this.childNodes );
9238 jQuery.expr.pseudos.hidden = function( elem ) {
9239 return !jQuery.expr.pseudos.visible( elem );
9241 jQuery.expr.pseudos.visible = function( elem ) {
9242 return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
9248 jQuery.ajaxSettings.xhr = function() {
9250 return new window.XMLHttpRequest();
9254 var xhrSuccessStatus = {
9256 // File protocol always yields status code 0, assume 200
9259 // Support: IE <=9 only
9260 // #1450: sometimes IE returns 1223 when it should be 204
9263 xhrSupported = jQuery.ajaxSettings.xhr();
9265 support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
9266 support.ajax = xhrSupported = !!xhrSupported;
9268 jQuery.ajaxTransport( function( options ) {
9269 var callback, errorCallback;
9271 // Cross domain only allowed if supported through XMLHttpRequest
9272 if ( support.cors || xhrSupported && !options.crossDomain ) {
9274 send: function( headers, complete ) {
9276 xhr = options.xhr();
9286 // Apply custom fields if provided
9287 if ( options.xhrFields ) {
9288 for ( i in options.xhrFields ) {
9289 xhr[ i ] = options.xhrFields[ i ];
9293 // Override mime type if needed
9294 if ( options.mimeType && xhr.overrideMimeType ) {
9295 xhr.overrideMimeType( options.mimeType );
9298 // X-Requested-With header
9299 // For cross-domain requests, seeing as conditions for a preflight are
9300 // akin to a jigsaw puzzle, we simply never set it to be sure.
9301 // (it can always be set on a per-request basis or even using ajaxSetup)
9302 // For same-domain requests, won't change header if already provided.
9303 if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
9304 headers[ "X-Requested-With" ] = "XMLHttpRequest";
9308 for ( i in headers ) {
9309 xhr.setRequestHeader( i, headers[ i ] );
9313 callback = function( type ) {
9316 callback = errorCallback = xhr.onload =
9317 xhr.onerror = xhr.onabort = xhr.onreadystatechange = null;
9319 if ( type === "abort" ) {
9321 } else if ( type === "error" ) {
9323 // Support: IE <=9 only
9324 // On a manual native abort, IE9 throws
9325 // errors on any property access that is not readyState
9326 if ( typeof xhr.status !== "number" ) {
9327 complete( 0, "error" );
9331 // File: protocol always yields status 0; see #8605, #14207
9338 xhrSuccessStatus[ xhr.status ] || xhr.status,
9341 // Support: IE <=9 only
9342 // IE9 has no XHR2 but throws on binary (trac-11426)
9343 // For XHR2 non-text, let the caller handle it (gh-2498)
9344 ( xhr.responseType || "text" ) !== "text" ||
9345 typeof xhr.responseText !== "string" ?
9346 { binary: xhr.response } :
9347 { text: xhr.responseText },
9348 xhr.getAllResponseHeaders()
9356 xhr.onload = callback();
9357 errorCallback = xhr.onerror = callback( "error" );
9359 // Support: IE 9 only
9360 // Use onreadystatechange to replace onabort
9361 // to handle uncaught aborts
9362 if ( xhr.onabort !== undefined ) {
9363 xhr.onabort = errorCallback;
9365 xhr.onreadystatechange = function() {
9367 // Check readyState before timeout as it changes
9368 if ( xhr.readyState === 4 ) {
9370 // Allow onerror to be called first,
9371 // but that will not handle a native abort
9372 // Also, save errorCallback to a variable
9373 // as xhr.onerror cannot be accessed
9374 window.setTimeout( function() {
9383 // Create the abort callback
9384 callback = callback( "abort" );
9388 // Do send the request (this may raise an exception)
9389 xhr.send( options.hasContent && options.data || null );
9392 // #14683: Only rethrow if this hasn't been notified as an error yet
9411 // Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
9412 jQuery.ajaxPrefilter( function( s ) {
9413 if ( s.crossDomain ) {
9414 s.contents.script = false;
9418 // Install script dataType
9421 script: "text/javascript, application/javascript, " +
9422 "application/ecmascript, application/x-ecmascript"
9425 script: /\b(?:java|ecma)script\b/
9428 "text script": function( text ) {
9429 jQuery.globalEval( text );
9435 // Handle cache's special case and crossDomain
9436 jQuery.ajaxPrefilter( "script", function( s ) {
9437 if ( s.cache === undefined ) {
9440 if ( s.crossDomain ) {
9445 // Bind script tag hack transport
9446 jQuery.ajaxTransport( "script", function( s ) {
9448 // This transport only deals with cross domain requests
9449 if ( s.crossDomain ) {
9450 var script, callback;
9452 send: function( _, complete ) {
9453 script = jQuery( "<script>" ).prop( {
9454 charset: s.scriptCharset,
9458 callback = function( evt ) {
9462 complete( evt.type === "error" ? 404 : 200, evt.type );
9467 // Use native DOM manipulation to avoid our domManip AJAX trickery
9468 document.head.appendChild( script[ 0 ] );
9482 var oldCallbacks = [],
9483 rjsonp = /(=)\?(?=&|$)|\?\?/;
9485 // Default jsonp settings
9488 jsonpCallback: function() {
9489 var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
9490 this[ callback ] = true;
9495 // Detect, normalize options and install callbacks for jsonp requests
9496 jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
9498 var callbackName, overwritten, responseContainer,
9499 jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
9501 typeof s.data === "string" &&
9502 ( s.contentType || "" )
9503 .indexOf( "application/x-www-form-urlencoded" ) === 0 &&
9504 rjsonp.test( s.data ) && "data"
9507 // Handle iff the expected data type is "jsonp" or we have a parameter to set
9508 if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
9510 // Get callback name, remembering preexisting value associated with it
9511 callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
9515 // Insert callback into url or form data
9517 s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
9518 } else if ( s.jsonp !== false ) {
9519 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
9522 // Use data converter to retrieve json after script execution
9523 s.converters[ "script json" ] = function() {
9524 if ( !responseContainer ) {
9525 jQuery.error( callbackName + " was not called" );
9527 return responseContainer[ 0 ];
9530 // Force json dataType
9531 s.dataTypes[ 0 ] = "json";
9534 overwritten = window[ callbackName ];
9535 window[ callbackName ] = function() {
9536 responseContainer = arguments;
9539 // Clean-up function (fires after converters)
9540 jqXHR.always( function() {
9542 // If previous value didn't exist - remove it
9543 if ( overwritten === undefined ) {
9544 jQuery( window ).removeProp( callbackName );
9546 // Otherwise restore preexisting value
9548 window[ callbackName ] = overwritten;
9551 // Save back as free
9552 if ( s[ callbackName ] ) {
9554 // Make sure that re-using the options doesn't screw things around
9555 s.jsonpCallback = originalSettings.jsonpCallback;
9557 // Save the callback name for future use
9558 oldCallbacks.push( callbackName );
9561 // Call if it was a function and we have a response
9562 if ( responseContainer && jQuery.isFunction( overwritten ) ) {
9563 overwritten( responseContainer[ 0 ] );
9566 responseContainer = overwritten = undefined;
9569 // Delegate to script
9577 // Support: Safari 8 only
9578 // In Safari 8 documents created via document.implementation.createHTMLDocument
9579 // collapse sibling forms: the second one becomes a child of the first one.
9580 // Because of that, this security measure has to be disabled in Safari 8.
9581 // https://bugs.webkit.org/show_bug.cgi?id=137337
9582 support.createHTMLDocument = ( function() {
9583 var body = document.implementation.createHTMLDocument( "" ).body;
9584 body.innerHTML = "<form></form><form></form>";
9585 return body.childNodes.length === 2;
9589 // Argument "data" should be string of html
9590 // context (optional): If specified, the fragment will be created in this context,
9591 // defaults to document
9592 // keepScripts (optional): If true, will include scripts passed in the html string
9593 jQuery.parseHTML = function( data, context, keepScripts ) {
9594 if ( typeof data !== "string" ) {
9597 if ( typeof context === "boolean" ) {
9598 keepScripts = context;
9602 var base, parsed, scripts;
9606 // Stop scripts or inline event handlers from being executed immediately
9607 // by using document.implementation
9608 if ( support.createHTMLDocument ) {
9609 context = document.implementation.createHTMLDocument( "" );
9611 // Set the base href for the created document
9612 // so any parsed elements with URLs
9613 // are based on the document's URL (gh-2965)
9614 base = context.createElement( "base" );
9615 base.href = document.location.href;
9616 context.head.appendChild( base );
9622 parsed = rsingleTag.exec( data );
9623 scripts = !keepScripts && [];
9627 return [ context.createElement( parsed[ 1 ] ) ];
9630 parsed = buildFragment( [ data ], context, scripts );
9632 if ( scripts && scripts.length ) {
9633 jQuery( scripts ).remove();
9636 return jQuery.merge( [], parsed.childNodes );
9641 * Load a url into a page
9643 jQuery.fn.load = function( url, params, callback ) {
9644 var selector, type, response,
9646 off = url.indexOf( " " );
9649 selector = jQuery.trim( url.slice( off ) );
9650 url = url.slice( 0, off );
9653 // If it's a function
9654 if ( jQuery.isFunction( params ) ) {
9656 // We assume that it's the callback
9660 // Otherwise, build a param string
9661 } else if ( params && typeof params === "object" ) {
9665 // If we have elements to modify, make the request
9666 if ( self.length > 0 ) {
9670 // If "type" variable is undefined, then "GET" method will be used.
9671 // Make value of this field explicit since
9672 // user can override it through ajaxSetup method
9673 type: type || "GET",
9676 } ).done( function( responseText ) {
9678 // Save response for use in complete callback
9679 response = arguments;
9681 self.html( selector ?
9683 // If a selector was specified, locate the right elements in a dummy div
9684 // Exclude scripts to avoid IE 'Permission Denied' errors
9685 jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :
9687 // Otherwise use the full result
9690 // If the request succeeds, this function gets "data", "status", "jqXHR"
9691 // but they are ignored because response was set above.
9692 // If it fails, this function gets "jqXHR", "status", "error"
9693 } ).always( callback && function( jqXHR, status ) {
9694 self.each( function() {
9695 callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
9706 // Attach a bunch of functions for handling common AJAX events
9714 ], function( i, type ) {
9715 jQuery.fn[ type ] = function( fn ) {
9716 return this.on( type, fn );
9723 jQuery.expr.pseudos.animated = function( elem ) {
9724 return jQuery.grep( jQuery.timers, function( fn ) {
9725 return elem === fn.elem;
9733 * Gets a window from an element
9735 function getWindow( elem ) {
9736 return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
9740 setOffset: function( elem, options, i ) {
9741 var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
9742 position = jQuery.css( elem, "position" ),
9743 curElem = jQuery( elem ),
9746 // Set position first, in-case top/left are set even on static elem
9747 if ( position === "static" ) {
9748 elem.style.position = "relative";
9751 curOffset = curElem.offset();
9752 curCSSTop = jQuery.css( elem, "top" );
9753 curCSSLeft = jQuery.css( elem, "left" );
9754 calculatePosition = ( position === "absolute" || position === "fixed" ) &&
9755 ( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1;
9757 // Need to be able to calculate position if either
9758 // top or left is auto and position is either absolute or fixed
9759 if ( calculatePosition ) {
9760 curPosition = curElem.position();
9761 curTop = curPosition.top;
9762 curLeft = curPosition.left;
9765 curTop = parseFloat( curCSSTop ) || 0;
9766 curLeft = parseFloat( curCSSLeft ) || 0;
9769 if ( jQuery.isFunction( options ) ) {
9771 // Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
9772 options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
9775 if ( options.top != null ) {
9776 props.top = ( options.top - curOffset.top ) + curTop;
9778 if ( options.left != null ) {
9779 props.left = ( options.left - curOffset.left ) + curLeft;
9782 if ( "using" in options ) {
9783 options.using.call( elem, props );
9786 curElem.css( props );
9792 offset: function( options ) {
9794 // Preserve chaining for setter
9795 if ( arguments.length ) {
9796 return options === undefined ?
9798 this.each( function( i ) {
9799 jQuery.offset.setOffset( this, options, i );
9803 var docElem, win, rect, doc,
9810 // Support: IE <=11 only
9811 // Running getBoundingClientRect on a
9812 // disconnected node in IE throws an error
9813 if ( !elem.getClientRects().length ) {
9814 return { top: 0, left: 0 };
9817 rect = elem.getBoundingClientRect();
9819 // Make sure element is not hidden (display: none)
9820 if ( rect.width || rect.height ) {
9821 doc = elem.ownerDocument;
9822 win = getWindow( doc );
9823 docElem = doc.documentElement;
9826 top: rect.top + win.pageYOffset - docElem.clientTop,
9827 left: rect.left + win.pageXOffset - docElem.clientLeft
9831 // Return zeros for disconnected and hidden elements (gh-2310)
9835 position: function() {
9840 var offsetParent, offset,
9842 parentOffset = { top: 0, left: 0 };
9844 // Fixed elements are offset from window (parentOffset = {top:0, left: 0},
9845 // because it is its only offset parent
9846 if ( jQuery.css( elem, "position" ) === "fixed" ) {
9848 // Assume getBoundingClientRect is there when computed position is fixed
9849 offset = elem.getBoundingClientRect();
9853 // Get *real* offsetParent
9854 offsetParent = this.offsetParent();
9856 // Get correct offsets
9857 offset = this.offset();
9858 if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
9859 parentOffset = offsetParent.offset();
9862 // Add offsetParent borders
9864 top: parentOffset.top + jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ),
9865 left: parentOffset.left + jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true )
9869 // Subtract parent offsets and element margins
9871 top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
9872 left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
9876 // This method will return documentElement in the following cases:
9877 // 1) For the element inside the iframe without offsetParent, this method will return
9878 // documentElement of the parent window
9879 // 2) For the hidden or detached element
9880 // 3) For body or html element, i.e. in case of the html node - it will return itself
9882 // but those exceptions were never presented as a real life use-cases
9883 // and might be considered as more preferable results.
9885 // This logic, however, is not guaranteed and can change at any point in the future
9886 offsetParent: function() {
9887 return this.map( function() {
9888 var offsetParent = this.offsetParent;
9890 while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
9891 offsetParent = offsetParent.offsetParent;
9894 return offsetParent || documentElement;
9899 // Create scrollLeft and scrollTop methods
9900 jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
9901 var top = "pageYOffset" === prop;
9903 jQuery.fn[ method ] = function( val ) {
9904 return access( this, function( elem, method, val ) {
9905 var win = getWindow( elem );
9907 if ( val === undefined ) {
9908 return win ? win[ prop ] : elem[ method ];
9913 !top ? val : win.pageXOffset,
9914 top ? val : win.pageYOffset
9918 elem[ method ] = val;
9920 }, method, val, arguments.length );
9924 // Support: Safari <=7 - 9.1, Chrome <=37 - 49
9925 // Add the top/left cssHooks using jQuery.fn.position
9926 // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
9927 // Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
9928 // getComputedStyle returns percent when specified for top/left/bottom/right;
9929 // rather than make the css module depend on the offset module, just check for it here
9930 jQuery.each( [ "top", "left" ], function( i, prop ) {
9931 jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
9932 function( elem, computed ) {
9934 computed = curCSS( elem, prop );
9936 // If curCSS returns percentage, fallback to offset
9937 return rnumnonpx.test( computed ) ?
9938 jQuery( elem ).position()[ prop ] + "px" :
9946 // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
9947 jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
9948 jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name },
9949 function( defaultExtra, funcName ) {
9951 // Margin is only for outerHeight, outerWidth
9952 jQuery.fn[ funcName ] = function( margin, value ) {
9953 var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
9954 extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
9956 return access( this, function( elem, type, value ) {
9959 if ( jQuery.isWindow( elem ) ) {
9961 // $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
9962 return funcName.indexOf( "outer" ) === 0 ?
9963 elem[ "inner" + name ] :
9964 elem.document.documentElement[ "client" + name ];
9967 // Get document width or height
9968 if ( elem.nodeType === 9 ) {
9969 doc = elem.documentElement;
9971 // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
9972 // whichever is greatest
9974 elem.body[ "scroll" + name ], doc[ "scroll" + name ],
9975 elem.body[ "offset" + name ], doc[ "offset" + name ],
9976 doc[ "client" + name ]
9980 return value === undefined ?
9982 // Get width or height on the element, requesting but not forcing parseFloat
9983 jQuery.css( elem, type, extra ) :
9985 // Set width or height on the element
9986 jQuery.style( elem, type, value, extra );
9987 }, type, chainable ? margin : undefined, chainable );
9995 bind: function( types, data, fn ) {
9996 return this.on( types, null, data, fn );
9998 unbind: function( types, fn ) {
9999 return this.off( types, null, fn );
10002 delegate: function( selector, types, data, fn ) {
10003 return this.on( types, selector, data, fn );
10005 undelegate: function( selector, types, fn ) {
10007 // ( namespace ) or ( selector, types [, fn] )
10008 return arguments.length === 1 ?
10009 this.off( selector, "**" ) :
10010 this.off( types, selector || "**", fn );
10014 jQuery.parseJSON = JSON.parse;
10019 // Register as a named AMD module, since jQuery can be concatenated with other
10020 // files that may use define, but not via a proper concatenation script that
10021 // understands anonymous AMD modules. A named AMD is safest and most robust
10022 // way to register. Lowercase jquery is used because AMD module names are
10023 // derived from file names, and jQuery is normally delivered in a lowercase
10024 // file name. Do this after creating the global so that if an AMD module wants
10025 // to call noConflict to hide this version of jQuery, it will work.
10027 // Note that for maximum portability, libraries that are not jQuery should
10028 // declare themselves as anonymous modules, and avoid setting a global if an
10029 // AMD loader is present. jQuery is a special case. For more information, see
10030 // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
10032 if ( typeof define === "function" && define.amd ) {
10033 define( "jquery", [], function() {
10044 // Map over jQuery in case of overwrite
10045 _jQuery = window.jQuery,
10047 // Map over the $ in case of overwrite
10050 jQuery.noConflict = function( deep ) {
10051 if ( window.$ === jQuery ) {
10055 if ( deep && window.jQuery === jQuery ) {
10056 window.jQuery = _jQuery;
10062 // Expose jQuery and $ identifiers, even in AMD
10063 // (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
10064 // and CommonJS for browser emulators (#13566)
10066 window.jQuery = window.$ = jQuery;
10074 * @license AngularJS v1.5.11
10075 * (c) 2010-2017 Google, Inc. http://angularjs.org
10079 var _jQuery = window.jQuery.noConflict(true);
10084 * This object provides a utility for producing rich Error messages within
10085 * Angular. It can be called as follows:
10087 * var exampleMinErr = minErr('example');
10088 * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
10090 * The above creates an instance of minErr in the example namespace. The
10091 * resulting error will have a namespaced error code of example.one. The
10092 * resulting error will replace {0} with the value of foo, and {1} with the
10093 * value of bar. The object is not restricted in the number of arguments it can
10096 * If fewer arguments are specified than necessary for interpolation, the extra
10097 * interpolation markers will be preserved in the final string.
10099 * Since data will be parsed statically during a build step, some restrictions
10100 * are applied with respect to how minErr instances are created and called.
10101 * Instances should have names of the form namespaceMinErr for a minErr created
10102 * using minErr('namespace') . Error codes, namespaces and template strings
10103 * should all be static strings, not variables or general expressions.
10105 * @param {string} module The namespace to use for the new minErr instance.
10106 * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
10107 * error from returned function, for cases when a particular type of error is useful.
10108 * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
10111 function minErr(module, ErrorConstructor) {
10112 ErrorConstructor = ErrorConstructor || Error;
10113 return function() {
10114 var SKIP_INDEXES = 2;
10116 var templateArgs = arguments,
10117 code = templateArgs[0],
10118 message = '[' + (module ? module + ':' : '') + code + '] ',
10119 template = templateArgs[1],
10122 message += template.replace(/\{\d+\}/g, function(match) {
10123 var index = +match.slice(1, -1),
10124 shiftedIndex = index + SKIP_INDEXES;
10126 if (shiftedIndex < templateArgs.length) {
10127 return toDebugString(templateArgs[shiftedIndex]);
10133 message += '\nhttp://errors.angularjs.org/1.5.11/' +
10134 (module ? module + '/' : '') + code;
10136 for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
10137 message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
10138 encodeURIComponent(toDebugString(templateArgs[i]));
10141 return new ErrorConstructor(message);
10145 /* We need to tell ESLint what variables are being exported */
10158 REGEX_STRING_REGEXP,
10159 VALIDITY_STATE_PROPERTY,
10213 convertTimezoneToLocal,
10216 tryDecodeURIComponent,
10228 assertNotHasOwnProperty,
10235 NODE_TYPE_ATTRIBUTE,
10238 NODE_TYPE_DOCUMENT,
10239 NODE_TYPE_DOCUMENT_FRAGMENT
10242 ////////////////////////////////////
10251 * # ng (core module)
10252 * The ng module is loaded by default when an AngularJS application is started. The module itself
10253 * contains the essential components for an AngularJS application to function. The table below
10254 * lists a high level breakdown of each of the services/factories, filters, directives and testing
10255 * components available within this core module.
10257 * <div doc-module-components="ng"></div>
10260 var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
10262 // The name of a form control's ValidityState property.
10263 // This is used so that it's possible for internal tests to create mock ValidityStates.
10264 var VALIDITY_STATE_PROPERTY = 'validity';
10266 var hasOwnProperty = Object.prototype.hasOwnProperty;
10268 var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
10269 var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
10272 var manualLowercase = function(s) {
10273 /* eslint-disable no-bitwise */
10275 ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
10277 /* eslint-enable */
10279 var manualUppercase = function(s) {
10280 /* eslint-disable no-bitwise */
10282 ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
10284 /* eslint-enable */
10288 // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
10289 // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
10290 // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
10291 if ('i' !== 'I'.toLowerCase()) {
10292 lowercase = manualLowercase;
10293 uppercase = manualUppercase;
10298 msie, // holds major version number for IE, or NaN if UA is not IE.
10299 jqLite, // delay binding since jQuery could be loaded after us.
10300 jQuery, // delay binding
10302 splice = [].splice,
10304 toString = Object.prototype.toString,
10305 getPrototypeOf = Object.getPrototypeOf,
10306 ngMinErr = minErr('ng'),
10308 /** @name angular */
10309 angular = window.angular || (window.angular = {}),
10314 * documentMode is an IE-only property
10315 * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
10317 msie = window.document.documentMode;
10323 * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
10326 function isArrayLike(obj) {
10328 // `null`, `undefined` and `window` are not array-like
10329 if (obj == null || isWindow(obj)) return false;
10331 // arrays, strings and jQuery/jqLite objects are array like
10332 // * jqLite is either the jQuery or jqLite constructor function
10333 // * we have to check the existence of jqLite first as this method is called
10334 // via the forEach method when constructing the jqLite object in the first place
10335 if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
10337 // Support: iOS 8.2 (not reproducible in simulator)
10338 // "length" in obj used to prevent JIT error (gh-11508)
10339 var length = 'length' in Object(obj) && obj.length;
10341 // NodeList objects (with `item` method) and
10342 // other objects with suitable length characteristics are array-like
10343 return isNumber(length) &&
10344 (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function');
10350 * @name angular.forEach
10355 * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
10356 * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
10357 * is the value of an object property or an array element, `key` is the object property key or
10358 * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
10360 * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
10361 * using the `hasOwnProperty` method.
10364 * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
10365 * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
10366 * return the value provided.
10369 var values = {name: 'misko', gender: 'male'};
10371 angular.forEach(values, function(value, key) {
10372 this.push(key + ': ' + value);
10374 expect(log).toEqual(['name: misko', 'gender: male']);
10377 * @param {Object|Array} obj Object to iterate over.
10378 * @param {Function} iterator Iterator function.
10379 * @param {Object=} context Object to become context (`this`) for the iterator function.
10380 * @returns {Object|Array} Reference to `obj`.
10383 function forEach(obj, iterator, context) {
10386 if (isFunction(obj)) {
10388 // Need to check if hasOwnProperty exists,
10389 // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
10390 if (key !== 'prototype' && key !== 'length' && key !== 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
10391 iterator.call(context, obj[key], key, obj);
10394 } else if (isArray(obj) || isArrayLike(obj)) {
10395 var isPrimitive = typeof obj !== 'object';
10396 for (key = 0, length = obj.length; key < length; key++) {
10397 if (isPrimitive || key in obj) {
10398 iterator.call(context, obj[key], key, obj);
10401 } else if (obj.forEach && obj.forEach !== forEach) {
10402 obj.forEach(iterator, context, obj);
10403 } else if (isBlankObject(obj)) {
10404 // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
10406 iterator.call(context, obj[key], key, obj);
10408 } else if (typeof obj.hasOwnProperty === 'function') {
10409 // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
10411 if (obj.hasOwnProperty(key)) {
10412 iterator.call(context, obj[key], key, obj);
10416 // Slow path for objects which do not have a method `hasOwnProperty`
10418 if (hasOwnProperty.call(obj, key)) {
10419 iterator.call(context, obj[key], key, obj);
10427 function forEachSorted(obj, iterator, context) {
10428 var keys = Object.keys(obj).sort();
10429 for (var i = 0; i < keys.length; i++) {
10430 iterator.call(context, obj[keys[i]], keys[i]);
10437 * when using forEach the params are value, key, but it is often useful to have key, value.
10438 * @param {function(string, *)} iteratorFn
10439 * @returns {function(*, string)}
10441 function reverseParams(iteratorFn) {
10442 return function(value, key) {iteratorFn(key, value);};
10446 * A consistent way of creating unique IDs in angular.
10448 * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
10449 * we hit number precision issues in JavaScript.
10451 * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
10453 * @returns {number} an unique alpha-numeric string
10455 function nextUid() {
10461 * Set or clear the hashkey for an object.
10462 * @param obj object
10463 * @param h the hashkey (!truthy to delete the hashkey)
10465 function setHashKey(obj, h) {
10469 delete obj.$$hashKey;
10474 function baseExtend(dst, objs, deep) {
10475 var h = dst.$$hashKey;
10477 for (var i = 0, ii = objs.length; i < ii; ++i) {
10479 if (!isObject(obj) && !isFunction(obj)) continue;
10480 var keys = Object.keys(obj);
10481 for (var j = 0, jj = keys.length; j < jj; j++) {
10483 var src = obj[key];
10485 if (deep && isObject(src)) {
10487 dst[key] = new Date(src.valueOf());
10488 } else if (isRegExp(src)) {
10489 dst[key] = new RegExp(src);
10490 } else if (src.nodeName) {
10491 dst[key] = src.cloneNode(true);
10492 } else if (isElement(src)) {
10493 dst[key] = src.clone();
10495 if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
10496 baseExtend(dst[key], [src], true);
10504 setHashKey(dst, h);
10510 * @name angular.extend
10515 * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
10516 * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
10517 * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
10519 * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
10520 * {@link angular.merge} for this.
10522 * @param {Object} dst Destination object.
10523 * @param {...Object} src Source object(s).
10524 * @returns {Object} Reference to `dst`.
10526 function extend(dst) {
10527 return baseExtend(dst, slice.call(arguments, 1), false);
10533 * @name angular.merge
10538 * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
10539 * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
10540 * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
10542 * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
10543 * objects, performing a deep copy.
10545 * @param {Object} dst Destination object.
10546 * @param {...Object} src Source object(s).
10547 * @returns {Object} Reference to `dst`.
10549 function merge(dst) {
10550 return baseExtend(dst, slice.call(arguments, 1), true);
10555 function toInt(str) {
10556 return parseInt(str, 10);
10559 var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
10560 // eslint-disable-next-line no-self-compare
10561 return num !== num;
10565 function inherit(parent, extra) {
10566 return extend(Object.create(parent), extra);
10571 * @name angular.noop
10576 * A function that performs no operations. This function can be useful when writing code in the
10577 * functional style.
10579 function foo(callback) {
10580 var result = calculateResult();
10581 (callback || angular.noop)(result);
10591 * @name angular.identity
10596 * A function that returns its first argument. This function is useful when writing code in the
10597 * functional style.
10600 function transformer(transformationFn, value) {
10601 return (transformationFn || angular.identity)(value);
10605 function getResult(fn, input) {
10606 return (fn || angular.identity)(input);
10609 getResult(function(n) { return n * 2; }, 21); // returns 42
10610 getResult(null, 21); // returns 21
10611 getResult(undefined, 21); // returns 21
10614 * @param {*} value to be returned.
10615 * @returns {*} the value passed in.
10617 function identity($) {return $;}
10618 identity.$inject = [];
10621 function valueFn(value) {return function valueRef() {return value;};}
10623 function hasCustomToString(obj) {
10624 return isFunction(obj.toString) && obj.toString !== toString;
10630 * @name angular.isUndefined
10635 * Determines if a reference is undefined.
10637 * @param {*} value Reference to check.
10638 * @returns {boolean} True if `value` is undefined.
10640 function isUndefined(value) {return typeof value === 'undefined';}
10645 * @name angular.isDefined
10650 * Determines if a reference is defined.
10652 * @param {*} value Reference to check.
10653 * @returns {boolean} True if `value` is defined.
10655 function isDefined(value) {return typeof value !== 'undefined';}
10660 * @name angular.isObject
10665 * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
10666 * considered to be objects. Note that JavaScript arrays are objects.
10668 * @param {*} value Reference to check.
10669 * @returns {boolean} True if `value` is an `Object` but not `null`.
10671 function isObject(value) {
10672 // http://jsperf.com/isobject4
10673 return value !== null && typeof value === 'object';
10678 * Determine if a value is an object with a null prototype
10680 * @returns {boolean} True if `value` is an `Object` with a null prototype
10682 function isBlankObject(value) {
10683 return value !== null && typeof value === 'object' && !getPrototypeOf(value);
10689 * @name angular.isString
10694 * Determines if a reference is a `String`.
10696 * @param {*} value Reference to check.
10697 * @returns {boolean} True if `value` is a `String`.
10699 function isString(value) {return typeof value === 'string';}
10704 * @name angular.isNumber
10709 * Determines if a reference is a `Number`.
10711 * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
10713 * If you wish to exclude these then you can use the native
10714 * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
10717 * @param {*} value Reference to check.
10718 * @returns {boolean} True if `value` is a `Number`.
10720 function isNumber(value) {return typeof value === 'number';}
10725 * @name angular.isDate
10730 * Determines if a value is a date.
10732 * @param {*} value Reference to check.
10733 * @returns {boolean} True if `value` is a `Date`.
10735 function isDate(value) {
10736 return toString.call(value) === '[object Date]';
10742 * @name angular.isArray
10747 * Determines if a reference is an `Array`. Alias of Array.isArray.
10749 * @param {*} value Reference to check.
10750 * @returns {boolean} True if `value` is an `Array`.
10752 var isArray = Array.isArray;
10756 * @name angular.isFunction
10761 * Determines if a reference is a `Function`.
10763 * @param {*} value Reference to check.
10764 * @returns {boolean} True if `value` is a `Function`.
10766 function isFunction(value) {return typeof value === 'function';}
10770 * Determines if a value is a regular expression object.
10773 * @param {*} value Reference to check.
10774 * @returns {boolean} True if `value` is a `RegExp`.
10776 function isRegExp(value) {
10777 return toString.call(value) === '[object RegExp]';
10782 * Checks if `obj` is a window object.
10785 * @param {*} obj Object to check
10786 * @returns {boolean} True if `obj` is a window obj.
10788 function isWindow(obj) {
10789 return obj && obj.window === obj;
10793 function isScope(obj) {
10794 return obj && obj.$evalAsync && obj.$watch;
10798 function isFile(obj) {
10799 return toString.call(obj) === '[object File]';
10803 function isFormData(obj) {
10804 return toString.call(obj) === '[object FormData]';
10808 function isBlob(obj) {
10809 return toString.call(obj) === '[object Blob]';
10813 function isBoolean(value) {
10814 return typeof value === 'boolean';
10818 function isPromiseLike(obj) {
10819 return obj && isFunction(obj.then);
10823 var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/;
10824 function isTypedArray(value) {
10825 return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
10828 function isArrayBuffer(obj) {
10829 return toString.call(obj) === '[object ArrayBuffer]';
10833 var trim = function(value) {
10834 return isString(value) ? value.trim() : value;
10838 // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
10839 // Prereq: s is a string.
10840 var escapeForRegexp = function(s) {
10842 .replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1')
10843 // eslint-disable-next-line no-control-regex
10844 .replace(/\x08/g, '\\x08');
10850 * @name angular.isElement
10855 * Determines if a reference is a DOM element (or wrapped jQuery element).
10857 * @param {*} value Reference to check.
10858 * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
10860 function isElement(node) {
10862 (node.nodeName // We are a direct element.
10863 || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API.
10867 * @param str 'key1,key2,...'
10868 * @returns {object} in the form of {key1:true, key2:true, ...}
10870 function makeMap(str) {
10871 var obj = {}, items = str.split(','), i;
10872 for (i = 0; i < items.length; i++) {
10873 obj[items[i]] = true;
10879 function nodeName_(element) {
10880 return lowercase(element.nodeName || (element[0] && element[0].nodeName));
10883 function includes(array, obj) {
10884 return Array.prototype.indexOf.call(array, obj) !== -1;
10887 function arrayRemove(array, value) {
10888 var index = array.indexOf(value);
10890 array.splice(index, 1);
10897 * @name angular.copy
10902 * Creates a deep copy of `source`, which should be an object or an array.
10904 * * If no destination is supplied, a copy of the object or array is created.
10905 * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
10906 * are deleted and then all elements/properties from the source are copied to it.
10907 * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
10908 * * If `source` is identical to `destination` an exception will be thrown.
10911 * <div class="alert alert-warning">
10912 * Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
10913 * and on `destination`) will be ignored.
10916 * @param {*} source The source that will be used to make a copy.
10917 * Can be any type, including primitives, `null`, and `undefined`.
10918 * @param {(Object|Array)=} destination Destination into which the source is copied. If
10919 * provided, must be of the same type as `source`.
10920 * @returns {*} The copy or updated `destination`, if `destination` was specified.
10923 <example module="copyExample" name="angular-copy">
10924 <file name="index.html">
10925 <div ng-controller="ExampleController">
10926 <form novalidate class="simple-form">
10927 <label>Name: <input type="text" ng-model="user.name" /></label><br />
10928 <label>Age: <input type="number" ng-model="user.age" /></label><br />
10929 Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
10930 <label><input type="radio" ng-model="user.gender" value="female" />female</label><br />
10931 <button ng-click="reset()">RESET</button>
10932 <button ng-click="update(user)">SAVE</button>
10934 <pre>form = {{user | json}}</pre>
10935 <pre>master = {{master | json}}</pre>
10938 <file name="script.js">
10939 // Module: copyExample
10941 module('copyExample', []).
10942 controller('ExampleController', ['$scope', function($scope) {
10943 $scope.master = {};
10945 $scope.reset = function() {
10946 // Example with 1 argument
10947 $scope.user = angular.copy($scope.master);
10950 $scope.update = function(user) {
10951 // Example with 2 arguments
10952 angular.copy(user, $scope.master);
10960 function copy(source, destination) {
10961 var stackSource = [];
10962 var stackDest = [];
10965 if (isTypedArray(destination) || isArrayBuffer(destination)) {
10966 throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
10968 if (source === destination) {
10969 throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
10972 // Empty the destination object
10973 if (isArray(destination)) {
10974 destination.length = 0;
10976 forEach(destination, function(value, key) {
10977 if (key !== '$$hashKey') {
10978 delete destination[key];
10983 stackSource.push(source);
10984 stackDest.push(destination);
10985 return copyRecurse(source, destination);
10988 return copyElement(source);
10990 function copyRecurse(source, destination) {
10991 var h = destination.$$hashKey;
10993 if (isArray(source)) {
10994 for (var i = 0, ii = source.length; i < ii; i++) {
10995 destination.push(copyElement(source[i]));
10997 } else if (isBlankObject(source)) {
10998 // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
10999 for (key in source) {
11000 destination[key] = copyElement(source[key]);
11002 } else if (source && typeof source.hasOwnProperty === 'function') {
11003 // Slow path, which must rely on hasOwnProperty
11004 for (key in source) {
11005 if (source.hasOwnProperty(key)) {
11006 destination[key] = copyElement(source[key]);
11010 // Slowest path --- hasOwnProperty can't be called as a method
11011 for (key in source) {
11012 if (hasOwnProperty.call(source, key)) {
11013 destination[key] = copyElement(source[key]);
11017 setHashKey(destination, h);
11018 return destination;
11021 function copyElement(source) {
11023 if (!isObject(source)) {
11027 // Already copied values
11028 var index = stackSource.indexOf(source);
11029 if (index !== -1) {
11030 return stackDest[index];
11033 if (isWindow(source) || isScope(source)) {
11034 throw ngMinErr('cpws',
11035 'Can\'t copy! Making copies of Window or Scope instances is not supported.');
11038 var needsRecurse = false;
11039 var destination = copyType(source);
11041 if (destination === undefined) {
11042 destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
11043 needsRecurse = true;
11046 stackSource.push(source);
11047 stackDest.push(destination);
11049 return needsRecurse
11050 ? copyRecurse(source, destination)
11054 function copyType(source) {
11055 switch (toString.call(source)) {
11056 case '[object Int8Array]':
11057 case '[object Int16Array]':
11058 case '[object Int32Array]':
11059 case '[object Float32Array]':
11060 case '[object Float64Array]':
11061 case '[object Uint8Array]':
11062 case '[object Uint8ClampedArray]':
11063 case '[object Uint16Array]':
11064 case '[object Uint32Array]':
11065 return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
11067 case '[object ArrayBuffer]':
11069 if (!source.slice) {
11070 // If we're in this case we know the environment supports ArrayBuffer
11071 /* eslint-disable no-undef */
11072 var copied = new ArrayBuffer(source.byteLength);
11073 new Uint8Array(copied).set(new Uint8Array(source));
11074 /* eslint-enable */
11077 return source.slice(0);
11079 case '[object Boolean]':
11080 case '[object Number]':
11081 case '[object String]':
11082 case '[object Date]':
11083 return new source.constructor(source.valueOf());
11085 case '[object RegExp]':
11086 var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);
11087 re.lastIndex = source.lastIndex;
11090 case '[object Blob]':
11091 return new source.constructor([source], {type: source.type});
11094 if (isFunction(source.cloneNode)) {
11095 return source.cloneNode(true);
11103 * @name angular.equals
11108 * Determines if two objects or two values are equivalent. Supports value types, regular
11109 * expressions, arrays and objects.
11111 * Two objects or values are considered equivalent if at least one of the following is true:
11113 * * Both objects or values pass `===` comparison.
11114 * * Both objects or values are of the same type and all of their properties are equal by
11115 * comparing them with `angular.equals`.
11116 * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
11117 * * Both values represent the same regular expression (In JavaScript,
11118 * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
11119 * representation matches).
11121 * During a property comparison, properties of `function` type and properties with names
11122 * that begin with `$` are ignored.
11124 * Scope and DOMWindow objects are being compared only by identify (`===`).
11126 * @param {*} o1 Object or value to compare.
11127 * @param {*} o2 Object or value to compare.
11128 * @returns {boolean} True if arguments are equal.
11131 <example module="equalsExample" name="equalsExample">
11132 <file name="index.html">
11133 <div ng-controller="ExampleController">
11136 Name: <input type="text" ng-model="user1.name">
11137 Age: <input type="number" ng-model="user1.age">
11140 Name: <input type="text" ng-model="user2.name">
11141 Age: <input type="number" ng-model="user2.age">
11145 <input type="button" value="Compare" ng-click="compare()">
11147 User 1: <pre>{{user1 | json}}</pre>
11148 User 2: <pre>{{user2 | json}}</pre>
11149 Equal: <pre>{{result}}</pre>
11153 <file name="script.js">
11154 angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
11157 $scope.compare = function() {
11158 $scope.result = angular.equals($scope.user1, $scope.user2);
11164 function equals(o1, o2) {
11165 if (o1 === o2) return true;
11166 if (o1 === null || o2 === null) return false;
11167 // eslint-disable-next-line no-self-compare
11168 if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
11169 var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
11170 if (t1 === t2 && t1 === 'object') {
11172 if (!isArray(o2)) return false;
11173 if ((length = o1.length) === o2.length) {
11174 for (key = 0; key < length; key++) {
11175 if (!equals(o1[key], o2[key])) return false;
11179 } else if (isDate(o1)) {
11180 if (!isDate(o2)) return false;
11181 return equals(o1.getTime(), o2.getTime());
11182 } else if (isRegExp(o1)) {
11183 if (!isRegExp(o2)) return false;
11184 return o1.toString() === o2.toString();
11186 if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
11187 isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
11188 keySet = createMap();
11190 if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
11191 if (!equals(o1[key], o2[key])) return false;
11192 keySet[key] = true;
11195 if (!(key in keySet) &&
11196 key.charAt(0) !== '$' &&
11197 isDefined(o2[key]) &&
11198 !isFunction(o2[key])) return false;
11206 var csp = function() {
11207 if (!isDefined(csp.rules)) {
11210 var ngCspElement = (window.document.querySelector('[ng-csp]') ||
11211 window.document.querySelector('[data-ng-csp]'));
11213 if (ngCspElement) {
11214 var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
11215 ngCspElement.getAttribute('data-ng-csp');
11217 noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
11218 noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
11222 noUnsafeEval: noUnsafeEval(),
11223 noInlineStyle: false
11230 function noUnsafeEval() {
11232 // eslint-disable-next-line no-new, no-new-func
11247 * @param {string=} ngJq the name of the library available under `window`
11248 * to be used for angular.element
11250 * Use this directive to force the angular.element library. This should be
11251 * used to force either jqLite by leaving ng-jq blank or setting the name of
11252 * the jquery variable under window (eg. jQuery).
11254 * Since angular looks for this directive when it is loaded (doesn't wait for the
11255 * DOMContentLoaded event), it must be placed on an element that comes before the script
11256 * which loads angular. Also, only the first instance of `ng-jq` will be used and all
11260 * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
11263 <html ng-app ng-jq>
11269 * This example shows how to use a jQuery based library of a different name.
11270 * The library name must be available at the top most 'window'.
11273 <html ng-app ng-jq="jQueryLib">
11279 var jq = function() {
11280 if (isDefined(jq.name_)) return jq.name_;
11282 var i, ii = ngAttrPrefixes.length, prefix, name;
11283 for (i = 0; i < ii; ++i) {
11284 prefix = ngAttrPrefixes[i];
11285 el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]');
11287 name = el.getAttribute(prefix + 'jq');
11292 return (jq.name_ = name);
11295 function concat(array1, array2, index) {
11296 return array1.concat(slice.call(array2, index));
11299 function sliceArgs(args, startIndex) {
11300 return slice.call(args, startIndex || 0);
11306 * @name angular.bind
11311 * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
11312 * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
11313 * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
11314 * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
11316 * @param {Object} self Context which `fn` should be evaluated in.
11317 * @param {function()} fn Function to be bound.
11318 * @param {...*} args Optional arguments to be prebound to the `fn` function call.
11319 * @returns {function()} Function that wraps the `fn` with all the specified bindings.
11321 function bind(self, fn) {
11322 var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
11323 if (isFunction(fn) && !(fn instanceof RegExp)) {
11324 return curryArgs.length
11326 return arguments.length
11327 ? fn.apply(self, concat(curryArgs, arguments, 0))
11328 : fn.apply(self, curryArgs);
11331 return arguments.length
11332 ? fn.apply(self, arguments)
11336 // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
11342 function toJsonReplacer(key, value) {
11345 if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
11347 } else if (isWindow(value)) {
11349 } else if (value && window.document === value) {
11351 } else if (isScope(value)) {
11361 * @name angular.toJson
11366 * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
11367 * stripped since angular uses this notation internally.
11369 * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON.
11370 * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
11371 * If set to an integer, the JSON output will contain that many spaces per indentation.
11372 * @returns {string|undefined} JSON-ified string representing `obj`.
11375 * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
11376 * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
11377 * `Date.prototype.toJSON` method as follows:
11380 * var _DatetoJSON = Date.prototype.toJSON;
11381 * Date.prototype.toJSON = function() {
11383 * return _DatetoJSON.call(this);
11385 * if (e instanceof RangeError) {
11393 * See https://github.com/angular/angular.js/pull/14221 for more information.
11395 function toJson(obj, pretty) {
11396 if (isUndefined(obj)) return undefined;
11397 if (!isNumber(pretty)) {
11398 pretty = pretty ? 2 : null;
11400 return JSON.stringify(obj, toJsonReplacer, pretty);
11406 * @name angular.fromJson
11411 * Deserializes a JSON string.
11413 * @param {string} json JSON string to deserialize.
11414 * @returns {Object|Array|string|number} Deserialized JSON string.
11416 function fromJson(json) {
11417 return isString(json)
11423 var ALL_COLONS = /:/g;
11424 function timezoneToOffset(timezone, fallback) {
11425 // IE/Edge do not "understand" colon (`:`) in timezone
11426 timezone = timezone.replace(ALL_COLONS, '');
11427 var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
11428 return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
11432 function addDateMinutes(date, minutes) {
11433 date = new Date(date.getTime());
11434 date.setMinutes(date.getMinutes() + minutes);
11439 function convertTimezoneToLocal(date, timezone, reverse) {
11440 reverse = reverse ? -1 : 1;
11441 var dateTimezoneOffset = date.getTimezoneOffset();
11442 var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
11443 return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
11448 * @returns {string} Returns the string representation of the element.
11450 function startingTag(element) {
11451 element = jqLite(element).clone();
11453 // turns out IE does not let you set .html() on elements which
11454 // are not allowed to have children. So we just ignore it.
11456 } catch (e) { /* empty */ }
11457 var elemHtml = jqLite('<div>').append(element).html();
11459 return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
11461 match(/^(<[^>]+>)/)[1].
11462 replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
11464 return lowercase(elemHtml);
11470 /////////////////////////////////////////////////
11473 * Tries to decode the URI component without throwing an exception.
11476 * @param str value potential URI component to check.
11477 * @returns {boolean} True if `value` can be decoded
11478 * with the decodeURIComponent function.
11480 function tryDecodeURIComponent(value) {
11482 return decodeURIComponent(value);
11484 // Ignore any invalid uri component.
11490 * Parses an escaped url query string into key-value pairs.
11491 * @returns {Object.<string,boolean|Array>}
11493 function parseKeyValue(/**string*/keyValue) {
11495 forEach((keyValue || '').split('&'), function(keyValue) {
11496 var splitPoint, key, val;
11498 key = keyValue = keyValue.replace(/\+/g,'%20');
11499 splitPoint = keyValue.indexOf('=');
11500 if (splitPoint !== -1) {
11501 key = keyValue.substring(0, splitPoint);
11502 val = keyValue.substring(splitPoint + 1);
11504 key = tryDecodeURIComponent(key);
11505 if (isDefined(key)) {
11506 val = isDefined(val) ? tryDecodeURIComponent(val) : true;
11507 if (!hasOwnProperty.call(obj, key)) {
11509 } else if (isArray(obj[key])) {
11510 obj[key].push(val);
11512 obj[key] = [obj[key],val];
11520 function toKeyValue(obj) {
11522 forEach(obj, function(value, key) {
11523 if (isArray(value)) {
11524 forEach(value, function(arrayValue) {
11525 parts.push(encodeUriQuery(key, true) +
11526 (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
11529 parts.push(encodeUriQuery(key, true) +
11530 (value === true ? '' : '=' + encodeUriQuery(value, true)));
11533 return parts.length ? parts.join('&') : '';
11538 * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
11539 * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
11542 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
11543 * pct-encoded = "%" HEXDIG HEXDIG
11544 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
11545 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
11546 * / "*" / "+" / "," / ";" / "="
11548 function encodeUriSegment(val) {
11549 return encodeUriQuery(val, true).
11550 replace(/%26/gi, '&').
11551 replace(/%3D/gi, '=').
11552 replace(/%2B/gi, '+');
11557 * This method is intended for encoding *key* or *value* parts of query component. We need a custom
11558 * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
11559 * encoded per http://tools.ietf.org/html/rfc3986:
11560 * query = *( pchar / "/" / "?" )
11561 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
11562 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
11563 * pct-encoded = "%" HEXDIG HEXDIG
11564 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
11565 * / "*" / "+" / "," / ";" / "="
11567 function encodeUriQuery(val, pctEncodeSpaces) {
11568 return encodeURIComponent(val).
11569 replace(/%40/gi, '@').
11570 replace(/%3A/gi, ':').
11571 replace(/%24/g, '$').
11572 replace(/%2C/gi, ',').
11573 replace(/%3B/gi, ';').
11574 replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
11577 var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
11579 function getNgAttribute(element, ngAttr) {
11580 var attr, i, ii = ngAttrPrefixes.length;
11581 for (i = 0; i < ii; ++i) {
11582 attr = ngAttrPrefixes[i] + ngAttr;
11583 if (isString(attr = element.getAttribute(attr))) {
11590 function allowAutoBootstrap(document) {
11591 var script = document.currentScript;
11592 var src = script && script.getAttribute('src');
11598 var link = document.createElement('a');
11601 if (document.location.origin === link.origin) {
11602 // Same-origin resources are always allowed, even for non-whitelisted schemes.
11605 // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web.
11606 // This is to prevent angular.js bundled with browser extensions from being used to bypass the
11607 // content security policy in web pages and other browser extensions.
11608 switch (link.protocol) {
11621 // Cached as it has to run during loading so that document.currentScript is available.
11622 var isAutoBootstrapAllowed = allowAutoBootstrap(window.document);
11630 * @param {angular.Module} ngApp an optional application
11631 * {@link angular.module module} name to load.
11632 * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
11633 * created in "strict-di" mode. This means that the application will fail to invoke functions which
11634 * do not use explicit function annotation (and are thus unsuitable for minification), as described
11635 * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
11636 * tracking down the root of these bugs.
11640 * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
11641 * designates the **root element** of the application and is typically placed near the root element
11642 * of the page - e.g. on the `<body>` or `<html>` tags.
11644 * There are a few things to keep in mind when using `ngApp`:
11645 * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
11646 * found in the document will be used to define the root element to auto-bootstrap as an
11647 * application. To run multiple applications in an HTML document you must manually bootstrap them using
11648 * {@link angular.bootstrap} instead.
11649 * - AngularJS applications cannot be nested within each other.
11650 * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
11651 * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
11652 * {@link ngRoute.ngView `ngView`}.
11653 * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
11654 * causing animations to stop working and making the injector inaccessible from outside the app.
11656 * You can specify an **AngularJS module** to be used as the root module for the application. This
11657 * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
11658 * should contain the application code needed or have dependencies on other modules that will
11659 * contain the code. See {@link angular.module} for more information.
11661 * In the example below if the `ngApp` directive were not placed on the `html` element then the
11662 * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
11663 * would not be resolved to `3`.
11665 * `ngApp` is the easiest, and most common way to bootstrap an application.
11667 <example module="ngAppDemo" name="ng-app">
11668 <file name="index.html">
11669 <div ng-controller="ngAppDemoController">
11670 I can add: {{a}} + {{b}} = {{ a+b }}
11673 <file name="script.js">
11674 angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
11681 * Using `ngStrictDi`, you would see something like this:
11683 <example ng-app-included="true" name="strict-di">
11684 <file name="index.html">
11685 <div ng-app="ngAppStrictDemo" ng-strict-di>
11686 <div ng-controller="GoodController1">
11687 I can add: {{a}} + {{b}} = {{ a+b }}
11689 <p>This renders because the controller does not fail to
11690 instantiate, by using explicit annotation style (see
11691 script.js for details)
11695 <div ng-controller="GoodController2">
11696 Name: <input ng-model="name"><br />
11699 <p>This renders because the controller does not fail to
11700 instantiate, by using explicit annotation style
11701 (see script.js for details)
11705 <div ng-controller="BadController">
11706 I can add: {{a}} + {{b}} = {{ a+b }}
11708 <p>The controller could not be instantiated, due to relying
11709 on automatic function annotations (which are disabled in
11710 strict mode). As such, the content of this section is not
11711 interpolated, and there should be an error in your web console.
11716 <file name="script.js">
11717 angular.module('ngAppStrictDemo', [])
11718 // BadController will fail to instantiate, due to relying on automatic function annotation,
11719 // rather than an explicit annotation
11720 .controller('BadController', function($scope) {
11724 // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
11725 // due to using explicit annotations using the array style and $inject property, respectively.
11726 .controller('GoodController1', ['$scope', function($scope) {
11730 .controller('GoodController2', GoodController2);
11731 function GoodController2($scope) {
11732 $scope.name = 'World';
11734 GoodController2.$inject = ['$scope'];
11736 <file name="style.css">
11737 div[ng-controller] {
11738 margin-bottom: 1em;
11739 -webkit-border-radius: 4px;
11740 border-radius: 4px;
11744 div[ng-controller^=Good] {
11745 border-color: #d6e9c6;
11746 background-color: #dff0d8;
11749 div[ng-controller^=Bad] {
11750 border-color: #ebccd1;
11751 background-color: #f2dede;
11758 function angularInit(element, bootstrap) {
11763 // The element `element` has priority over any other element.
11764 forEach(ngAttrPrefixes, function(prefix) {
11765 var name = prefix + 'app';
11767 if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
11768 appElement = element;
11769 module = element.getAttribute(name);
11772 forEach(ngAttrPrefixes, function(prefix) {
11773 var name = prefix + 'app';
11776 if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
11777 appElement = candidate;
11778 module = candidate.getAttribute(name);
11782 if (!isAutoBootstrapAllowed) {
11783 window.console.error('Angular: disabling automatic bootstrap. <script> protocol indicates ' +
11784 'an extension, document.location.href does not match.');
11787 config.strictDi = getNgAttribute(appElement, 'strict-di') !== null;
11788 bootstrap(appElement, module ? [module] : [], config);
11794 * @name angular.bootstrap
11797 * Use this function to manually start up angular application.
11799 * For more information, see the {@link guide/bootstrap Bootstrap guide}.
11801 * Angular will detect if it has been loaded into the browser more than once and only allow the
11802 * first loaded script to be bootstrapped and will report a warning to the browser console for
11803 * each of the subsequent scripts. This prevents strange results in applications, where otherwise
11804 * multiple instances of Angular try to work on the DOM.
11806 * <div class="alert alert-warning">
11807 * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
11808 * They must use {@link ng.directive:ngApp ngApp}.
11811 * <div class="alert alert-warning">
11812 * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
11813 * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
11814 * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
11815 * causing animations to stop working and making the injector inaccessible from outside the app.
11822 * <div ng-controller="WelcomeController">
11826 * <script src="angular.js"></script>
11828 * var app = angular.module('demo', [])
11829 * .controller('WelcomeController', function($scope) {
11830 * $scope.greeting = 'Welcome!';
11832 * angular.bootstrap(document, ['demo']);
11838 * @param {DOMElement} element DOM element which is the root of angular application.
11839 * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
11840 * Each item in the array should be the name of a predefined module or a (DI annotated)
11841 * function that will be invoked by the injector as a `config` block.
11842 * See: {@link angular.module modules}
11843 * @param {Object=} config an object for defining configuration options for the application. The
11844 * following keys are supported:
11846 * * `strictDi` - disable automatic function annotation for the application. This is meant to
11847 * assist in finding bugs which break minified code. Defaults to `false`.
11849 * @returns {auto.$injector} Returns the newly created injector for this app.
11851 function bootstrap(element, modules, config) {
11852 if (!isObject(config)) config = {};
11853 var defaultConfig = {
11856 config = extend(defaultConfig, config);
11857 var doBootstrap = function() {
11858 element = jqLite(element);
11860 if (element.injector()) {
11861 var tag = (element[0] === window.document) ? 'document' : startingTag(element);
11862 // Encode angle brackets to prevent input from being sanitized to empty string #8683.
11865 'App already bootstrapped with this element \'{0}\'',
11866 tag.replace(/</,'<').replace(/>/,'>'));
11869 modules = modules || [];
11870 modules.unshift(['$provide', function($provide) {
11871 $provide.value('$rootElement', element);
11874 if (config.debugInfoEnabled) {
11875 // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
11876 modules.push(['$compileProvider', function($compileProvider) {
11877 $compileProvider.debugInfoEnabled(true);
11881 modules.unshift('ng');
11882 var injector = createInjector(modules, config.strictDi);
11883 injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
11884 function bootstrapApply(scope, element, compile, injector) {
11885 scope.$apply(function() {
11886 element.data('$injector', injector);
11887 compile(element)(scope);
11894 var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
11895 var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
11897 if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
11898 config.debugInfoEnabled = true;
11899 window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
11902 if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
11903 return doBootstrap();
11906 window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
11907 angular.resumeBootstrap = function(extraModules) {
11908 forEach(extraModules, function(module) {
11909 modules.push(module);
11911 return doBootstrap();
11914 if (isFunction(angular.resumeDeferredBootstrap)) {
11915 angular.resumeDeferredBootstrap();
11921 * @name angular.reloadWithDebugInfo
11924 * Use this function to reload the current application with debug information turned on.
11925 * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
11927 * See {@link ng.$compileProvider#debugInfoEnabled} for more.
11929 function reloadWithDebugInfo() {
11930 window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
11931 window.location.reload();
11935 * @name angular.getTestability
11938 * Get the testability service for the instance of Angular on the given
11940 * @param {DOMElement} element DOM element which is the root of angular application.
11942 function getTestability(rootElement) {
11943 var injector = angular.element(rootElement).injector();
11945 throw ngMinErr('test',
11946 'no injector found for element argument to getTestability');
11948 return injector.get('$$testability');
11951 var SNAKE_CASE_REGEXP = /[A-Z]/g;
11952 function snake_case(name, separator) {
11953 separator = separator || '_';
11954 return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
11955 return (pos ? separator : '') + letter.toLowerCase();
11959 var bindJQueryFired = false;
11960 function bindJQuery() {
11961 var originalCleanData;
11963 if (bindJQueryFired) {
11967 // bind to jQuery if present;
11969 jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
11970 !jqName ? undefined : // use jqLite
11971 window[jqName]; // use jQuery specified by `ngJq`
11973 // Use jQuery if it exists with proper functionality, otherwise default to us.
11974 // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
11975 // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
11976 // versions. It will not work for sure with jQuery <1.7, though.
11977 if (jQuery && jQuery.fn.on) {
11979 extend(jQuery.fn, {
11980 scope: JQLitePrototype.scope,
11981 isolateScope: JQLitePrototype.isolateScope,
11982 controller: JQLitePrototype.controller,
11983 injector: JQLitePrototype.injector,
11984 inheritedData: JQLitePrototype.inheritedData
11987 // All nodes removed from the DOM via various jQuery APIs like .remove()
11988 // are passed through jQuery.cleanData. Monkey-patch this method to fire
11989 // the $destroy event on all removed nodes.
11990 originalCleanData = jQuery.cleanData;
11991 jQuery.cleanData = function(elems) {
11993 for (var i = 0, elem; (elem = elems[i]) != null; i++) {
11994 events = jQuery._data(elem, 'events');
11995 if (events && events.$destroy) {
11996 jQuery(elem).triggerHandler('$destroy');
11999 originalCleanData(elems);
12005 angular.element = jqLite;
12007 // Prevent double-proxying.
12008 bindJQueryFired = true;
12012 * throw error if the argument is falsy.
12014 function assertArg(arg, name, reason) {
12016 throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
12021 function assertArgFn(arg, name, acceptArrayAnnotation) {
12022 if (acceptArrayAnnotation && isArray(arg)) {
12023 arg = arg[arg.length - 1];
12026 assertArg(isFunction(arg), name, 'not a function, got ' +
12027 (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
12032 * throw error if the name given is hasOwnProperty
12033 * @param {String} name the name to test
12034 * @param {String} context the context in which the name is used, such as module or directive
12036 function assertNotHasOwnProperty(name, context) {
12037 if (name === 'hasOwnProperty') {
12038 throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
12043 * Return the value accessible from the object by path. Any undefined traversals are ignored
12044 * @param {Object} obj starting object
12045 * @param {String} path path to traverse
12046 * @param {boolean} [bindFnToScope=true]
12047 * @returns {Object} value as accessible by path
12049 //TODO(misko): this function needs to be removed
12050 function getter(obj, path, bindFnToScope) {
12051 if (!path) return obj;
12052 var keys = path.split('.');
12054 var lastInstance = obj;
12055 var len = keys.length;
12057 for (var i = 0; i < len; i++) {
12060 obj = (lastInstance = obj)[key];
12063 if (!bindFnToScope && isFunction(obj)) {
12064 return bind(lastInstance, obj);
12070 * Return the DOM siblings between the first and last node in the given array.
12071 * @param {Array} array like object
12072 * @returns {Array} the inputted object or a jqLite collection containing the nodes
12074 function getBlockNodes(nodes) {
12075 // TODO(perf): update `nodes` instead of creating a new object?
12076 var node = nodes[0];
12077 var endNode = nodes[nodes.length - 1];
12080 for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
12081 if (blockNodes || nodes[i] !== node) {
12083 blockNodes = jqLite(slice.call(nodes, 0, i));
12085 blockNodes.push(node);
12089 return blockNodes || nodes;
12094 * Creates a new object without a prototype. This object is useful for lookup without having to
12095 * guard against prototypically inherited properties via hasOwnProperty.
12097 * Related micro-benchmarks:
12098 * - http://jsperf.com/object-create2
12099 * - http://jsperf.com/proto-map-lookup/2
12100 * - http://jsperf.com/for-in-vs-object-keys2
12102 * @returns {Object}
12104 function createMap() {
12105 return Object.create(null);
12108 var NODE_TYPE_ELEMENT = 1;
12109 var NODE_TYPE_ATTRIBUTE = 2;
12110 var NODE_TYPE_TEXT = 3;
12111 var NODE_TYPE_COMMENT = 8;
12112 var NODE_TYPE_DOCUMENT = 9;
12113 var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
12117 * @name angular.Module
12121 * Interface for configuring angular {@link angular.module modules}.
12124 function setupModuleLoader(window) {
12126 var $injectorMinErr = minErr('$injector');
12127 var ngMinErr = minErr('ng');
12129 function ensure(obj, name, factory) {
12130 return obj[name] || (obj[name] = factory());
12133 var angular = ensure(window, 'angular', Object);
12135 // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
12136 angular.$$minErr = angular.$$minErr || minErr;
12138 return ensure(angular, 'module', function() {
12139 /** @type {Object.<string, angular.Module>} */
12144 * @name angular.module
12148 * The `angular.module` is a global place for creating, registering and retrieving Angular
12150 * All modules (angular core or 3rd party) that should be available to an application must be
12151 * registered using this mechanism.
12153 * Passing one argument retrieves an existing {@link angular.Module},
12154 * whereas passing more than one argument creates a new {@link angular.Module}
12159 * A module is a collection of services, directives, controllers, filters, and configuration information.
12160 * `angular.module` is used to configure the {@link auto.$injector $injector}.
12163 * // Create a new module
12164 * var myModule = angular.module('myModule', []);
12166 * // register a new service
12167 * myModule.value('appName', 'MyCoolApp');
12169 * // configure existing services inside initialization blocks.
12170 * myModule.config(['$locationProvider', function($locationProvider) {
12171 * // Configure existing providers
12172 * $locationProvider.hashPrefix('!');
12176 * Then you can create an injector and load your modules like this:
12179 * var injector = angular.injector(['ng', 'myModule'])
12182 * However it's more likely that you'll just use
12183 * {@link ng.directive:ngApp ngApp} or
12184 * {@link angular.bootstrap} to simplify this process for you.
12186 * @param {!string} name The name of the module to create or retrieve.
12187 * @param {!Array.<string>=} requires If specified then new module is being created. If
12188 * unspecified then the module is being retrieved for further configuration.
12189 * @param {Function=} configFn Optional configuration function for the module. Same as
12190 * {@link angular.Module#config Module#config()}.
12191 * @returns {angular.Module} new module with the {@link angular.Module} api.
12193 return function module(name, requires, configFn) {
12194 var assertNotHasOwnProperty = function(name, context) {
12195 if (name === 'hasOwnProperty') {
12196 throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
12200 assertNotHasOwnProperty(name, 'module');
12201 if (requires && modules.hasOwnProperty(name)) {
12202 modules[name] = null;
12204 return ensure(modules, name, function() {
12206 throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' +
12207 'the module name or forgot to load it. If registering a module ensure that you ' +
12208 'specify the dependencies as the second argument.', name);
12211 /** @type {!Array.<Array.<*>>} */
12212 var invokeQueue = [];
12214 /** @type {!Array.<Function>} */
12215 var configBlocks = [];
12217 /** @type {!Array.<Function>} */
12218 var runBlocks = [];
12220 var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
12222 /** @type {angular.Module} */
12223 var moduleInstance = {
12225 _invokeQueue: invokeQueue,
12226 _configBlocks: configBlocks,
12227 _runBlocks: runBlocks,
12231 * @name angular.Module#requires
12235 * Holds the list of modules which the injector will load before the current module is
12238 requires: requires,
12242 * @name angular.Module#name
12246 * Name of the module.
12253 * @name angular.Module#provider
12255 * @param {string} name service name
12256 * @param {Function} providerType Construction function for creating new instance of the
12259 * See {@link auto.$provide#provider $provide.provider()}.
12261 provider: invokeLaterAndSetModuleName('$provide', 'provider'),
12265 * @name angular.Module#factory
12267 * @param {string} name service name
12268 * @param {Function} providerFunction Function for creating new instance of the service.
12270 * See {@link auto.$provide#factory $provide.factory()}.
12272 factory: invokeLaterAndSetModuleName('$provide', 'factory'),
12276 * @name angular.Module#service
12278 * @param {string} name service name
12279 * @param {Function} constructor A constructor function that will be instantiated.
12281 * See {@link auto.$provide#service $provide.service()}.
12283 service: invokeLaterAndSetModuleName('$provide', 'service'),
12287 * @name angular.Module#value
12289 * @param {string} name service name
12290 * @param {*} object Service instance object.
12292 * See {@link auto.$provide#value $provide.value()}.
12294 value: invokeLater('$provide', 'value'),
12298 * @name angular.Module#constant
12300 * @param {string} name constant name
12301 * @param {*} object Constant value.
12303 * Because the constants are fixed, they get applied before other provide methods.
12304 * See {@link auto.$provide#constant $provide.constant()}.
12306 constant: invokeLater('$provide', 'constant', 'unshift'),
12310 * @name angular.Module#decorator
12312 * @param {string} name The name of the service to decorate.
12313 * @param {Function} decorFn This function will be invoked when the service needs to be
12314 * instantiated and should return the decorated service instance.
12316 * See {@link auto.$provide#decorator $provide.decorator()}.
12318 decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
12322 * @name angular.Module#animation
12324 * @param {string} name animation name
12325 * @param {Function} animationFactory Factory function for creating new instance of an
12329 * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
12332 * Defines an animation hook that can be later used with
12333 * {@link $animate $animate} service and directives that use this service.
12336 * module.animation('.animation-name', function($inject1, $inject2) {
12338 * eventName : function(element, done) {
12339 * //code to run the animation
12340 * //once complete, then run done()
12341 * return function cancellationFunction(element) {
12342 * //code to cancel the animation
12349 * See {@link ng.$animateProvider#register $animateProvider.register()} and
12350 * {@link ngAnimate ngAnimate module} for more information.
12352 animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
12356 * @name angular.Module#filter
12358 * @param {string} name Filter name - this must be a valid angular expression identifier
12359 * @param {Function} filterFactory Factory function for creating new instance of filter.
12361 * See {@link ng.$filterProvider#register $filterProvider.register()}.
12363 * <div class="alert alert-warning">
12364 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
12365 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
12366 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
12367 * (`myapp_subsection_filterx`).
12370 filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
12374 * @name angular.Module#controller
12376 * @param {string|Object} name Controller name, or an object map of controllers where the
12377 * keys are the names and the values are the constructors.
12378 * @param {Function} constructor Controller constructor function.
12380 * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
12382 controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
12386 * @name angular.Module#directive
12388 * @param {string|Object} name Directive name, or an object map of directives where the
12389 * keys are the names and the values are the factories.
12390 * @param {Function} directiveFactory Factory function for creating new instance of
12393 * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
12395 directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
12399 * @name angular.Module#component
12401 * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
12402 * @param {Object} options Component definition object (a simplified
12403 * {@link ng.$compile#directive-definition-object directive definition object})
12406 * See {@link ng.$compileProvider#component $compileProvider.component()}.
12408 component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
12412 * @name angular.Module#config
12414 * @param {Function} configFn Execute this function on module load. Useful for service
12417 * Use this method to register work which needs to be performed on module loading.
12418 * For more about how to configure services, see
12419 * {@link providers#provider-recipe Provider Recipe}.
12425 * @name angular.Module#run
12427 * @param {Function} initializationFn Execute this function after injector creation.
12428 * Useful for application initialization.
12430 * Use this method to register work which should be performed when the injector is done
12431 * loading all modules.
12433 run: function(block) {
12434 runBlocks.push(block);
12443 return moduleInstance;
12446 * @param {string} provider
12447 * @param {string} method
12448 * @param {String=} insertMethod
12449 * @returns {angular.Module}
12451 function invokeLater(provider, method, insertMethod, queue) {
12452 if (!queue) queue = invokeQueue;
12453 return function() {
12454 queue[insertMethod || 'push']([provider, method, arguments]);
12455 return moduleInstance;
12460 * @param {string} provider
12461 * @param {string} method
12462 * @returns {angular.Module}
12464 function invokeLaterAndSetModuleName(provider, method) {
12465 return function(recipeName, factoryFunction) {
12466 if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
12467 invokeQueue.push([provider, method, arguments]);
12468 return moduleInstance;
12477 /* global shallowCopy: true */
12480 * Creates a shallow copy of an object, an array or a primitive.
12482 * Assumes that there are no proto properties for objects.
12484 function shallowCopy(src, dst) {
12485 if (isArray(src)) {
12488 for (var i = 0, ii = src.length; i < ii; i++) {
12491 } else if (isObject(src)) {
12494 for (var key in src) {
12495 if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
12496 dst[key] = src[key];
12504 /* global toDebugString: true */
12506 function serializeObject(obj) {
12509 return JSON.stringify(obj, function(key, val) {
12510 val = toJsonReplacer(key, val);
12511 if (isObject(val)) {
12513 if (seen.indexOf(val) >= 0) return '...';
12521 function toDebugString(obj) {
12522 if (typeof obj === 'function') {
12523 return obj.toString().replace(/ \{[\s\S]*$/, '');
12524 } else if (isUndefined(obj)) {
12525 return 'undefined';
12526 } else if (typeof obj !== 'string') {
12527 return serializeObject(obj);
12532 /* global angularModule: true,
12537 htmlAnchorDirective,
12545 ngBindHtmlDirective,
12546 ngBindTemplateDirective,
12548 ngClassEvenDirective,
12549 ngClassOddDirective,
12551 ngControllerDirective,
12555 ngIncludeDirective,
12556 ngIncludeFillContentDirective,
12558 ngNonBindableDirective,
12559 ngPluralizeDirective,
12564 ngSwitchWhenDirective,
12565 ngSwitchDefaultDirective,
12566 ngOptionsDirective,
12567 ngTranscludeDirective,
12575 minlengthDirective,
12576 minlengthDirective,
12577 maxlengthDirective,
12578 maxlengthDirective,
12580 ngModelOptionsDirective,
12581 ngAttributeAliasDirectives,
12584 $AnchorScrollProvider,
12586 $CoreAnimateCssProvider,
12587 $$CoreAnimateJsProvider,
12588 $$CoreAnimateQueueProvider,
12589 $$AnimateRunnerFactoryProvider,
12590 $$AnimateAsyncRunFactoryProvider,
12592 $CacheFactoryProvider,
12593 $ControllerProvider,
12596 $ExceptionHandlerProvider,
12598 $$ForceReflowProvider,
12599 $InterpolateProvider,
12603 $HttpParamSerializerProvider,
12604 $HttpParamSerializerJQLikeProvider,
12605 $HttpBackendProvider,
12606 $xhrFactoryProvider,
12607 $jsonpCallbacksProvider,
12611 $RootScopeProvider,
12614 $$SanitizeUriProvider,
12616 $SceDelegateProvider,
12618 $TemplateCacheProvider,
12619 $TemplateRequestProvider,
12620 $$TestabilityProvider,
12625 $$CookieReaderProvider
12631 * @name angular.version
12634 * An object that contains information about the current AngularJS version.
12636 * This object has the following properties:
12638 * - `full` – `{string}` – Full version string, such as "0.9.18".
12639 * - `major` – `{number}` – Major version number, such as "0".
12640 * - `minor` – `{number}` – Minor version number, such as "9".
12641 * - `dot` – `{number}` – Dot version number, such as "18".
12642 * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
12645 // These placeholder strings will be replaced by grunt's `build` task.
12646 // They need to be double- or single-quoted.
12651 codeName: 'princely-quest'
12655 function publishExternalAPI(angular) {
12657 'bootstrap': bootstrap,
12663 'forEach': forEach,
12664 'injector': createInjector,
12668 'fromJson': fromJson,
12669 'identity': identity,
12670 'isUndefined': isUndefined,
12671 'isDefined': isDefined,
12672 'isString': isString,
12673 'isFunction': isFunction,
12674 'isObject': isObject,
12675 'isNumber': isNumber,
12676 'isElement': isElement,
12677 'isArray': isArray,
12678 'version': version,
12680 'lowercase': lowercase,
12681 'uppercase': uppercase,
12682 'callbacks': {$$counter: 0},
12683 'getTestability': getTestability,
12684 '$$minErr': minErr,
12686 'reloadWithDebugInfo': reloadWithDebugInfo
12689 angularModule = setupModuleLoader(window);
12691 angularModule('ng', ['ngLocale'], ['$provide',
12692 function ngModule($provide) {
12693 // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
12694 $provide.provider({
12695 $$sanitizeUri: $$SanitizeUriProvider
12697 $provide.provider('$compile', $CompileProvider).
12699 a: htmlAnchorDirective,
12700 input: inputDirective,
12701 textarea: inputDirective,
12702 form: formDirective,
12703 script: scriptDirective,
12704 select: selectDirective,
12705 option: optionDirective,
12706 ngBind: ngBindDirective,
12707 ngBindHtml: ngBindHtmlDirective,
12708 ngBindTemplate: ngBindTemplateDirective,
12709 ngClass: ngClassDirective,
12710 ngClassEven: ngClassEvenDirective,
12711 ngClassOdd: ngClassOddDirective,
12712 ngCloak: ngCloakDirective,
12713 ngController: ngControllerDirective,
12714 ngForm: ngFormDirective,
12715 ngHide: ngHideDirective,
12716 ngIf: ngIfDirective,
12717 ngInclude: ngIncludeDirective,
12718 ngInit: ngInitDirective,
12719 ngNonBindable: ngNonBindableDirective,
12720 ngPluralize: ngPluralizeDirective,
12721 ngRepeat: ngRepeatDirective,
12722 ngShow: ngShowDirective,
12723 ngStyle: ngStyleDirective,
12724 ngSwitch: ngSwitchDirective,
12725 ngSwitchWhen: ngSwitchWhenDirective,
12726 ngSwitchDefault: ngSwitchDefaultDirective,
12727 ngOptions: ngOptionsDirective,
12728 ngTransclude: ngTranscludeDirective,
12729 ngModel: ngModelDirective,
12730 ngList: ngListDirective,
12731 ngChange: ngChangeDirective,
12732 pattern: patternDirective,
12733 ngPattern: patternDirective,
12734 required: requiredDirective,
12735 ngRequired: requiredDirective,
12736 minlength: minlengthDirective,
12737 ngMinlength: minlengthDirective,
12738 maxlength: maxlengthDirective,
12739 ngMaxlength: maxlengthDirective,
12740 ngValue: ngValueDirective,
12741 ngModelOptions: ngModelOptionsDirective
12744 ngInclude: ngIncludeFillContentDirective
12746 directive(ngAttributeAliasDirectives).
12747 directive(ngEventDirectives);
12748 $provide.provider({
12749 $anchorScroll: $AnchorScrollProvider,
12750 $animate: $AnimateProvider,
12751 $animateCss: $CoreAnimateCssProvider,
12752 $$animateJs: $$CoreAnimateJsProvider,
12753 $$animateQueue: $$CoreAnimateQueueProvider,
12754 $$AnimateRunner: $$AnimateRunnerFactoryProvider,
12755 $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
12756 $browser: $BrowserProvider,
12757 $cacheFactory: $CacheFactoryProvider,
12758 $controller: $ControllerProvider,
12759 $document: $DocumentProvider,
12760 $exceptionHandler: $ExceptionHandlerProvider,
12761 $filter: $FilterProvider,
12762 $$forceReflow: $$ForceReflowProvider,
12763 $interpolate: $InterpolateProvider,
12764 $interval: $IntervalProvider,
12765 $http: $HttpProvider,
12766 $httpParamSerializer: $HttpParamSerializerProvider,
12767 $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
12768 $httpBackend: $HttpBackendProvider,
12769 $xhrFactory: $xhrFactoryProvider,
12770 $jsonpCallbacks: $jsonpCallbacksProvider,
12771 $location: $LocationProvider,
12772 $log: $LogProvider,
12773 $parse: $ParseProvider,
12774 $rootScope: $RootScopeProvider,
12777 $sce: $SceProvider,
12778 $sceDelegate: $SceDelegateProvider,
12779 $sniffer: $SnifferProvider,
12780 $templateCache: $TemplateCacheProvider,
12781 $templateRequest: $TemplateRequestProvider,
12782 $$testability: $$TestabilityProvider,
12783 $timeout: $TimeoutProvider,
12784 $window: $WindowProvider,
12785 $$rAF: $$RAFProvider,
12786 $$jqLite: $$jqLiteProvider,
12787 $$HashMap: $$HashMapProvider,
12788 $$cookieReader: $$CookieReaderProvider
12794 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
12795 * Any commits to this file should be reviewed with security in mind. *
12796 * Changes to this file can potentially create security vulnerabilities. *
12797 * An approval from 2 Core members with history of modifying *
12798 * this file is required. *
12800 * Does the change somehow allow for arbitrary javascript to be executed? *
12801 * Or allows for someone to change the prototype of built-in objects? *
12802 * Or gives undesired access to variables likes document or window? *
12803 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
12805 /* global JQLitePrototype: true,
12806 addEventListenerFn: true,
12807 removeEventListenerFn: true,
12808 BOOLEAN_ATTR: true,
12812 //////////////////////////////////
12814 //////////////////////////////////
12818 * @name angular.element
12823 * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
12825 * If jQuery is available, `angular.element` is an alias for the
12826 * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
12827 * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
12829 * jqLite is a tiny, API-compatible subset of jQuery that allows
12830 * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
12831 * commonly needed functionality with the goal of having a very small footprint.
12833 * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
12834 * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
12835 * specific version of jQuery if multiple versions exist on the page.
12837 * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
12838 * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
12840 * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
12841 * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
12842 * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
12844 * ## Angular's jqLite
12845 * jqLite provides only the following jQuery methods:
12847 * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
12848 * - [`after()`](http://api.jquery.com/after/)
12849 * - [`append()`](http://api.jquery.com/append/)
12850 * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
12851 * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
12852 * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
12853 * - [`clone()`](http://api.jquery.com/clone/)
12854 * - [`contents()`](http://api.jquery.com/contents/)
12855 * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
12856 * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
12857 * - [`data()`](http://api.jquery.com/data/)
12858 * - [`detach()`](http://api.jquery.com/detach/)
12859 * - [`empty()`](http://api.jquery.com/empty/)
12860 * - [`eq()`](http://api.jquery.com/eq/)
12861 * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
12862 * - [`hasClass()`](http://api.jquery.com/hasClass/)
12863 * - [`html()`](http://api.jquery.com/html/)
12864 * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
12865 * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
12866 * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
12867 * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
12868 * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
12869 * - [`prepend()`](http://api.jquery.com/prepend/)
12870 * - [`prop()`](http://api.jquery.com/prop/)
12871 * - [`ready()`](http://api.jquery.com/ready/)
12872 * - [`remove()`](http://api.jquery.com/remove/)
12873 * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes
12874 * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
12875 * - [`removeData()`](http://api.jquery.com/removeData/)
12876 * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
12877 * - [`text()`](http://api.jquery.com/text/)
12878 * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
12879 * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
12880 * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
12881 * - [`val()`](http://api.jquery.com/val/)
12882 * - [`wrap()`](http://api.jquery.com/wrap/)
12884 * ## jQuery/jqLite Extras
12885 * Angular also provides the following additional methods and events to both jQuery and jqLite:
12888 * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
12889 * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
12890 * element before it is removed.
12893 * - `controller(name)` - retrieves the controller of the current element or its parent. By default
12894 * retrieves controller associated with the `ngController` directive. If `name` is provided as
12895 * camelCase directive name, then the controller for this directive will be retrieved (e.g.
12897 * - `injector()` - retrieves the injector of the current element or its parent.
12898 * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
12899 * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
12901 * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
12902 * current element. This getter should be used only on elements that contain a directive which starts a new isolate
12903 * scope. Calling `scope()` on this element always returns the original non-isolate scope.
12904 * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
12905 * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
12906 * parent element is reached.
12908 * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
12909 * https://github.com/angular/angular.js/issues/14251 for more information.
12911 * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
12912 * @returns {Object} jQuery object.
12915 JQLite.expando = 'ng339';
12917 var jqCache = JQLite.cache = {},
12919 addEventListenerFn = function(element, type, fn) {
12920 element.addEventListener(type, fn, false);
12922 removeEventListenerFn = function(element, type, fn) {
12923 element.removeEventListener(type, fn, false);
12927 * !!! This is an undocumented "private" function !!!
12929 JQLite._data = function(node) {
12930 //jQuery always returns an object on cache miss
12931 return this.cache[node[this.expando]] || {};
12934 function jqNextId() { return ++jqId; }
12937 var SPECIAL_CHARS_REGEXP = /([:\-_]+(.))/g;
12938 var MOZ_HACK_REGEXP = /^moz([A-Z])/;
12939 var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };
12940 var jqLiteMinErr = minErr('jqLite');
12943 * Converts snake_case to camelCase.
12944 * Also there is special case for Moz prefix starting with upper case letter.
12945 * @param name Name to normalize
12947 function camelCase(name) {
12949 replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
12950 return offset ? letter.toUpperCase() : letter;
12952 replace(MOZ_HACK_REGEXP, 'Moz$1');
12955 var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
12956 var HTML_REGEXP = /<|&#?\w+;/;
12957 var TAG_NAME_REGEXP = /<([\w:-]+)/;
12958 var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
12961 'option': [1, '<select multiple="multiple">', '</select>'],
12963 'thead': [1, '<table>', '</table>'],
12964 'col': [2, '<table><colgroup>', '</colgroup></table>'],
12965 'tr': [2, '<table><tbody>', '</tbody></table>'],
12966 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
12967 '_default': [0, '', '']
12970 wrapMap.optgroup = wrapMap.option;
12971 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
12972 wrapMap.th = wrapMap.td;
12975 function jqLiteIsTextNode(html) {
12976 return !HTML_REGEXP.test(html);
12979 function jqLiteAcceptsData(node) {
12980 // The window object can accept data but has no nodeType
12981 // Otherwise we are only interested in elements (1) and documents (9)
12982 var nodeType = node.nodeType;
12983 return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
12986 function jqLiteHasData(node) {
12987 for (var key in jqCache[node.ng339]) {
12993 function jqLiteCleanData(nodes) {
12994 for (var i = 0, ii = nodes.length; i < ii; i++) {
12995 jqLiteRemoveData(nodes[i]);
12999 function jqLiteBuildFragment(html, context) {
13000 var tmp, tag, wrap,
13001 fragment = context.createDocumentFragment(),
13004 if (jqLiteIsTextNode(html)) {
13005 // Convert non-html into a text node
13006 nodes.push(context.createTextNode(html));
13008 // Convert html into DOM nodes
13009 tmp = fragment.appendChild(context.createElement('div'));
13010 tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
13011 wrap = wrapMap[tag] || wrapMap._default;
13012 tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1></$2>') + wrap[2];
13014 // Descend through wrappers to the right content
13017 tmp = tmp.lastChild;
13020 nodes = concat(nodes, tmp.childNodes);
13022 tmp = fragment.firstChild;
13023 tmp.textContent = '';
13026 // Remove wrapper from fragment
13027 fragment.textContent = '';
13028 fragment.innerHTML = ''; // Clear inner HTML
13029 forEach(nodes, function(node) {
13030 fragment.appendChild(node);
13036 function jqLiteParseHTML(html, context) {
13037 context = context || window.document;
13040 if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
13041 return [context.createElement(parsed[1])];
13044 if ((parsed = jqLiteBuildFragment(html, context))) {
13045 return parsed.childNodes;
13051 function jqLiteWrapNode(node, wrapper) {
13052 var parent = node.parentNode;
13055 parent.replaceChild(wrapper, node);
13058 wrapper.appendChild(node);
13062 // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
13063 var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
13064 // eslint-disable-next-line no-bitwise
13065 return !!(this.compareDocumentPosition(arg) & 16);
13068 /////////////////////////////////////////////
13069 function JQLite(element) {
13070 if (element instanceof JQLite) {
13076 if (isString(element)) {
13077 element = trim(element);
13078 argIsString = true;
13080 if (!(this instanceof JQLite)) {
13081 if (argIsString && element.charAt(0) !== '<') {
13082 throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
13084 return new JQLite(element);
13088 jqLiteAddNodes(this, jqLiteParseHTML(element));
13090 jqLiteAddNodes(this, element);
13094 function jqLiteClone(element) {
13095 return element.cloneNode(true);
13098 function jqLiteDealoc(element, onlyDescendants) {
13099 if (!onlyDescendants) jqLiteRemoveData(element);
13101 if (element.querySelectorAll) {
13102 var descendants = element.querySelectorAll('*');
13103 for (var i = 0, l = descendants.length; i < l; i++) {
13104 jqLiteRemoveData(descendants[i]);
13109 function jqLiteOff(element, type, fn, unsupported) {
13110 if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
13112 var expandoStore = jqLiteExpandoStore(element);
13113 var events = expandoStore && expandoStore.events;
13114 var handle = expandoStore && expandoStore.handle;
13116 if (!handle) return; //no listeners registered
13119 for (type in events) {
13120 if (type !== '$destroy') {
13121 removeEventListenerFn(element, type, handle);
13123 delete events[type];
13127 var removeHandler = function(type) {
13128 var listenerFns = events[type];
13129 if (isDefined(fn)) {
13130 arrayRemove(listenerFns || [], fn);
13132 if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
13133 removeEventListenerFn(element, type, handle);
13134 delete events[type];
13138 forEach(type.split(' '), function(type) {
13139 removeHandler(type);
13140 if (MOUSE_EVENT_MAP[type]) {
13141 removeHandler(MOUSE_EVENT_MAP[type]);
13147 function jqLiteRemoveData(element, name) {
13148 var expandoId = element.ng339;
13149 var expandoStore = expandoId && jqCache[expandoId];
13151 if (expandoStore) {
13153 delete expandoStore.data[name];
13157 if (expandoStore.handle) {
13158 if (expandoStore.events.$destroy) {
13159 expandoStore.handle({}, '$destroy');
13161 jqLiteOff(element);
13163 delete jqCache[expandoId];
13164 element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
13169 function jqLiteExpandoStore(element, createIfNecessary) {
13170 var expandoId = element.ng339,
13171 expandoStore = expandoId && jqCache[expandoId];
13173 if (createIfNecessary && !expandoStore) {
13174 element.ng339 = expandoId = jqNextId();
13175 expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
13178 return expandoStore;
13182 function jqLiteData(element, key, value) {
13183 if (jqLiteAcceptsData(element)) {
13185 var isSimpleSetter = isDefined(value);
13186 var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
13187 var massGetter = !key;
13188 var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
13189 var data = expandoStore && expandoStore.data;
13191 if (isSimpleSetter) { // data('key', value)
13194 if (massGetter) { // data()
13197 if (isSimpleGetter) { // data('key')
13198 // don't force creation of expandoStore if it doesn't exist yet
13199 return data && data[key];
13200 } else { // mass-setter: data({key1: val1, key2: val2})
13208 function jqLiteHasClass(element, selector) {
13209 if (!element.getAttribute) return false;
13210 return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
13211 indexOf(' ' + selector + ' ') > -1);
13214 function jqLiteRemoveClass(element, cssClasses) {
13215 if (cssClasses && element.setAttribute) {
13216 forEach(cssClasses.split(' '), function(cssClass) {
13217 element.setAttribute('class', trim(
13218 (' ' + (element.getAttribute('class') || '') + ' ')
13219 .replace(/[\n\t]/g, ' ')
13220 .replace(' ' + trim(cssClass) + ' ', ' '))
13226 function jqLiteAddClass(element, cssClasses) {
13227 if (cssClasses && element.setAttribute) {
13228 var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
13229 .replace(/[\n\t]/g, ' ');
13231 forEach(cssClasses.split(' '), function(cssClass) {
13232 cssClass = trim(cssClass);
13233 if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
13234 existingClasses += cssClass + ' ';
13238 element.setAttribute('class', trim(existingClasses));
13243 function jqLiteAddNodes(root, elements) {
13244 // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
13248 // if a Node (the most common case)
13249 if (elements.nodeType) {
13250 root[root.length++] = elements;
13252 var length = elements.length;
13254 // if an Array or NodeList and not a Window
13255 if (typeof length === 'number' && elements.window !== elements) {
13257 for (var i = 0; i < length; i++) {
13258 root[root.length++] = elements[i];
13262 root[root.length++] = elements;
13269 function jqLiteController(element, name) {
13270 return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
13273 function jqLiteInheritedData(element, name, value) {
13274 // if element is the document object work with the html element instead
13275 // this makes $(document).scope() possible
13276 if (element.nodeType === NODE_TYPE_DOCUMENT) {
13277 element = element.documentElement;
13279 var names = isArray(name) ? name : [name];
13282 for (var i = 0, ii = names.length; i < ii; i++) {
13283 if (isDefined(value = jqLite.data(element, names[i]))) return value;
13286 // If dealing with a document fragment node with a host element, and no parent, use the host
13287 // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
13288 // to lookup parent controllers.
13289 element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
13293 function jqLiteEmpty(element) {
13294 jqLiteDealoc(element, true);
13295 while (element.firstChild) {
13296 element.removeChild(element.firstChild);
13300 function jqLiteRemove(element, keepData) {
13301 if (!keepData) jqLiteDealoc(element);
13302 var parent = element.parentNode;
13303 if (parent) parent.removeChild(element);
13307 function jqLiteDocumentLoaded(action, win) {
13308 win = win || window;
13309 if (win.document.readyState === 'complete') {
13310 // Force the action to be run async for consistent behavior
13311 // from the action's point of view
13312 // i.e. it will definitely not be in a $apply
13313 win.setTimeout(action);
13315 // No need to unbind this handler as load is only ever called once
13316 jqLite(win).on('load', action);
13320 //////////////////////////////////////////
13321 // Functions which are declared directly.
13322 //////////////////////////////////////////
13323 var JQLitePrototype = JQLite.prototype = {
13324 ready: function(fn) {
13327 function trigger() {
13333 // check if document is already loaded
13334 if (window.document.readyState === 'complete') {
13335 window.setTimeout(trigger);
13337 this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
13338 // we can not use jqLite since we are not done loading and jQuery could be loaded later.
13339 // eslint-disable-next-line new-cap
13340 JQLite(window).on('load', trigger); // fallback to window.onload for others
13343 toString: function() {
13345 forEach(this, function(e) { value.push('' + e);});
13346 return '[' + value.join(', ') + ']';
13349 eq: function(index) {
13350 return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
13359 //////////////////////////////////////////
13360 // Functions iterating getter/setters.
13361 // these functions return self on setter and
13363 //////////////////////////////////////////
13364 var BOOLEAN_ATTR = {};
13365 forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
13366 BOOLEAN_ATTR[lowercase(value)] = value;
13368 var BOOLEAN_ELEMENTS = {};
13369 forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
13370 BOOLEAN_ELEMENTS[value] = true;
13372 var ALIASED_ATTR = {
13373 'ngMinlength': 'minlength',
13374 'ngMaxlength': 'maxlength',
13377 'ngPattern': 'pattern'
13380 function getBooleanAttrName(element, name) {
13381 // check dom last since we will most likely fail on name
13382 var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
13384 // booleanAttr is here twice to minimize DOM access
13385 return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
13388 function getAliasedAttrName(name) {
13389 return ALIASED_ATTR[name];
13394 removeData: jqLiteRemoveData,
13395 hasData: jqLiteHasData,
13396 cleanData: jqLiteCleanData
13397 }, function(fn, name) {
13403 inheritedData: jqLiteInheritedData,
13405 scope: function(element) {
13406 // Can't use jqLiteData here directly so we stay compatible with jQuery!
13407 return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
13410 isolateScope: function(element) {
13411 // Can't use jqLiteData here directly so we stay compatible with jQuery!
13412 return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
13415 controller: jqLiteController,
13417 injector: function(element) {
13418 return jqLiteInheritedData(element, '$injector');
13421 removeAttr: function(element, name) {
13422 element.removeAttribute(name);
13425 hasClass: jqLiteHasClass,
13427 css: function(element, name, value) {
13428 name = camelCase(name);
13430 if (isDefined(value)) {
13431 element.style[name] = value;
13433 return element.style[name];
13437 attr: function(element, name, value) {
13438 var nodeType = element.nodeType;
13439 if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
13442 var lowercasedName = lowercase(name);
13443 if (BOOLEAN_ATTR[lowercasedName]) {
13444 if (isDefined(value)) {
13446 element[name] = true;
13447 element.setAttribute(name, lowercasedName);
13449 element[name] = false;
13450 element.removeAttribute(lowercasedName);
13453 return (element[name] ||
13454 (element.attributes.getNamedItem(name) || noop).specified)
13458 } else if (isDefined(value)) {
13459 element.setAttribute(name, value);
13460 } else if (element.getAttribute) {
13461 // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
13462 // some elements (e.g. Document) don't have get attribute, so return undefined
13463 var ret = element.getAttribute(name, 2);
13464 // normalize non-existing attributes to undefined (as jQuery)
13465 return ret === null ? undefined : ret;
13469 prop: function(element, name, value) {
13470 if (isDefined(value)) {
13471 element[name] = value;
13473 return element[name];
13477 text: (function() {
13481 function getText(element, value) {
13482 if (isUndefined(value)) {
13483 var nodeType = element.nodeType;
13484 return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
13486 element.textContent = value;
13490 val: function(element, value) {
13491 if (isUndefined(value)) {
13492 if (element.multiple && nodeName_(element) === 'select') {
13494 forEach(element.options, function(option) {
13495 if (option.selected) {
13496 result.push(option.value || option.text);
13499 return result.length === 0 ? null : result;
13501 return element.value;
13503 element.value = value;
13506 html: function(element, value) {
13507 if (isUndefined(value)) {
13508 return element.innerHTML;
13510 jqLiteDealoc(element, true);
13511 element.innerHTML = value;
13515 }, function(fn, name) {
13517 * Properties: writes return selection, reads return first value
13519 JQLite.prototype[name] = function(arg1, arg2) {
13521 var nodeCount = this.length;
13523 // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
13524 // in a way that survives minification.
13525 // jqLiteEmpty takes no arguments but is a setter.
13526 if (fn !== jqLiteEmpty &&
13527 (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
13528 if (isObject(arg1)) {
13530 // we are a write, but the object properties are the key/values
13531 for (i = 0; i < nodeCount; i++) {
13532 if (fn === jqLiteData) {
13533 // data() takes the whole object in jQuery
13536 for (key in arg1) {
13537 fn(this[i], key, arg1[key]);
13541 // return self for chaining
13544 // we are a read, so read the first child.
13545 // TODO: do we still need this?
13546 var value = fn.$dv;
13547 // Only if we have $dv do we iterate over all, otherwise it is just the first element.
13548 var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
13549 for (var j = 0; j < jj; j++) {
13550 var nodeValue = fn(this[j], arg1, arg2);
13551 value = value ? value + nodeValue : nodeValue;
13556 // we are a write, so apply to all children
13557 for (i = 0; i < nodeCount; i++) {
13558 fn(this[i], arg1, arg2);
13560 // return self for chaining
13566 function createEventHandler(element, events) {
13567 var eventHandler = function(event, type) {
13568 // jQuery specific api
13569 event.isDefaultPrevented = function() {
13570 return event.defaultPrevented;
13573 var eventFns = events[type || event.type];
13574 var eventFnsLength = eventFns ? eventFns.length : 0;
13576 if (!eventFnsLength) return;
13578 if (isUndefined(event.immediatePropagationStopped)) {
13579 var originalStopImmediatePropagation = event.stopImmediatePropagation;
13580 event.stopImmediatePropagation = function() {
13581 event.immediatePropagationStopped = true;
13583 if (event.stopPropagation) {
13584 event.stopPropagation();
13587 if (originalStopImmediatePropagation) {
13588 originalStopImmediatePropagation.call(event);
13593 event.isImmediatePropagationStopped = function() {
13594 return event.immediatePropagationStopped === true;
13597 // Some events have special handlers that wrap the real handler
13598 var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
13600 // Copy event handlers in case event handlers array is modified during execution.
13601 if ((eventFnsLength > 1)) {
13602 eventFns = shallowCopy(eventFns);
13605 for (var i = 0; i < eventFnsLength; i++) {
13606 if (!event.isImmediatePropagationStopped()) {
13607 handlerWrapper(element, event, eventFns[i]);
13612 // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
13613 // events on `element`
13614 eventHandler.elem = element;
13615 return eventHandler;
13618 function defaultHandlerWrapper(element, event, handler) {
13619 handler.call(element, event);
13622 function specialMouseHandlerWrapper(target, event, handler) {
13623 // Refer to jQuery's implementation of mouseenter & mouseleave
13624 // Read about mouseenter and mouseleave:
13625 // http://www.quirksmode.org/js/events_mouse.html#link8
13626 var related = event.relatedTarget;
13627 // For mousenter/leave call the handler if related is outside the target.
13628 // NB: No relatedTarget if the mouse left/entered the browser window
13629 if (!related || (related !== target && !jqLiteContains.call(target, related))) {
13630 handler.call(target, event);
13634 //////////////////////////////////////////
13635 // Functions iterating traversal.
13636 // These functions chain results into a single
13638 //////////////////////////////////////////
13640 removeData: jqLiteRemoveData,
13642 on: function jqLiteOn(element, type, fn, unsupported) {
13643 if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
13645 // Do not add event handlers to non-elements because they will not be cleaned up.
13646 if (!jqLiteAcceptsData(element)) {
13650 var expandoStore = jqLiteExpandoStore(element, true);
13651 var events = expandoStore.events;
13652 var handle = expandoStore.handle;
13655 handle = expandoStore.handle = createEventHandler(element, events);
13658 // http://jsperf.com/string-indexof-vs-split
13659 var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
13660 var i = types.length;
13662 var addHandler = function(type, specialHandlerWrapper, noEventListener) {
13663 var eventFns = events[type];
13666 eventFns = events[type] = [];
13667 eventFns.specialHandlerWrapper = specialHandlerWrapper;
13668 if (type !== '$destroy' && !noEventListener) {
13669 addEventListenerFn(element, type, handle);
13678 if (MOUSE_EVENT_MAP[type]) {
13679 addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
13680 addHandler(type, undefined, true);
13689 one: function(element, type, fn) {
13690 element = jqLite(element);
13692 //add the listener twice so that when it is called
13693 //you can remove the original function and still be
13694 //able to call element.off(ev, fn) normally
13695 element.on(type, function onFn() {
13696 element.off(type, fn);
13697 element.off(type, onFn);
13699 element.on(type, fn);
13702 replaceWith: function(element, replaceNode) {
13703 var index, parent = element.parentNode;
13704 jqLiteDealoc(element);
13705 forEach(new JQLite(replaceNode), function(node) {
13707 parent.insertBefore(node, index.nextSibling);
13709 parent.replaceChild(node, element);
13715 children: function(element) {
13717 forEach(element.childNodes, function(element) {
13718 if (element.nodeType === NODE_TYPE_ELEMENT) {
13719 children.push(element);
13725 contents: function(element) {
13726 return element.contentDocument || element.childNodes || [];
13729 append: function(element, node) {
13730 var nodeType = element.nodeType;
13731 if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
13733 node = new JQLite(node);
13735 for (var i = 0, ii = node.length; i < ii; i++) {
13736 var child = node[i];
13737 element.appendChild(child);
13741 prepend: function(element, node) {
13742 if (element.nodeType === NODE_TYPE_ELEMENT) {
13743 var index = element.firstChild;
13744 forEach(new JQLite(node), function(child) {
13745 element.insertBefore(child, index);
13750 wrap: function(element, wrapNode) {
13751 jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
13754 remove: jqLiteRemove,
13756 detach: function(element) {
13757 jqLiteRemove(element, true);
13760 after: function(element, newElement) {
13761 var index = element, parent = element.parentNode;
13764 newElement = new JQLite(newElement);
13766 for (var i = 0, ii = newElement.length; i < ii; i++) {
13767 var node = newElement[i];
13768 parent.insertBefore(node, index.nextSibling);
13774 addClass: jqLiteAddClass,
13775 removeClass: jqLiteRemoveClass,
13777 toggleClass: function(element, selector, condition) {
13779 forEach(selector.split(' '), function(className) {
13780 var classCondition = condition;
13781 if (isUndefined(classCondition)) {
13782 classCondition = !jqLiteHasClass(element, className);
13784 (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
13789 parent: function(element) {
13790 var parent = element.parentNode;
13791 return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
13794 next: function(element) {
13795 return element.nextElementSibling;
13798 find: function(element, selector) {
13799 if (element.getElementsByTagName) {
13800 return element.getElementsByTagName(selector);
13806 clone: jqLiteClone,
13808 triggerHandler: function(element, event, extraParameters) {
13810 var dummyEvent, eventFnsCopy, handlerArgs;
13811 var eventName = event.type || event;
13812 var expandoStore = jqLiteExpandoStore(element);
13813 var events = expandoStore && expandoStore.events;
13814 var eventFns = events && events[eventName];
13817 // Create a dummy event to pass to the handlers
13819 preventDefault: function() { this.defaultPrevented = true; },
13820 isDefaultPrevented: function() { return this.defaultPrevented === true; },
13821 stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
13822 isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
13823 stopPropagation: noop,
13828 // If a custom event was provided then extend our dummy event with it
13830 dummyEvent = extend(dummyEvent, event);
13833 // Copy event handlers in case event handlers array is modified during execution.
13834 eventFnsCopy = shallowCopy(eventFns);
13835 handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
13837 forEach(eventFnsCopy, function(fn) {
13838 if (!dummyEvent.isImmediatePropagationStopped()) {
13839 fn.apply(element, handlerArgs);
13844 }, function(fn, name) {
13846 * chaining functions
13848 JQLite.prototype[name] = function(arg1, arg2, arg3) {
13851 for (var i = 0, ii = this.length; i < ii; i++) {
13852 if (isUndefined(value)) {
13853 value = fn(this[i], arg1, arg2, arg3);
13854 if (isDefined(value)) {
13855 // any function which returns a value needs to be wrapped
13856 value = jqLite(value);
13859 jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
13862 return isDefined(value) ? value : this;
13866 // bind legacy bind/unbind to on/off
13867 JQLite.prototype.bind = JQLite.prototype.on;
13868 JQLite.prototype.unbind = JQLite.prototype.off;
13871 // Provider for private $$jqLite service
13873 function $$jqLiteProvider() {
13874 this.$get = function $$jqLite() {
13875 return extend(JQLite, {
13876 hasClass: function(node, classes) {
13877 if (node.attr) node = node[0];
13878 return jqLiteHasClass(node, classes);
13880 addClass: function(node, classes) {
13881 if (node.attr) node = node[0];
13882 return jqLiteAddClass(node, classes);
13884 removeClass: function(node, classes) {
13885 if (node.attr) node = node[0];
13886 return jqLiteRemoveClass(node, classes);
13893 * Computes a hash of an 'obj'.
13896 * number is number as string
13897 * object is either result of calling $$hashKey function on the object or uniquely generated id,
13898 * that is also assigned to the $$hashKey property of the object.
13901 * @returns {string} hash string such that the same input will have the same hash string.
13902 * The resulting string key is in 'type:hashKey' format.
13904 function hashKey(obj, nextUidFn) {
13905 var key = obj && obj.$$hashKey;
13908 if (typeof key === 'function') {
13909 key = obj.$$hashKey();
13914 var objType = typeof obj;
13915 if (objType === 'function' || (objType === 'object' && obj !== null)) {
13916 key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
13918 key = objType + ':' + obj;
13925 * HashMap which can use objects as keys
13927 function HashMap(array, isolatedUid) {
13930 this.nextUid = function() {
13934 forEach(array, this.put, this);
13936 HashMap.prototype = {
13938 * Store key value pair
13939 * @param key key to store can be any type
13940 * @param value value to store can be any type
13942 put: function(key, value) {
13943 this[hashKey(key, this.nextUid)] = value;
13948 * @returns {Object} the value for the key
13950 get: function(key) {
13951 return this[hashKey(key, this.nextUid)];
13955 * Remove the key/value pair
13958 remove: function(key) {
13959 var value = this[key = hashKey(key, this.nextUid)];
13965 var $$HashMapProvider = [/** @this */function() {
13966 this.$get = [function() {
13974 * @name angular.injector
13978 * Creates an injector object that can be used for retrieving services as well as for
13979 * dependency injection (see {@link guide/di dependency injection}).
13981 * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
13982 * {@link angular.module}. The `ng` module must be explicitly added.
13983 * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
13984 * disallows argument name annotation inference.
13985 * @returns {injector} Injector object. See {@link auto.$injector $injector}.
13990 * // create an injector
13991 * var $injector = angular.injector(['ng']);
13993 * // use the injector to kick off your application
13994 * // use the type inference to auto inject arguments, or use implicit injection
13995 * $injector.invoke(function($rootScope, $compile, $document) {
13996 * $compile($document)($rootScope);
13997 * $rootScope.$digest();
14001 * Sometimes you want to get access to the injector of a currently running Angular app
14002 * from outside Angular. Perhaps, you want to inject and compile some markup after the
14003 * application has been bootstrapped. You can do this using the extra `injector()` added
14004 * to JQuery/jqLite elements. See {@link angular.element}.
14006 * *This is fairly rare but could be the case if a third party library is injecting the
14009 * In the following example a new block of HTML containing a `ng-controller`
14010 * directive is added to the end of the document body by JQuery. We then compile and link
14011 * it into the current AngularJS scope.
14014 * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
14015 * $(document.body).append($div);
14017 * angular.element(document).injector().invoke(function($compile) {
14018 * var scope = angular.element($div).scope();
14019 * $compile($div)(scope);
14031 * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
14034 var ARROW_ARG = /^([^(]+?)=>/;
14035 var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m;
14036 var FN_ARG_SPLIT = /,/;
14037 var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
14038 var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
14039 var $injectorMinErr = minErr('$injector');
14041 function stringifyFn(fn) {
14042 // Support: Chrome 50-51 only
14043 // Creating a new string by adding `' '` at the end, to hack around some bug in Chrome v50/51
14044 // (See https://github.com/angular/angular.js/issues/14487.)
14045 // TODO (gkalpak): Remove workaround when Chrome v52 is released
14046 return Function.prototype.toString.call(fn) + ' ';
14049 function extractArgs(fn) {
14050 var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
14051 args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
14055 function anonFn(fn) {
14056 // For anonymous functions, showing at the very least the function signature can help in
14058 var args = extractArgs(fn);
14060 return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
14065 function annotate(fn, strictDi, name) {
14070 if (typeof fn === 'function') {
14071 if (!($inject = fn.$inject)) {
14075 if (!isString(name) || !name) {
14076 name = fn.name || anonFn(fn);
14078 throw $injectorMinErr('strictdi',
14079 '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
14081 argDecl = extractArgs(fn);
14082 forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
14083 arg.replace(FN_ARG, function(all, underscore, name) {
14084 $inject.push(name);
14088 fn.$inject = $inject;
14090 } else if (isArray(fn)) {
14091 last = fn.length - 1;
14092 assertArgFn(fn[last], 'fn');
14093 $inject = fn.slice(0, last);
14095 assertArgFn(fn, 'fn', true);
14100 ///////////////////////////////////////
14108 * `$injector` is used to retrieve object instances as defined by
14109 * {@link auto.$provide provider}, instantiate types, invoke methods,
14110 * and load modules.
14112 * The following always holds true:
14115 * var $injector = angular.injector();
14116 * expect($injector.get('$injector')).toBe($injector);
14117 * expect($injector.invoke(function($injector) {
14118 * return $injector;
14119 * })).toBe($injector);
14122 * # Injection Function Annotation
14124 * JavaScript does not have annotations, and annotations are needed for dependency injection. The
14125 * following are all valid ways of annotating function with injection arguments and are equivalent.
14128 * // inferred (only works if code not minified/obfuscated)
14129 * $injector.invoke(function(serviceA){});
14132 * function explicit(serviceA) {};
14133 * explicit.$inject = ['serviceA'];
14134 * $injector.invoke(explicit);
14137 * $injector.invoke(['serviceA', function(serviceA){}]);
14142 * In JavaScript calling `toString()` on a function returns the function definition. The definition
14143 * can then be parsed and the function arguments can be extracted. This method of discovering
14144 * annotations is disallowed when the injector is in strict mode.
14145 * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
14148 * ## `$inject` Annotation
14149 * By adding an `$inject` property onto a function the injection parameters can be specified.
14152 * As an array of injection names, where the last item in the array is the function to call.
14157 * @name $injector#get
14160 * Return an instance of the service.
14162 * @param {string} name The name of the instance to retrieve.
14163 * @param {string=} caller An optional string to provide the origin of the function call for error messages.
14164 * @return {*} The instance.
14169 * @name $injector#invoke
14172 * Invoke the method and supply the method arguments from the `$injector`.
14174 * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
14175 * injected according to the {@link guide/di $inject Annotation} rules.
14176 * @param {Object=} self The `this` for the invoked method.
14177 * @param {Object=} locals Optional object. If preset then any argument names are read from this
14178 * object first, before the `$injector` is consulted.
14179 * @returns {*} the value returned by the invoked `fn` function.
14184 * @name $injector#has
14187 * Allows the user to query if the particular service exists.
14189 * @param {string} name Name of the service to query.
14190 * @returns {boolean} `true` if injector has given service.
14195 * @name $injector#instantiate
14197 * Create a new instance of JS type. The method takes a constructor function, invokes the new
14198 * operator, and supplies all of the arguments to the constructor function as specified by the
14199 * constructor annotation.
14201 * @param {Function} Type Annotated constructor function.
14202 * @param {Object=} locals Optional object. If preset then any argument names are read from this
14203 * object first, before the `$injector` is consulted.
14204 * @returns {Object} new instance of `Type`.
14209 * @name $injector#annotate
14212 * Returns an array of service names which the function is requesting for injection. This API is
14213 * used by the injector to determine which services need to be injected into the function when the
14214 * function is invoked. There are three ways in which the function can be annotated with the needed
14219 * The simplest form is to extract the dependencies from the arguments of the function. This is done
14220 * by converting the function into a string using `toString()` method and extracting the argument
14224 * function MyController($scope, $route) {
14229 * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
14232 * You can disallow this method by using strict injection mode.
14234 * This method does not work with code minification / obfuscation. For this reason the following
14235 * annotation strategies are supported.
14237 * # The `$inject` property
14239 * If a function has an `$inject` property and its value is an array of strings, then the strings
14240 * represent names of services to be injected into the function.
14243 * var MyController = function(obfuscatedScope, obfuscatedRoute) {
14246 * // Define function dependencies
14247 * MyController['$inject'] = ['$scope', '$route'];
14250 * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
14253 * # The array notation
14255 * It is often desirable to inline Injected functions and that's when setting the `$inject` property
14256 * is very inconvenient. In these situations using the array notation to specify the dependencies in
14257 * a way that survives minification is a better choice:
14260 * // We wish to write this (not minification / obfuscation safe)
14261 * injector.invoke(function($compile, $rootScope) {
14265 * // We are forced to write break inlining
14266 * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
14269 * tmpFn.$inject = ['$compile', '$rootScope'];
14270 * injector.invoke(tmpFn);
14272 * // To better support inline function the inline annotation is supported
14273 * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
14278 * expect(injector.annotate(
14279 * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
14280 * ).toEqual(['$compile', '$rootScope']);
14283 * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
14284 * be retrieved as described above.
14286 * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
14288 * @returns {Array.<string>} The names of the services which the function requires.
14299 * The {@link auto.$provide $provide} service has a number of methods for registering components
14300 * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
14301 * {@link angular.Module}.
14303 * An Angular **service** is a singleton object created by a **service factory**. These **service
14304 * factories** are functions which, in turn, are created by a **service provider**.
14305 * The **service providers** are constructor functions. When instantiated they must contain a
14306 * property called `$get`, which holds the **service factory** function.
14308 * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
14309 * correct **service provider**, instantiating it and then calling its `$get` **service factory**
14310 * function to get the instance of the **service**.
14312 * Often services have no configuration options and there is no need to add methods to the service
14313 * provider. The provider will be no more than a constructor function with a `$get` property. For
14314 * these cases the {@link auto.$provide $provide} service has additional helper methods to register
14315 * services without specifying a provider.
14317 * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
14318 * {@link auto.$injector $injector}
14319 * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
14320 * providers and services.
14321 * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
14322 * services, not providers.
14323 * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
14324 * that will be wrapped in a **service provider** object, whose `$get` property will contain the
14325 * given factory function.
14326 * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
14327 * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
14328 * a new object using the given constructor function.
14329 * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
14330 * will be able to modify or replace the implementation of another service.
14332 * See the individual methods for more information and examples.
14337 * @name $provide#provider
14340 * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
14341 * are constructor functions, whose instances are responsible for "providing" a factory for a
14344 * Service provider names start with the name of the service they provide followed by `Provider`.
14345 * For example, the {@link ng.$log $log} service has a provider called
14346 * {@link ng.$logProvider $logProvider}.
14348 * Service provider objects can have additional methods which allow configuration of the provider
14349 * and its service. Importantly, you can configure what kind of service is created by the `$get`
14350 * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
14351 * method {@link ng.$logProvider#debugEnabled debugEnabled}
14352 * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
14355 * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
14357 * @param {(Object|function())} provider If the provider is:
14359 * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
14360 * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
14361 * - `Constructor`: a new instance of the provider will be created using
14362 * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
14364 * @returns {Object} registered provider instance
14368 * The following example shows how to create a simple event tracking service and register it using
14369 * {@link auto.$provide#provider $provide.provider()}.
14372 * // Define the eventTracker provider
14373 * function EventTrackerProvider() {
14374 * var trackingUrl = '/track';
14376 * // A provider method for configuring where the tracked events should been saved
14377 * this.setTrackingUrl = function(url) {
14378 * trackingUrl = url;
14381 * // The service factory function
14382 * this.$get = ['$http', function($http) {
14383 * var trackedEvents = {};
14385 * // Call this to track an event
14386 * event: function(event) {
14387 * var count = trackedEvents[event] || 0;
14389 * trackedEvents[event] = count;
14392 * // Call this to save the tracked events to the trackingUrl
14393 * save: function() {
14394 * $http.post(trackingUrl, trackedEvents);
14400 * describe('eventTracker', function() {
14403 * beforeEach(module(function($provide) {
14404 * // Register the eventTracker provider
14405 * $provide.provider('eventTracker', EventTrackerProvider);
14408 * beforeEach(module(function(eventTrackerProvider) {
14409 * // Configure eventTracker provider
14410 * eventTrackerProvider.setTrackingUrl('/custom-track');
14413 * it('tracks events', inject(function(eventTracker) {
14414 * expect(eventTracker.event('login')).toEqual(1);
14415 * expect(eventTracker.event('login')).toEqual(2);
14418 * it('saves to the tracking url', inject(function(eventTracker, $http) {
14419 * postSpy = spyOn($http, 'post');
14420 * eventTracker.event('login');
14421 * eventTracker.save();
14422 * expect(postSpy).toHaveBeenCalled();
14423 * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
14424 * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
14425 * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
14433 * @name $provide#factory
14436 * Register a **service factory**, which will be called to return the service instance.
14437 * This is short for registering a service where its provider consists of only a `$get` property,
14438 * which is the given service factory function.
14439 * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
14440 * configure your service in a provider.
14442 * @param {string} name The name of the instance.
14443 * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
14444 * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
14445 * @returns {Object} registered provider instance
14448 * Here is an example of registering a service
14450 * $provide.factory('ping', ['$http', function($http) {
14451 * return function ping() {
14452 * return $http.send('/ping');
14456 * You would then inject and use this service like this:
14458 * someModule.controller('Ctrl', ['ping', function(ping) {
14467 * @name $provide#service
14470 * Register a **service constructor**, which will be invoked with `new` to create the service
14472 * This is short for registering a service where its provider's `$get` property is a factory
14473 * function that returns an instance instantiated by the injector from the service constructor
14476 * Internally it looks a bit like this:
14480 * $get: function() {
14481 * return $injector.instantiate(constructor);
14487 * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
14490 * @param {string} name The name of the instance.
14491 * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
14492 * that will be instantiated.
14493 * @returns {Object} registered provider instance
14496 * Here is an example of registering a service using
14497 * {@link auto.$provide#service $provide.service(class)}.
14499 * var Ping = function($http) {
14500 * this.$http = $http;
14503 * Ping.$inject = ['$http'];
14505 * Ping.prototype.send = function() {
14506 * return this.$http.get('/ping');
14508 * $provide.service('ping', Ping);
14510 * You would then inject and use this service like this:
14512 * someModule.controller('Ctrl', ['ping', function(ping) {
14521 * @name $provide#value
14524 * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
14525 * number, an array, an object or a function. This is short for registering a service where its
14526 * provider's `$get` property is a factory function that takes no arguments and returns the **value
14527 * service**. That also means it is not possible to inject other services into a value service.
14529 * Value services are similar to constant services, except that they cannot be injected into a
14530 * module configuration function (see {@link angular.Module#config}) but they can be overridden by
14531 * an Angular {@link auto.$provide#decorator decorator}.
14533 * @param {string} name The name of the instance.
14534 * @param {*} value The value.
14535 * @returns {Object} registered provider instance
14538 * Here are some examples of creating value services.
14540 * $provide.value('ADMIN_USER', 'admin');
14542 * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
14544 * $provide.value('halfOf', function(value) {
14545 * return value / 2;
14553 * @name $provide#constant
14556 * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
14557 * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
14558 * possible to inject other services into a constant.
14560 * But unlike {@link auto.$provide#value value}, a constant can be
14561 * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
14562 * be overridden by an Angular {@link auto.$provide#decorator decorator}.
14564 * @param {string} name The name of the constant.
14565 * @param {*} value The constant value.
14566 * @returns {Object} registered instance
14569 * Here a some examples of creating constants:
14571 * $provide.constant('SHARD_HEIGHT', 306);
14573 * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
14575 * $provide.constant('double', function(value) {
14576 * return value * 2;
14584 * @name $provide#decorator
14587 * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
14588 * intercepts the creation of a service, allowing it to override or modify the behavior of the
14589 * service. The return value of the decorator function may be the original service, or a new service
14590 * that replaces (or wraps and delegates to) the original service.
14592 * You can find out more about using decorators in the {@link guide/decorators} guide.
14594 * @param {string} name The name of the service to decorate.
14595 * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
14596 * provided and should return the decorated service instance. The function is called using
14597 * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
14598 * Local injection arguments:
14600 * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
14601 * decorated or delegated to.
14604 * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
14605 * calls to {@link ng.$log#error $log.warn()}.
14607 * $provide.decorator('$log', ['$delegate', function($delegate) {
14608 * $delegate.warn = $delegate.error;
14609 * return $delegate;
14615 function createInjector(modulesToLoad, strictDi) {
14616 strictDi = (strictDi === true);
14617 var INSTANTIATING = {},
14618 providerSuffix = 'Provider',
14620 loadedModules = new HashMap([], true),
14623 provider: supportObject(provider),
14624 factory: supportObject(factory),
14625 service: supportObject(service),
14626 value: supportObject(value),
14627 constant: supportObject(constant),
14628 decorator: decorator
14631 providerInjector = (providerCache.$injector =
14632 createInternalInjector(providerCache, function(serviceName, caller) {
14633 if (angular.isString(caller)) {
14636 throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
14638 instanceCache = {},
14639 protoInstanceInjector =
14640 createInternalInjector(instanceCache, function(serviceName, caller) {
14641 var provider = providerInjector.get(serviceName + providerSuffix, caller);
14642 return instanceInjector.invoke(
14643 provider.$get, provider, undefined, serviceName);
14645 instanceInjector = protoInstanceInjector;
14647 providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
14648 var runBlocks = loadModules(modulesToLoad);
14649 instanceInjector = protoInstanceInjector.get('$injector');
14650 instanceInjector.strictDi = strictDi;
14651 forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
14653 return instanceInjector;
14655 ////////////////////////////////////
14657 ////////////////////////////////////
14659 function supportObject(delegate) {
14660 return function(key, value) {
14661 if (isObject(key)) {
14662 forEach(key, reverseParams(delegate));
14664 return delegate(key, value);
14669 function provider(name, provider_) {
14670 assertNotHasOwnProperty(name, 'service');
14671 if (isFunction(provider_) || isArray(provider_)) {
14672 provider_ = providerInjector.instantiate(provider_);
14674 if (!provider_.$get) {
14675 throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
14677 return (providerCache[name + providerSuffix] = provider_);
14680 function enforceReturnValue(name, factory) {
14681 return /** @this */ function enforcedReturnValue() {
14682 var result = instanceInjector.invoke(factory, this);
14683 if (isUndefined(result)) {
14684 throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name);
14690 function factory(name, factoryFn, enforce) {
14691 return provider(name, {
14692 $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
14696 function service(name, constructor) {
14697 return factory(name, ['$injector', function($injector) {
14698 return $injector.instantiate(constructor);
14702 function value(name, val) { return factory(name, valueFn(val), false); }
14704 function constant(name, value) {
14705 assertNotHasOwnProperty(name, 'constant');
14706 providerCache[name] = value;
14707 instanceCache[name] = value;
14710 function decorator(serviceName, decorFn) {
14711 var origProvider = providerInjector.get(serviceName + providerSuffix),
14712 orig$get = origProvider.$get;
14714 origProvider.$get = function() {
14715 var origInstance = instanceInjector.invoke(orig$get, origProvider);
14716 return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
14720 ////////////////////////////////////
14722 ////////////////////////////////////
14723 function loadModules(modulesToLoad) {
14724 assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
14725 var runBlocks = [], moduleFn;
14726 forEach(modulesToLoad, function(module) {
14727 if (loadedModules.get(module)) return;
14728 loadedModules.put(module, true);
14730 function runInvokeQueue(queue) {
14732 for (i = 0, ii = queue.length; i < ii; i++) {
14733 var invokeArgs = queue[i],
14734 provider = providerInjector.get(invokeArgs[0]);
14736 provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
14741 if (isString(module)) {
14742 moduleFn = angularModule(module);
14743 runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
14744 runInvokeQueue(moduleFn._invokeQueue);
14745 runInvokeQueue(moduleFn._configBlocks);
14746 } else if (isFunction(module)) {
14747 runBlocks.push(providerInjector.invoke(module));
14748 } else if (isArray(module)) {
14749 runBlocks.push(providerInjector.invoke(module));
14751 assertArgFn(module, 'module');
14754 if (isArray(module)) {
14755 module = module[module.length - 1];
14757 if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {
14758 // Safari & FF's stack traces don't contain error.message content
14759 // unlike those of Chrome and IE
14760 // So if stack doesn't contain message, we create a new string that contains both.
14761 // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
14762 // eslint-disable-next-line no-ex-assign
14763 e = e.message + '\n' + e.stack;
14765 throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
14766 module, e.stack || e.message || e);
14772 ////////////////////////////////////
14773 // internal Injector
14774 ////////////////////////////////////
14776 function createInternalInjector(cache, factory) {
14778 function getService(serviceName, caller) {
14779 if (cache.hasOwnProperty(serviceName)) {
14780 if (cache[serviceName] === INSTANTIATING) {
14781 throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
14782 serviceName + ' <- ' + path.join(' <- '));
14784 return cache[serviceName];
14787 path.unshift(serviceName);
14788 cache[serviceName] = INSTANTIATING;
14789 cache[serviceName] = factory(serviceName, caller);
14790 return cache[serviceName];
14792 if (cache[serviceName] === INSTANTIATING) {
14793 delete cache[serviceName];
14803 function injectionArgs(fn, locals, serviceName) {
14805 $inject = createInjector.$$annotate(fn, strictDi, serviceName);
14807 for (var i = 0, length = $inject.length; i < length; i++) {
14808 var key = $inject[i];
14809 if (typeof key !== 'string') {
14810 throw $injectorMinErr('itkn',
14811 'Incorrect injection token! Expected service name as string, got {0}', key);
14813 args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
14814 getService(key, serviceName));
14819 function isClass(func) {
14820 // IE 9-11 do not support classes and IE9 leaks with the code below.
14824 // Support: Edge 12-13 only
14825 // See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/
14826 return typeof func === 'function'
14827 && /^(?:class\b|constructor\()/.test(stringifyFn(func));
14830 function invoke(fn, self, locals, serviceName) {
14831 if (typeof locals === 'string') {
14832 serviceName = locals;
14836 var args = injectionArgs(fn, locals, serviceName);
14838 fn = fn[fn.length - 1];
14841 if (!isClass(fn)) {
14842 // http://jsperf.com/angularjs-invoke-apply-vs-switch
14844 return fn.apply(self, args);
14846 args.unshift(null);
14847 return new (Function.prototype.bind.apply(fn, args))();
14852 function instantiate(Type, locals, serviceName) {
14853 // Check if Type is annotated and use just the given function at n-1 as parameter
14854 // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
14855 var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
14856 var args = injectionArgs(Type, locals, serviceName);
14857 // Empty object at position 0 is ignored for invocation with `new`, but required.
14858 args.unshift(null);
14859 return new (Function.prototype.bind.apply(ctor, args))();
14865 instantiate: instantiate,
14867 annotate: createInjector.$$annotate,
14868 has: function(name) {
14869 return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
14875 createInjector.$$annotate = annotate;
14879 * @name $anchorScrollProvider
14883 * Use `$anchorScrollProvider` to disable automatic scrolling whenever
14884 * {@link ng.$location#hash $location.hash()} changes.
14886 function $AnchorScrollProvider() {
14888 var autoScrollingEnabled = true;
14892 * @name $anchorScrollProvider#disableAutoScrolling
14895 * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
14896 * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
14897 * Use this method to disable automatic scrolling.
14899 * If automatic scrolling is disabled, one must explicitly call
14900 * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
14903 this.disableAutoScrolling = function() {
14904 autoScrollingEnabled = false;
14909 * @name $anchorScroll
14911 * @requires $window
14912 * @requires $location
14913 * @requires $rootScope
14916 * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
14917 * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
14919 * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
14921 * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
14922 * match any anchor whenever it changes. This can be disabled by calling
14923 * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
14925 * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
14926 * vertical scroll-offset (either fixed or dynamic).
14928 * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
14929 * {@link ng.$location#hash $location.hash()} will be used.
14931 * @property {(number|function|jqLite)} yOffset
14932 * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
14933 * positioned elements at the top of the page, such as navbars, headers etc.
14935 * `yOffset` can be specified in various ways:
14936 * - **number**: A fixed number of pixels to be used as offset.<br /><br />
14937 * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
14938 * a number representing the offset (in pixels).<br /><br />
14939 * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
14940 * the top of the page to the element's bottom will be used as offset.<br />
14941 * **Note**: The element will be taken into account only as long as its `position` is set to
14942 * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
14943 * their height and/or positioning according to the viewport's size.
14946 * <div class="alert alert-warning">
14947 * In order for `yOffset` to work properly, scrolling should take place on the document's root and
14948 * not some child element.
14952 <example module="anchorScrollExample" name="anchor-scroll">
14953 <file name="index.html">
14954 <div id="scrollArea" ng-controller="ScrollController">
14955 <a ng-click="gotoBottom()">Go to bottom</a>
14956 <a id="bottom"></a> You're at the bottom!
14959 <file name="script.js">
14960 angular.module('anchorScrollExample', [])
14961 .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
14962 function($scope, $location, $anchorScroll) {
14963 $scope.gotoBottom = function() {
14964 // set the location.hash to the id of
14965 // the element you wish to scroll to.
14966 $location.hash('bottom');
14968 // call $anchorScroll()
14973 <file name="style.css">
14981 margin-top: 2000px;
14987 * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
14988 * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
14991 <example module="anchorScrollOffsetExample" name="anchor-scroll-offset">
14992 <file name="index.html">
14993 <div class="fixed-header" ng-controller="headerCtrl">
14994 <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
14998 <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
15002 <file name="script.js">
15003 angular.module('anchorScrollOffsetExample', [])
15004 .run(['$anchorScroll', function($anchorScroll) {
15005 $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
15007 .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
15008 function($anchorScroll, $location, $scope) {
15009 $scope.gotoAnchor = function(x) {
15010 var newHash = 'anchor' + x;
15011 if ($location.hash() !== newHash) {
15012 // set the $location.hash to `newHash` and
15013 // $anchorScroll will automatically scroll to it
15014 $location.hash('anchor' + x);
15016 // call $anchorScroll() explicitly,
15017 // since $location.hash hasn't changed
15024 <file name="style.css">
15030 border: 2px dashed DarkOrchid;
15031 padding: 10px 10px 200px 10px;
15035 background-color: rgba(0, 0, 0, 0.2);
15038 top: 0; left: 0; right: 0;
15041 .fixed-header > a {
15042 display: inline-block;
15048 this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
15049 var document = $window.document;
15051 // Helper function to get first anchor from a NodeList
15052 // (using `Array#some()` instead of `angular#forEach()` since it's more performant
15053 // and working in all supported browsers.)
15054 function getFirstAnchor(list) {
15056 Array.prototype.some.call(list, function(element) {
15057 if (nodeName_(element) === 'a') {
15065 function getYOffset() {
15067 var offset = scroll.yOffset;
15069 if (isFunction(offset)) {
15071 } else if (isElement(offset)) {
15072 var elem = offset[0];
15073 var style = $window.getComputedStyle(elem);
15074 if (style.position !== 'fixed') {
15077 offset = elem.getBoundingClientRect().bottom;
15079 } else if (!isNumber(offset)) {
15086 function scrollTo(elem) {
15088 elem.scrollIntoView();
15090 var offset = getYOffset();
15093 // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
15094 // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
15095 // top of the viewport.
15097 // IF the number of pixels from the top of `elem` to the end of the page's content is less
15098 // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
15099 // way down the page.
15101 // This is often the case for elements near the bottom of the page.
15103 // In such cases we do not need to scroll the whole `offset` up, just the difference between
15104 // the top of the element and the offset, which is enough to align the top of `elem` at the
15105 // desired position.
15106 var elemTop = elem.getBoundingClientRect().top;
15107 $window.scrollBy(0, elemTop - offset);
15110 $window.scrollTo(0, 0);
15114 function scroll(hash) {
15115 // Allow numeric hashes
15116 hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();
15119 // empty hash, scroll to the top of the page
15120 if (!hash) scrollTo(null);
15122 // element with given id
15123 else if ((elm = document.getElementById(hash))) scrollTo(elm);
15125 // first anchor with given name :-D
15126 else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
15128 // no element and hash === 'top', scroll to the top of the page
15129 else if (hash === 'top') scrollTo(null);
15132 // does not scroll when user clicks on anchor link that is currently on
15133 // (no url change, no $location.hash() change), browser native does scroll
15134 if (autoScrollingEnabled) {
15135 $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
15136 function autoScrollWatchAction(newVal, oldVal) {
15137 // skip the initial scroll if $location.hash is empty
15138 if (newVal === oldVal && newVal === '') return;
15140 jqLiteDocumentLoaded(function() {
15141 $rootScope.$evalAsync(scroll);
15150 var $animateMinErr = minErr('$animate');
15151 var ELEMENT_NODE = 1;
15152 var NG_ANIMATE_CLASSNAME = 'ng-animate';
15154 function mergeClasses(a,b) {
15155 if (!a && !b) return '';
15158 if (isArray(a)) a = a.join(' ');
15159 if (isArray(b)) b = b.join(' ');
15160 return a + ' ' + b;
15163 function extractElementNode(element) {
15164 for (var i = 0; i < element.length; i++) {
15165 var elm = element[i];
15166 if (elm.nodeType === ELEMENT_NODE) {
15172 function splitClasses(classes) {
15173 if (isString(classes)) {
15174 classes = classes.split(' ');
15177 // Use createMap() to prevent class assumptions involving property names in
15178 // Object.prototype
15179 var obj = createMap();
15180 forEach(classes, function(klass) {
15181 // sometimes the split leaves empty string values
15182 // incase extra spaces were applied to the options
15183 if (klass.length) {
15190 // if any other type of options value besides an Object value is
15191 // passed into the $animate.method() animation then this helper code
15192 // will be run which will ignore it. While this patch is not the
15193 // greatest solution to this, a lot of existing plugins depend on
15194 // $animate to either call the callback (< 1.2) or return a promise
15195 // that can be changed. This helper function ensures that the options
15196 // are wiped clean incase a callback function is provided.
15197 function prepareAnimateOptions(options) {
15198 return isObject(options)
15203 var $$CoreAnimateJsProvider = /** @this */ function() {
15207 // this is prefixed with Core since it conflicts with
15208 // the animateQueueProvider defined in ngAnimate/animateQueue.js
15209 var $$CoreAnimateQueueProvider = /** @this */ function() {
15210 var postDigestQueue = new HashMap();
15211 var postDigestElements = [];
15213 this.$get = ['$$AnimateRunner', '$rootScope',
15214 function($$AnimateRunner, $rootScope) {
15221 push: function(element, event, options, domOperation) {
15222 if (domOperation) {
15226 options = options || {};
15227 if (options.from) {
15228 element.css(options.from);
15231 element.css(options.to);
15234 if (options.addClass || options.removeClass) {
15235 addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
15238 var runner = new $$AnimateRunner();
15240 // since there are no animations to run the runner needs to be
15241 // notified that the animation call is complete.
15248 function updateData(data, classes, value) {
15249 var changed = false;
15251 classes = isString(classes) ? classes.split(' ') :
15252 isArray(classes) ? classes : [];
15253 forEach(classes, function(className) {
15256 data[className] = value;
15263 function handleCSSClassChanges() {
15264 forEach(postDigestElements, function(element) {
15265 var data = postDigestQueue.get(element);
15267 var existing = splitClasses(element.attr('class'));
15270 forEach(data, function(status, className) {
15271 var hasClass = !!existing[className];
15272 if (status !== hasClass) {
15274 toAdd += (toAdd.length ? ' ' : '') + className;
15276 toRemove += (toRemove.length ? ' ' : '') + className;
15281 forEach(element, function(elm) {
15283 jqLiteAddClass(elm, toAdd);
15286 jqLiteRemoveClass(elm, toRemove);
15289 postDigestQueue.remove(element);
15292 postDigestElements.length = 0;
15296 function addRemoveClassesPostDigest(element, add, remove) {
15297 var data = postDigestQueue.get(element) || {};
15299 var classesAdded = updateData(data, add, true);
15300 var classesRemoved = updateData(data, remove, false);
15302 if (classesAdded || classesRemoved) {
15304 postDigestQueue.put(element, data);
15305 postDigestElements.push(element);
15307 if (postDigestElements.length === 1) {
15308 $rootScope.$$postDigest(handleCSSClassChanges);
15317 * @name $animateProvider
15320 * Default implementation of $animate that doesn't perform any animations, instead just
15321 * synchronously performs DOM updates and resolves the returned runner promise.
15323 * In order to enable animations the `ngAnimate` module has to be loaded.
15325 * To see the functional implementation check out `src/ngAnimate/animate.js`.
15327 var $AnimateProvider = ['$provide', /** @this */ function($provide) {
15328 var provider = this;
15330 this.$$registeredAnimations = Object.create(null);
15334 * @name $animateProvider#register
15337 * Registers a new injectable animation factory function. The factory function produces the
15338 * animation object which contains callback functions for each event that is expected to be
15341 * * `eventFn`: `function(element, ... , doneFunction, options)`
15342 * The element to animate, the `doneFunction` and the options fed into the animation. Depending
15343 * on the type of animation additional arguments will be injected into the animation function. The
15344 * list below explains the function signatures for the different animation methods:
15346 * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
15347 * - addClass: function(element, addedClasses, doneFunction, options)
15348 * - removeClass: function(element, removedClasses, doneFunction, options)
15349 * - enter, leave, move: function(element, doneFunction, options)
15350 * - animate: function(element, fromStyles, toStyles, doneFunction, options)
15352 * Make sure to trigger the `doneFunction` once the animation is fully complete.
15356 * //enter, leave, move signature
15357 * eventFn : function(element, done, options) {
15358 * //code to run the animation
15359 * //once complete, then run done()
15360 * return function endFunction(wasCancelled) {
15361 * //code to cancel the animation
15367 * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
15368 * @param {Function} factory The factory function that will be executed to return the animation
15371 this.register = function(name, factory) {
15372 if (name && name.charAt(0) !== '.') {
15373 throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
15376 var key = name + '-animation';
15377 provider.$$registeredAnimations[name.substr(1)] = key;
15378 $provide.factory(key, factory);
15383 * @name $animateProvider#classNameFilter
15386 * Sets and/or returns the CSS class regular expression that is checked when performing
15387 * an animation. Upon bootstrap the classNameFilter value is not set at all and will
15388 * therefore enable $animate to attempt to perform an animation on any element that is triggered.
15389 * When setting the `classNameFilter` value, animations will only be performed on elements
15390 * that successfully match the filter expression. This in turn can boost performance
15391 * for low-powered devices as well as applications containing a lot of structural operations.
15392 * @param {RegExp=} expression The className expression which will be checked against all animations
15393 * @return {RegExp} The current CSS className expression value. If null then there is no expression value
15395 this.classNameFilter = function(expression) {
15396 if (arguments.length === 1) {
15397 this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
15398 if (this.$$classNameFilter) {
15399 var reservedRegex = new RegExp('(\\s+|\\/)' + NG_ANIMATE_CLASSNAME + '(\\s+|\\/)');
15400 if (reservedRegex.test(this.$$classNameFilter.toString())) {
15401 throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
15406 return this.$$classNameFilter;
15409 this.$get = ['$$animateQueue', function($$animateQueue) {
15410 function domInsert(element, parentElement, afterElement) {
15411 // if for some reason the previous element was removed
15412 // from the dom sometime before this code runs then let's
15413 // just stick to using the parent element as the anchor
15414 if (afterElement) {
15415 var afterNode = extractElementNode(afterElement);
15416 if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
15417 afterElement = null;
15420 if (afterElement) {
15421 afterElement.after(element);
15423 parentElement.prepend(element);
15430 * @description The $animate service exposes a series of DOM utility methods that provide support
15431 * for animation hooks. The default behavior is the application of DOM operations, however,
15432 * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
15433 * to ensure that animation runs with the triggered DOM operation.
15435 * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
15436 * included and only when it is active then the animation hooks that `$animate` triggers will be
15437 * functional. Once active then all structural `ng-` directives will trigger animations as they perform
15438 * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
15439 * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
15441 * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
15443 * To learn more about enabling animation support, click here to visit the
15444 * {@link ngAnimate ngAnimate module page}.
15447 // we don't call it directly since non-existant arguments may
15448 // be interpreted as null within the sub enabled function
15453 * @name $animate#on
15455 * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
15456 * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
15457 * is fired with the following params:
15460 * $animate.on('enter', container,
15461 * function callback(element, phase) {
15462 * // cool we detected an enter animation within the container
15467 * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
15468 * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
15469 * as well as among its children
15470 * @param {Function} callback the callback function that will be fired when the listener is triggered
15472 * The arguments present in the callback function are:
15473 * * `element` - The captured DOM element that the animation was fired on.
15474 * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
15476 on: $$animateQueue.on,
15481 * @name $animate#off
15483 * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
15484 * can be used in three different ways depending on the arguments:
15487 * // remove all the animation event listeners listening for `enter`
15488 * $animate.off('enter');
15490 * // remove listeners for all animation events from the container element
15491 * $animate.off(container);
15493 * // remove all the animation event listeners listening for `enter` on the given element and its children
15494 * $animate.off('enter', container);
15496 * // remove the event listener function provided by `callback` that is set
15497 * // to listen for `enter` on the given `container` as well as its children
15498 * $animate.off('enter', container, callback);
15501 * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
15502 * addClass, removeClass, etc...), or the container element. If it is the element, all other
15503 * arguments are ignored.
15504 * @param {DOMElement=} container the container element the event listener was placed on
15505 * @param {Function=} callback the callback function that was registered as the listener
15507 off: $$animateQueue.off,
15511 * @name $animate#pin
15513 * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
15514 * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
15515 * element despite being outside the realm of the application or within another application. Say for example if the application
15516 * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
15517 * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
15518 * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
15520 * Note that this feature is only active when the `ngAnimate` module is used.
15522 * @param {DOMElement} element the external element that will be pinned
15523 * @param {DOMElement} parentElement the host parent element that will be associated with the external element
15525 pin: $$animateQueue.pin,
15530 * @name $animate#enabled
15532 * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
15533 * function can be called in four ways:
15536 * // returns true or false
15537 * $animate.enabled();
15539 * // changes the enabled state for all animations
15540 * $animate.enabled(false);
15541 * $animate.enabled(true);
15543 * // returns true or false if animations are enabled for an element
15544 * $animate.enabled(element);
15546 * // changes the enabled state for an element and its children
15547 * $animate.enabled(element, true);
15548 * $animate.enabled(element, false);
15551 * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
15552 * @param {boolean=} enabled whether or not the animations will be enabled for the element
15554 * @return {boolean} whether or not animations are enabled
15556 enabled: $$animateQueue.enabled,
15560 * @name $animate#cancel
15562 * @description Cancels the provided animation.
15564 * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
15566 cancel: function(runner) {
15575 * @name $animate#enter
15577 * @description Inserts the element into the DOM either after the `after` element (if provided) or
15578 * as the first child within the `parent` element and then triggers an animation.
15579 * A promise is returned that will be resolved during the next digest once the animation
15582 * @param {DOMElement} element the element which will be inserted into the DOM
15583 * @param {DOMElement} parent the parent element which will append the element as
15584 * a child (so long as the after element is not present)
15585 * @param {DOMElement=} after the sibling element after which the element will be appended
15586 * @param {object=} options an optional collection of options/styles that will be applied to the element.
15587 * The object can have the following properties:
15589 * - **addClass** - `{string}` - space-separated CSS classes to add to element
15590 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
15591 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
15592 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
15594 * @return {Promise} the animation callback promise
15596 enter: function(element, parent, after, options) {
15597 parent = parent && jqLite(parent);
15598 after = after && jqLite(after);
15599 parent = parent || after.parent();
15600 domInsert(element, parent, after);
15601 return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
15607 * @name $animate#move
15609 * @description Inserts (moves) the element into its new position in the DOM either after
15610 * the `after` element (if provided) or as the first child within the `parent` element
15611 * and then triggers an animation. A promise is returned that will be resolved
15612 * during the next digest once the animation has completed.
15614 * @param {DOMElement} element the element which will be moved into the new DOM position
15615 * @param {DOMElement} parent the parent element which will append the element as
15616 * a child (so long as the after element is not present)
15617 * @param {DOMElement=} after the sibling element after which the element will be appended
15618 * @param {object=} options an optional collection of options/styles that will be applied to the element.
15619 * The object can have the following properties:
15621 * - **addClass** - `{string}` - space-separated CSS classes to add to element
15622 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
15623 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
15624 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
15626 * @return {Promise} the animation callback promise
15628 move: function(element, parent, after, options) {
15629 parent = parent && jqLite(parent);
15630 after = after && jqLite(after);
15631 parent = parent || after.parent();
15632 domInsert(element, parent, after);
15633 return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
15638 * @name $animate#leave
15640 * @description Triggers an animation and then removes the element from the DOM.
15641 * When the function is called a promise is returned that will be resolved during the next
15642 * digest once the animation has completed.
15644 * @param {DOMElement} element the element which will be removed from the DOM
15645 * @param {object=} options an optional collection of options/styles that will be applied to the element.
15646 * The object can have the following properties:
15648 * - **addClass** - `{string}` - space-separated CSS classes to add to element
15649 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
15650 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
15651 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
15653 * @return {Promise} the animation callback promise
15655 leave: function(element, options) {
15656 return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
15663 * @name $animate#addClass
15666 * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
15667 * execution, the addClass operation will only be handled after the next digest and it will not trigger an
15668 * animation if element already contains the CSS class or if the class is removed at a later step.
15669 * Note that class-based animations are treated differently compared to structural animations
15670 * (like enter, move and leave) since the CSS classes may be added/removed at different points
15671 * depending if CSS or JavaScript animations are used.
15673 * @param {DOMElement} element the element which the CSS classes will be applied to
15674 * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
15675 * @param {object=} options an optional collection of options/styles that will be applied to the element.
15676 * The object can have the following properties:
15678 * - **addClass** - `{string}` - space-separated CSS classes to add to element
15679 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
15680 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
15681 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
15683 * @return {Promise} the animation callback promise
15685 addClass: function(element, className, options) {
15686 options = prepareAnimateOptions(options);
15687 options.addClass = mergeClasses(options.addclass, className);
15688 return $$animateQueue.push(element, 'addClass', options);
15693 * @name $animate#removeClass
15696 * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
15697 * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
15698 * animation if element does not contain the CSS class or if the class is added at a later step.
15699 * Note that class-based animations are treated differently compared to structural animations
15700 * (like enter, move and leave) since the CSS classes may be added/removed at different points
15701 * depending if CSS or JavaScript animations are used.
15703 * @param {DOMElement} element the element which the CSS classes will be applied to
15704 * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
15705 * @param {object=} options an optional collection of options/styles that will be applied to the element.
15706 * The object can have the following properties:
15708 * - **addClass** - `{string}` - space-separated CSS classes to add to element
15709 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
15710 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
15711 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
15713 * @return {Promise} the animation callback promise
15715 removeClass: function(element, className, options) {
15716 options = prepareAnimateOptions(options);
15717 options.removeClass = mergeClasses(options.removeClass, className);
15718 return $$animateQueue.push(element, 'removeClass', options);
15723 * @name $animate#setClass
15726 * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
15727 * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
15728 * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
15729 * passed. Note that class-based animations are treated differently compared to structural animations
15730 * (like enter, move and leave) since the CSS classes may be added/removed at different points
15731 * depending if CSS or JavaScript animations are used.
15733 * @param {DOMElement} element the element which the CSS classes will be applied to
15734 * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
15735 * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
15736 * @param {object=} options an optional collection of options/styles that will be applied to the element.
15737 * The object can have the following properties:
15739 * - **addClass** - `{string}` - space-separated CSS classes to add to element
15740 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
15741 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
15742 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
15744 * @return {Promise} the animation callback promise
15746 setClass: function(element, add, remove, options) {
15747 options = prepareAnimateOptions(options);
15748 options.addClass = mergeClasses(options.addClass, add);
15749 options.removeClass = mergeClasses(options.removeClass, remove);
15750 return $$animateQueue.push(element, 'setClass', options);
15755 * @name $animate#animate
15758 * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
15759 * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
15760 * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and
15761 * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
15762 * style in `to`, the style in `from` is applied immediately, and no animation is run.
15763 * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
15764 * method (or as part of the `options` parameter):
15767 * ngModule.animation('.my-inline-animation', function() {
15769 * animate : function(element, from, to, done, options) {
15777 * @param {DOMElement} element the element which the CSS styles will be applied to
15778 * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
15779 * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
15780 * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
15781 * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
15782 * (Note that if no animation is detected then this value will not be applied to the element.)
15783 * @param {object=} options an optional collection of options/styles that will be applied to the element.
15784 * The object can have the following properties:
15786 * - **addClass** - `{string}` - space-separated CSS classes to add to element
15787 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
15788 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
15789 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
15791 * @return {Promise} the animation callback promise
15793 animate: function(element, from, to, className, options) {
15794 options = prepareAnimateOptions(options);
15795 options.from = options.from ? extend(options.from, from) : from;
15796 options.to = options.to ? extend(options.to, to) : to;
15798 className = className || 'ng-inline-animate';
15799 options.tempClasses = mergeClasses(options.tempClasses, className);
15800 return $$animateQueue.push(element, 'animate', options);
15806 var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
15807 this.$get = ['$$rAF', function($$rAF) {
15808 var waitQueue = [];
15810 function waitForTick(fn) {
15811 waitQueue.push(fn);
15812 if (waitQueue.length > 1) return;
15814 for (var i = 0; i < waitQueue.length; i++) {
15821 return function() {
15822 var passed = false;
15823 waitForTick(function() {
15826 return function(callback) {
15830 waitForTick(callback);
15837 var $$AnimateRunnerFactoryProvider = /** @this */ function() {
15838 this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$document', '$timeout',
15839 function($q, $sniffer, $$animateAsyncRun, $document, $timeout) {
15841 var INITIAL_STATE = 0;
15842 var DONE_PENDING_STATE = 1;
15843 var DONE_COMPLETE_STATE = 2;
15845 AnimateRunner.chain = function(chain, callback) {
15850 if (index === chain.length) {
15855 chain[index](function(response) {
15856 if (response === false) {
15866 AnimateRunner.all = function(runners, callback) {
15869 forEach(runners, function(runner) {
15870 runner.done(onProgress);
15873 function onProgress(response) {
15874 status = status && response;
15875 if (++count === runners.length) {
15881 function AnimateRunner(host) {
15882 this.setHost(host);
15884 var rafTick = $$animateAsyncRun();
15885 var timeoutTick = function(fn) {
15886 $timeout(fn, 0, false);
15889 this._doneCallbacks = [];
15890 this._tick = function(fn) {
15891 var doc = $document[0];
15893 // the document may not be ready or attached
15894 // to the module for some internal tests
15895 if (doc && doc.hidden) {
15904 AnimateRunner.prototype = {
15905 setHost: function(host) {
15906 this.host = host || {};
15909 done: function(fn) {
15910 if (this._state === DONE_COMPLETE_STATE) {
15913 this._doneCallbacks.push(fn);
15919 getPromise: function() {
15920 if (!this.promise) {
15922 this.promise = $q(function(resolve, reject) {
15923 self.done(function(status) {
15924 if (status === false) {
15932 return this.promise;
15935 then: function(resolveHandler, rejectHandler) {
15936 return this.getPromise().then(resolveHandler, rejectHandler);
15939 'catch': function(handler) {
15940 return this.getPromise()['catch'](handler);
15943 'finally': function(handler) {
15944 return this.getPromise()['finally'](handler);
15947 pause: function() {
15948 if (this.host.pause) {
15953 resume: function() {
15954 if (this.host.resume) {
15955 this.host.resume();
15960 if (this.host.end) {
15963 this._resolve(true);
15966 cancel: function() {
15967 if (this.host.cancel) {
15968 this.host.cancel();
15970 this._resolve(false);
15973 complete: function(response) {
15975 if (self._state === INITIAL_STATE) {
15976 self._state = DONE_PENDING_STATE;
15977 self._tick(function() {
15978 self._resolve(response);
15983 _resolve: function(response) {
15984 if (this._state !== DONE_COMPLETE_STATE) {
15985 forEach(this._doneCallbacks, function(fn) {
15988 this._doneCallbacks.length = 0;
15989 this._state = DONE_COMPLETE_STATE;
15994 return AnimateRunner;
15998 /* exported $CoreAnimateCssProvider */
16002 * @name $animateCss
16007 * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
16008 * then the `$animateCss` service will actually perform animations.
16010 * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
16012 var $CoreAnimateCssProvider = function() {
16013 this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
16015 return function(element, initialOptions) {
16016 // all of the animation functions should create
16017 // a copy of the options data, however, if a
16018 // parent service has already created a copy then
16019 // we should stick to using that
16020 var options = initialOptions || {};
16021 if (!options.$$prepared) {
16022 options = copy(options);
16025 // there is no point in applying the styles since
16026 // there is no animation that goes on at all in
16027 // this version of $animateCss.
16028 if (options.cleanupStyles) {
16029 options.from = options.to = null;
16032 if (options.from) {
16033 element.css(options.from);
16034 options.from = null;
16037 var closed, runner = new $$AnimateRunner();
16045 applyAnimationContents();
16054 function applyAnimationContents() {
16055 if (options.addClass) {
16056 element.addClass(options.addClass);
16057 options.addClass = null;
16059 if (options.removeClass) {
16060 element.removeClass(options.removeClass);
16061 options.removeClass = null;
16064 element.css(options.to);
16072 /* global stripHash: true */
16075 * ! This is a private undocumented service !
16080 * This object has two goals:
16082 * - hide all the global state in the browser caused by the window object
16083 * - abstract away all the browser specific features and inconsistencies
16085 * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
16086 * service, which can be used for convenient testing of the application without the interaction with
16087 * the real browser apis.
16090 * @param {object} window The global window object.
16091 * @param {object} document jQuery wrapped document.
16092 * @param {object} $log window.console or an object with the same interface.
16093 * @param {object} $sniffer $sniffer service
16095 function Browser(window, document, $log, $sniffer) {
16097 location = window.location,
16098 history = window.history,
16099 setTimeout = window.setTimeout,
16100 clearTimeout = window.clearTimeout,
16101 pendingDeferIds = {};
16103 self.isMock = false;
16105 var outstandingRequestCount = 0;
16106 var outstandingRequestCallbacks = [];
16108 // TODO(vojta): remove this temporary api
16109 self.$$completeOutstandingRequest = completeOutstandingRequest;
16110 self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
16113 * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
16114 * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
16116 function completeOutstandingRequest(fn) {
16118 fn.apply(null, sliceArgs(arguments, 1));
16120 outstandingRequestCount--;
16121 if (outstandingRequestCount === 0) {
16122 while (outstandingRequestCallbacks.length) {
16124 outstandingRequestCallbacks.pop()();
16133 function getHash(url) {
16134 var index = url.indexOf('#');
16135 return index === -1 ? '' : url.substr(index);
16140 * Note: this method is used only by scenario runner
16141 * TODO(vojta): prefix this method with $$ ?
16142 * @param {function()} callback Function that will be called when no outstanding request
16144 self.notifyWhenNoOutstandingRequests = function(callback) {
16145 if (outstandingRequestCount === 0) {
16148 outstandingRequestCallbacks.push(callback);
16152 //////////////////////////////////////////////////////////////
16154 //////////////////////////////////////////////////////////////
16156 var cachedState, lastHistoryState,
16157 lastBrowserUrl = location.href,
16158 baseElement = document.find('base'),
16159 pendingLocation = null,
16160 getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
16162 return history.state;
16164 // MSIE can reportedly throw when there is no state (UNCONFIRMED).
16169 lastHistoryState = cachedState;
16172 * @name $browser#url
16176 * Without any argument, this method just returns current value of location.href.
16179 * With at least one argument, this method sets url to new value.
16180 * If html5 history api supported, pushState/replaceState is used, otherwise
16181 * location.href/location.replace is used.
16182 * Returns its own instance to allow chaining
16184 * NOTE: this api is intended for use only by the $location service. Please use the
16185 * {@link ng.$location $location service} to change url.
16187 * @param {string} url New url (when used as setter)
16188 * @param {boolean=} replace Should new url replace current history record?
16189 * @param {object=} state object to use with pushState/replaceState
16191 self.url = function(url, replace, state) {
16192 // In modern browsers `history.state` is `null` by default; treating it separately
16193 // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
16194 // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
16195 if (isUndefined(state)) {
16199 // Android Browser BFCache causes location, history reference to become stale.
16200 if (location !== window.location) location = window.location;
16201 if (history !== window.history) history = window.history;
16205 var sameState = lastHistoryState === state;
16207 // Don't change anything if previous and current URLs and states match. This also prevents
16208 // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
16209 // See https://github.com/angular/angular.js/commit/ffb2701
16210 if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
16213 var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
16214 lastBrowserUrl = url;
16215 lastHistoryState = state;
16216 // Don't use history API if only the hash changed
16217 // due to a bug in IE10/IE11 which leads
16218 // to not firing a `hashchange` nor `popstate` event
16219 // in some cases (see #9143).
16220 if ($sniffer.history && (!sameBase || !sameState)) {
16221 history[replace ? 'replaceState' : 'pushState'](state, '', url);
16223 // Do the assignment again so that those two variables are referentially identical.
16224 lastHistoryState = cachedState;
16227 pendingLocation = url;
16230 location.replace(url);
16231 } else if (!sameBase) {
16232 location.href = url;
16234 location.hash = getHash(url);
16236 if (location.href !== url) {
16237 pendingLocation = url;
16240 if (pendingLocation) {
16241 pendingLocation = url;
16246 // - pendingLocation is needed as browsers don't allow to read out
16247 // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
16248 // https://openradar.appspot.com/22186109).
16249 // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
16250 return pendingLocation || location.href.replace(/%27/g,'\'');
16255 * @name $browser#state
16258 * This method is a getter.
16260 * Return history.state or null if history.state is undefined.
16262 * @returns {object} state
16264 self.state = function() {
16265 return cachedState;
16268 var urlChangeListeners = [],
16269 urlChangeInit = false;
16271 function cacheStateAndFireUrlChange() {
16272 pendingLocation = null;
16277 // This variable should be used *only* inside the cacheState function.
16278 var lastCachedState = null;
16279 function cacheState() {
16280 // This should be the only place in $browser where `history.state` is read.
16281 cachedState = getCurrentState();
16282 cachedState = isUndefined(cachedState) ? null : cachedState;
16284 // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
16285 if (equals(cachedState, lastCachedState)) {
16286 cachedState = lastCachedState;
16288 lastCachedState = cachedState;
16291 function fireUrlChange() {
16292 if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
16296 lastBrowserUrl = self.url();
16297 lastHistoryState = cachedState;
16298 forEach(urlChangeListeners, function(listener) {
16299 listener(self.url(), cachedState);
16304 * @name $browser#onUrlChange
16307 * Register callback function that will be called, when url changes.
16309 * It's only called when the url is changed from outside of angular:
16310 * - user types different url into address bar
16311 * - user clicks on history (forward/back) button
16312 * - user clicks on a link
16314 * It's not called when url is changed by $browser.url() method
16316 * The listener gets called with new url as parameter.
16318 * NOTE: this api is intended for use only by the $location service. Please use the
16319 * {@link ng.$location $location service} to monitor url changes in angular apps.
16321 * @param {function(string)} listener Listener function to be called when url changes.
16322 * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
16324 self.onUrlChange = function(callback) {
16325 // TODO(vojta): refactor to use node's syntax for events
16326 if (!urlChangeInit) {
16327 // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
16328 // don't fire popstate when user change the address bar and don't fire hashchange when url
16329 // changed by push/replaceState
16331 // html5 history api - popstate event
16332 if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
16333 // hashchange event
16334 jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
16336 urlChangeInit = true;
16339 urlChangeListeners.push(callback);
16345 * Remove popstate and hashchange handler from window.
16347 * NOTE: this api is intended for use only by $rootScope.
16349 self.$$applicationDestroyed = function() {
16350 jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
16354 * Checks whether the url has changed outside of Angular.
16355 * Needs to be exported to be able to check for changes that have been done in sync,
16356 * as hashchange/popstate events fire in async.
16358 self.$$checkUrlChange = fireUrlChange;
16360 //////////////////////////////////////////////////////////////
16362 //////////////////////////////////////////////////////////////
16365 * @name $browser#baseHref
16368 * Returns current <base href>
16369 * (always relative - without domain)
16371 * @returns {string} The current base href
16373 self.baseHref = function() {
16374 var href = baseElement.attr('href');
16375 return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : '';
16379 * @name $browser#defer
16380 * @param {function()} fn A function, who's execution should be deferred.
16381 * @param {number=} [delay=0] of milliseconds to defer the function execution.
16382 * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
16385 * Executes a fn asynchronously via `setTimeout(fn, delay)`.
16387 * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
16388 * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
16389 * via `$browser.defer.flush()`.
16392 self.defer = function(fn, delay) {
16394 outstandingRequestCount++;
16395 timeoutId = setTimeout(function() {
16396 delete pendingDeferIds[timeoutId];
16397 completeOutstandingRequest(fn);
16399 pendingDeferIds[timeoutId] = true;
16405 * @name $browser#defer.cancel
16408 * Cancels a deferred task identified with `deferId`.
16410 * @param {*} deferId Token returned by the `$browser.defer` function.
16411 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
16414 self.defer.cancel = function(deferId) {
16415 if (pendingDeferIds[deferId]) {
16416 delete pendingDeferIds[deferId];
16417 clearTimeout(deferId);
16418 completeOutstandingRequest(noop);
16427 function $BrowserProvider() {
16428 this.$get = ['$window', '$log', '$sniffer', '$document',
16429 function($window, $log, $sniffer, $document) {
16430 return new Browser($window, $document, $log, $sniffer);
16436 * @name $cacheFactory
16440 * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
16445 * var cache = $cacheFactory('cacheId');
16446 * expect($cacheFactory.get('cacheId')).toBe(cache);
16447 * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
16449 * cache.put("key", "value");
16450 * cache.put("another key", "another value");
16452 * // We've specified no options on creation
16453 * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
16458 * @param {string} cacheId Name or id of the newly created cache.
16459 * @param {object=} options Options object that specifies the cache behavior. Properties:
16461 * - `{number=}` `capacity` — turns the cache into LRU cache.
16463 * @returns {object} Newly created cache object with the following set of methods:
16465 * - `{object}` `info()` — Returns id, size, and options of cache.
16466 * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
16468 * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
16469 * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
16470 * - `{void}` `removeAll()` — Removes all cached values.
16471 * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
16474 <example module="cacheExampleApp" name="cache-factory">
16475 <file name="index.html">
16476 <div ng-controller="CacheController">
16477 <input ng-model="newCacheKey" placeholder="Key">
16478 <input ng-model="newCacheValue" placeholder="Value">
16479 <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
16481 <p ng-if="keys.length">Cached Values</p>
16482 <div ng-repeat="key in keys">
16483 <span ng-bind="key"></span>
16485 <b ng-bind="cache.get(key)"></b>
16489 <div ng-repeat="(key, value) in cache.info()">
16490 <span ng-bind="key"></span>
16492 <b ng-bind="value"></b>
16496 <file name="script.js">
16497 angular.module('cacheExampleApp', []).
16498 controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
16500 $scope.cache = $cacheFactory('cacheId');
16501 $scope.put = function(key, value) {
16502 if (angular.isUndefined($scope.cache.get(key))) {
16503 $scope.keys.push(key);
16505 $scope.cache.put(key, angular.isUndefined(value) ? null : value);
16509 <file name="style.css">
16511 margin: 10px 0 3px;
16516 function $CacheFactoryProvider() {
16518 this.$get = function() {
16521 function cacheFactory(cacheId, options) {
16522 if (cacheId in caches) {
16523 throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
16527 stats = extend({}, options, {id: cacheId}),
16528 data = createMap(),
16529 capacity = (options && options.capacity) || Number.MAX_VALUE,
16530 lruHash = createMap(),
16536 * @name $cacheFactory.Cache
16539 * A cache object used to store and retrieve data, primarily used by
16540 * {@link $http $http} and the {@link ng.directive:script script} directive to cache
16541 * templates and other data.
16544 * angular.module('superCache')
16545 * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
16546 * return $cacheFactory('super-cache');
16553 * it('should behave like a cache', inject(function(superCache) {
16554 * superCache.put('key', 'value');
16555 * superCache.put('another key', 'another value');
16557 * expect(superCache.info()).toEqual({
16558 * id: 'super-cache',
16562 * superCache.remove('another key');
16563 * expect(superCache.get('another key')).toBeUndefined();
16565 * superCache.removeAll();
16566 * expect(superCache.info()).toEqual({
16567 * id: 'super-cache',
16573 return (caches[cacheId] = {
16577 * @name $cacheFactory.Cache#put
16581 * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
16582 * retrieved later, and incrementing the size of the cache if the key was not already
16583 * present in the cache. If behaving like an LRU cache, it will also remove stale
16584 * entries from the set.
16586 * It will not insert undefined values into the cache.
16588 * @param {string} key the key under which the cached data is stored.
16589 * @param {*} value the value to store alongside the key. If it is undefined, the key
16590 * will not be stored.
16591 * @returns {*} the value stored.
16593 put: function(key, value) {
16594 if (isUndefined(value)) return;
16595 if (capacity < Number.MAX_VALUE) {
16596 var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
16601 if (!(key in data)) size++;
16604 if (size > capacity) {
16605 this.remove(staleEnd.key);
16613 * @name $cacheFactory.Cache#get
16617 * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
16619 * @param {string} key the key of the data to be retrieved
16620 * @returns {*} the value stored.
16622 get: function(key) {
16623 if (capacity < Number.MAX_VALUE) {
16624 var lruEntry = lruHash[key];
16626 if (!lruEntry) return;
16637 * @name $cacheFactory.Cache#remove
16641 * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
16643 * @param {string} key the key of the entry to be removed
16645 remove: function(key) {
16646 if (capacity < Number.MAX_VALUE) {
16647 var lruEntry = lruHash[key];
16649 if (!lruEntry) return;
16651 if (lruEntry === freshEnd) freshEnd = lruEntry.p;
16652 if (lruEntry === staleEnd) staleEnd = lruEntry.n;
16653 link(lruEntry.n,lruEntry.p);
16655 delete lruHash[key];
16658 if (!(key in data)) return;
16667 * @name $cacheFactory.Cache#removeAll
16671 * Clears the cache object of any entries.
16673 removeAll: function() {
16674 data = createMap();
16676 lruHash = createMap();
16677 freshEnd = staleEnd = null;
16683 * @name $cacheFactory.Cache#destroy
16687 * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
16688 * removing it from the {@link $cacheFactory $cacheFactory} set.
16690 destroy: function() {
16694 delete caches[cacheId];
16700 * @name $cacheFactory.Cache#info
16704 * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
16706 * @returns {object} an object with the following properties:
16708 * <li>**id**: the id of the cache instance</li>
16709 * <li>**size**: the number of entries kept in the cache instance</li>
16710 * <li>**...**: any additional properties from the options object when creating the
16715 return extend({}, stats, {size: size});
16721 * makes the `entry` the freshEnd of the LRU linked list
16723 function refresh(entry) {
16724 if (entry !== freshEnd) {
16727 } else if (staleEnd === entry) {
16728 staleEnd = entry.n;
16731 link(entry.n, entry.p);
16732 link(entry, freshEnd);
16740 * bidirectionally links two entries of the LRU linked list
16742 function link(nextEntry, prevEntry) {
16743 if (nextEntry !== prevEntry) {
16744 if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
16745 if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
16753 * @name $cacheFactory#info
16756 * Get information about all the caches that have been created
16758 * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
16760 cacheFactory.info = function() {
16762 forEach(caches, function(cache, cacheId) {
16763 info[cacheId] = cache.info();
16771 * @name $cacheFactory#get
16774 * Get access to a cache object by the `cacheId` used when it was created.
16776 * @param {string} cacheId Name or id of a cache to access.
16777 * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
16779 cacheFactory.get = function(cacheId) {
16780 return caches[cacheId];
16784 return cacheFactory;
16790 * @name $templateCache
16794 * The first time a template is used, it is loaded in the template cache for quick retrieval. You
16795 * can load templates directly into the cache in a `script` tag, or by consuming the
16796 * `$templateCache` service directly.
16798 * Adding via the `script` tag:
16801 * <script type="text/ng-template" id="templateId.html">
16802 * <p>This is the content of the template</p>
16806 * **Note:** the `script` tag containing the template does not need to be included in the `head` of
16807 * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
16808 * element with ng-app attribute), otherwise the template will be ignored.
16810 * Adding via the `$templateCache` service:
16813 * var myApp = angular.module('myApp', []);
16814 * myApp.run(function($templateCache) {
16815 * $templateCache.put('templateId.html', 'This is the content of the template');
16819 * To retrieve the template later, simply use it in your component:
16821 * myApp.component('myComponent', {
16822 * templateUrl: 'templateId.html'
16826 * or get it via the `$templateCache` service:
16828 * $templateCache.get('templateId.html')
16831 * See {@link ng.$cacheFactory $cacheFactory}.
16834 function $TemplateCacheProvider() {
16835 this.$get = ['$cacheFactory', function($cacheFactory) {
16836 return $cacheFactory('templates');
16840 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
16841 * Any commits to this file should be reviewed with security in mind. *
16842 * Changes to this file can potentially create security vulnerabilities. *
16843 * An approval from 2 Core members with history of modifying *
16844 * this file is required. *
16846 * Does the change somehow allow for arbitrary javascript to be executed? *
16847 * Or allows for someone to change the prototype of built-in objects? *
16848 * Or gives undesired access to variables like document or window? *
16849 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
16851 /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
16853 * DOM-related variables:
16855 * - "node" - DOM Node
16856 * - "element" - DOM Element or Node
16857 * - "$node" or "$element" - jqLite-wrapped node or element
16860 * Compiler related stuff:
16862 * - "linkFn" - linking fn of a single directive
16863 * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
16864 * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
16865 * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
16875 * Compiles an HTML string or DOM into a template and produces a template function, which
16876 * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
16878 * The compilation is a process of walking the DOM tree and matching DOM elements to
16879 * {@link ng.$compileProvider#directive directives}.
16881 * <div class="alert alert-warning">
16882 * **Note:** This document is an in-depth reference of all directive options.
16883 * For a gentle introduction to directives with examples of common use cases,
16884 * see the {@link guide/directive directive guide}.
16887 * ## Comprehensive Directive API
16889 * There are many different options for a directive.
16891 * The difference resides in the return value of the factory function.
16892 * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
16893 * that defines the directive properties, or just the `postLink` function (all other properties will have
16894 * the default values).
16896 * <div class="alert alert-success">
16897 * **Best Practice:** It's recommended to use the "directive definition object" form.
16900 * Here's an example directive declared with a Directive Definition Object:
16903 * var myModule = angular.module(...);
16905 * myModule.directive('directiveName', function factory(injectables) {
16906 * var directiveDefinitionObject = {
16907 * {@link $compile#-priority- priority}: 0,
16908 * {@link $compile#-template- template}: '<div></div>', // or // function(tElement, tAttrs) { ... },
16910 * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... },
16911 * {@link $compile#-transclude- transclude}: false,
16912 * {@link $compile#-restrict- restrict}: 'A',
16913 * {@link $compile#-templatenamespace- templateNamespace}: 'html',
16914 * {@link $compile#-scope- scope}: false,
16915 * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
16916 * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier',
16917 * {@link $compile#-bindtocontroller- bindToController}: false,
16918 * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
16919 * {@link $compile#-multielement- multiElement}: false,
16920 * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) {
16922 * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
16923 * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
16926 * // return function postLink( ... ) { ... }
16929 * // {@link $compile#-link- link}: {
16930 * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
16931 * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
16934 * // {@link $compile#-link- link}: function postLink( ... ) { ... }
16936 * return directiveDefinitionObject;
16940 * <div class="alert alert-warning">
16941 * **Note:** Any unspecified options will use the default value. You can see the default values below.
16944 * Therefore the above can be simplified as:
16947 * var myModule = angular.module(...);
16949 * myModule.directive('directiveName', function factory(injectables) {
16950 * var directiveDefinitionObject = {
16951 * link: function postLink(scope, iElement, iAttrs) { ... }
16953 * return directiveDefinitionObject;
16955 * // return function postLink(scope, iElement, iAttrs) { ... }
16959 * ### Life-cycle hooks
16960 * Directive controllers can provide the following methods that are called by Angular at points in the life-cycle of the
16962 * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
16963 * had their bindings initialized (and before the pre & post linking functions for the directives on
16964 * this element). This is a good place to put initialization code for your controller.
16965 * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
16966 * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
16967 * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
16968 * component such as cloning the bound value to prevent accidental mutation of the outer value.
16969 * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
16970 * changes. Any actions that you wish to take in response to the changes that you detect must be
16971 * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
16972 * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
16973 * be detected by Angular's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
16974 * if detecting changes, you must store the previous value(s) for comparison to the current values.
16975 * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
16976 * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
16977 * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
16978 * components will have their `$onDestroy()` hook called before child components.
16979 * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
16980 * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
16981 * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
16982 * they are waiting for their template to load asynchronously and their own compilation and linking has been
16983 * suspended until that occurs.
16985 * #### Comparison with Angular 2 life-cycle hooks
16986 * Angular 2 also uses life-cycle hooks for its components. While the Angular 1 life-cycle hooks are similar there are
16987 * some differences that you should be aware of, especially when it comes to moving your code from Angular 1 to Angular 2:
16989 * * Angular 1 hooks are prefixed with `$`, such as `$onInit`. Angular 2 hooks are prefixed with `ng`, such as `ngOnInit`.
16990 * * Angular 1 hooks can be defined on the controller prototype or added to the controller inside its constructor.
16991 * In Angular 2 you can only define hooks on the prototype of the Component class.
16992 * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in Angular 1 than you would to
16993 * `ngDoCheck` in Angular 2
16994 * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
16995 * propagated throughout the application.
16996 * Angular 2 does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
16997 * error or do nothing depending upon the state of `enableProdMode()`.
16999 * #### Life-cycle hook examples
17001 * This example shows how you can check for mutations to a Date object even though the identity of the object
17004 * <example name="doCheckDateExample" module="do-check-module">
17005 * <file name="app.js">
17006 * angular.module('do-check-module', [])
17007 * .component('app', {
17009 * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' +
17010 * 'Date: {{ $ctrl.date }}' +
17011 * '<test date="$ctrl.date"></test>',
17012 * controller: function() {
17013 * this.date = new Date();
17014 * this.month = this.date.getMonth();
17015 * this.updateDate = function() {
17016 * this.date.setMonth(this.month);
17020 * .component('test', {
17021 * bindings: { date: '<' },
17023 * '<pre>{{ $ctrl.log | json }}</pre>',
17024 * controller: function() {
17025 * var previousValue;
17027 * this.$doCheck = function() {
17028 * var currentValue = this.date && this.date.valueOf();
17029 * if (previousValue !== currentValue) {
17030 * this.log.push('doCheck: date mutated: ' + this.date);
17031 * previousValue = currentValue;
17037 * <file name="index.html">
17042 * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
17043 * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
17044 * arrays or objects can have a negative impact on your application performance)
17046 * <example name="doCheckArrayExample" module="do-check-module">
17047 * <file name="index.html">
17048 * <div ng-init="items = []">
17049 * <button ng-click="items.push(items.length)">Add Item</button>
17050 * <button ng-click="items = []">Reset Items</button>
17051 * <pre>{{ items }}</pre>
17052 * <test items="items"></test>
17055 * <file name="app.js">
17056 * angular.module('do-check-module', [])
17057 * .component('test', {
17058 * bindings: { items: '<' },
17060 * '<pre>{{ $ctrl.log | json }}</pre>',
17061 * controller: function() {
17064 * this.$doCheck = function() {
17065 * if (this.items_ref !== this.items) {
17066 * this.log.push('doCheck: items changed');
17067 * this.items_ref = this.items;
17069 * if (!angular.equals(this.items_clone, this.items)) {
17070 * this.log.push('doCheck: items mutated');
17071 * this.items_clone = angular.copy(this.items);
17080 * ### Directive Definition Object
17082 * The directive definition object provides instructions to the {@link ng.$compile
17083 * compiler}. The attributes are:
17085 * #### `multiElement`
17086 * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between
17087 * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
17088 * together as the directive elements. It is recommended that this feature be used on directives
17089 * which are not strictly behavioral (such as {@link ngClick}), and which
17090 * do not manipulate or replace child nodes (such as {@link ngInclude}).
17093 * When there are multiple directives defined on a single DOM element, sometimes it
17094 * is necessary to specify the order in which the directives are applied. The `priority` is used
17095 * to sort the directives before their `compile` functions get called. Priority is defined as a
17096 * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
17097 * are also run in priority order, but post-link functions are run in reverse order. The order
17098 * of directives with the same priority is undefined. The default priority is `0`.
17101 * If set to true then the current `priority` will be the last set of directives
17102 * which will execute (any directives at the current priority will still execute
17103 * as the order of execution on same `priority` is undefined). Note that expressions
17104 * and other directives used in the directive's template will also be excluded from execution.
17107 * The scope property can be `false`, `true`, or an object:
17109 * * **`false` (default):** No scope will be created for the directive. The directive will use its
17112 * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
17113 * the directive's element. If multiple directives on the same element request a new scope,
17114 * only one new scope is created.
17116 * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
17117 * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
17118 * scope. This is useful when creating reusable components, which should not accidentally read or modify
17119 * data in the parent scope.
17121 * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
17122 * directive's element. These local properties are useful for aliasing values for templates. The keys in
17123 * the object hash map to the name of the property on the isolate scope; the values define how the property
17124 * is bound to the parent scope, via matching attributes on the directive's element:
17126 * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
17127 * always a string since DOM attributes are strings. If no `attr` name is specified then the
17128 * attribute name is assumed to be the same as the local name. Given `<my-component
17129 * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
17130 * the directive's scope property `localName` will reflect the interpolated value of `hello
17131 * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
17132 * scope. The `name` is read from the parent scope (not the directive's scope).
17134 * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
17135 * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
17136 * If no `attr` name is specified then the attribute name is assumed to be the same as the local
17137 * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
17138 * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
17139 * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
17140 * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
17141 * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
17142 * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
17143 * will be thrown upon discovering changes to the local value, since it will be impossible to sync
17144 * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
17145 * method is used for tracking changes, and the equality check is based on object identity.
17146 * However, if an object literal or an array literal is passed as the binding expression, the
17147 * equality check is done by value (using the {@link angular.equals} function). It's also possible
17148 * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
17149 * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
17151 * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
17152 * expression passed via the attribute `attr`. The expression is evaluated in the context of the
17153 * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
17154 * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
17156 * For example, given `<my-component my-attr="parentModel">` and directive definition of
17157 * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
17158 * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
17159 * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
17161 * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
17162 * sets the same value. That means if your bound value is an object, changes to its properties
17163 * in the isolated scope will be reflected in the parent scope (because both reference the same object).
17164 * 2. one-way binding watches changes to the **identity** of the parent value. That means the
17165 * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
17166 * to the value has changed. In most cases, this should not be of concern, but can be important
17167 * to know if you one-way bind to an object, and then replace that object in the isolated scope.
17168 * If you now change a property of the object in your parent scope, the change will not be
17169 * propagated to the isolated scope, because the identity of the object on the parent scope
17170 * has not changed. Instead you must assign a new object.
17172 * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
17173 * back to the parent. However, it does not make this completely impossible.
17175 * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
17176 * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
17177 * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
17178 * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
17179 * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
17180 * via an expression to the parent scope. This can be done by passing a map of local variable names
17181 * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
17182 * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
17184 * In general it's possible to apply more than one directive to one element, but there might be limitations
17185 * depending on the type of scope required by the directives. The following points will help explain these limitations.
17186 * For simplicity only two directives are taken into account, but it is also applicable for several directives:
17188 * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
17189 * * **child scope** + **no scope** => Both directives will share one single child scope
17190 * * **child scope** + **child scope** => Both directives will share one single child scope
17191 * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
17192 * its parent's scope
17193 * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
17194 * be applied to the same element.
17195 * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
17196 * cannot be applied to the same element.
17199 * #### `bindToController`
17200 * This property is used to bind scope properties directly to the controller. It can be either
17201 * `true` or an object hash with the same format as the `scope` property.
17203 * When an isolate scope is used for a directive (see above), `bindToController: true` will
17204 * allow a component to have its properties bound to the controller, rather than to scope.
17206 * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
17207 * properties. You can access these bindings once they have been initialized by providing a controller method called
17208 * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
17211 * <div class="alert alert-warning">
17212 * **Deprecation warning:** although bindings for non-ES6 class controllers are currently
17213 * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization
17214 * code that relies upon bindings inside a `$onInit` method on the controller, instead.
17217 * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
17218 * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
17219 * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
17220 * scope (useful for component directives).
17222 * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
17225 * #### `controller`
17226 * Controller constructor function. The controller is instantiated before the
17227 * pre-linking phase and can be accessed by other directives (see
17228 * `require` attribute). This allows the directives to communicate with each other and augment
17229 * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
17231 * * `$scope` - Current scope associated with the element
17232 * * `$element` - Current element
17233 * * `$attrs` - Current attributes object for the element
17234 * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
17235 * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
17236 * * `scope`: (optional) override the scope.
17237 * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
17238 * * `futureParentElement` (optional):
17239 * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
17240 * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
17241 * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
17242 * and when the `cloneLinkingFn` is passed,
17243 * as those elements need to created and cloned in a special way when they are defined outside their
17244 * usual containers (e.g. like `<svg>`).
17245 * * See also the `directive.templateNamespace` property.
17246 * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
17247 * then the default transclusion is provided.
17248 * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
17249 * `true` if the specified slot contains content (i.e. one or more DOM nodes).
17252 * Require another directive and inject its controller as the fourth argument to the linking function. The
17253 * `require` property can be a string, an array or an object:
17254 * * a **string** containing the name of the directive to pass to the linking function
17255 * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
17256 * linking function will be an array of controllers in the same order as the names in the `require` property
17257 * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
17258 * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
17261 * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
17262 * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
17263 * have been constructed but before `$onInit` is called.
17264 * If the name of the required controller is the same as the local name (the key), the name can be
17265 * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.
17266 * See the {@link $compileProvider#component} helper for an example of how this can be used.
17267 * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
17268 * raised (unless no link function is specified and the required controllers are not being bound to the directive
17269 * controller, in which case error checking is skipped). The name can be prefixed with:
17271 * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
17272 * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
17273 * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
17274 * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
17275 * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
17276 * `null` to the `link` fn if not found.
17277 * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
17278 * `null` to the `link` fn if not found.
17281 * #### `controllerAs`
17282 * Identifier name for a reference to the controller in the directive's scope.
17283 * This allows the controller to be referenced from the directive template. This is especially
17284 * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
17285 * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
17286 * `controllerAs` reference might overwrite a property that already exists on the parent scope.
17290 * String of subset of `EACM` which restricts the directive to a specific directive
17291 * declaration style. If omitted, the defaults (elements and attributes) are used.
17293 * * `E` - Element name (default): `<my-directive></my-directive>`
17294 * * `A` - Attribute (default): `<div my-directive="exp"></div>`
17295 * * `C` - Class: `<div class="my-directive: exp;"></div>`
17296 * * `M` - Comment: `<!-- directive: my-directive exp -->`
17299 * #### `templateNamespace`
17300 * String representing the document type used by the markup in the template.
17301 * AngularJS needs this information as those elements need to be created and cloned
17302 * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
17304 * * `html` - All root nodes in the template are HTML. Root nodes may also be
17305 * top-level elements such as `<svg>` or `<math>`.
17306 * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
17307 * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
17309 * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
17312 * HTML markup that may:
17313 * * Replace the contents of the directive's element (default).
17314 * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
17315 * * Wrap the contents of the directive's element (if `transclude` is true).
17319 * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
17320 * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
17321 * function api below) and returns a string value.
17324 * #### `templateUrl`
17325 * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
17327 * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
17328 * for later when the template has been resolved. In the meantime it will continue to compile and link
17329 * sibling and parent elements as though this element had not contained any directives.
17331 * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
17332 * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
17333 * case when only one deeply nested directive has `templateUrl`.
17335 * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
17337 * You can specify `templateUrl` as a string representing the URL or as a function which takes two
17338 * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
17339 * a string value representing the url. In either case, the template URL is passed through {@link
17340 * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
17343 * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
17344 * specify what the template should replace. Defaults to `false`.
17346 * * `true` - the template will replace the directive's element.
17347 * * `false` - the template will replace the contents of the directive's element.
17349 * The replacement process migrates all of the attributes / classes from the old element to the new
17350 * one. See the {@link guide/directive#template-expanding-directive
17351 * Directives Guide} for an example.
17353 * There are very few scenarios where element replacement is required for the application function,
17354 * the main one being reusable custom components that are used within SVG contexts
17355 * (because SVG doesn't work with custom elements in the DOM tree).
17357 * #### `transclude`
17358 * Extract the contents of the element where the directive appears and make it available to the directive.
17359 * The contents are compiled and provided to the directive as a **transclusion function**. See the
17360 * {@link $compile#transclusion Transclusion} section below.
17366 * function compile(tElement, tAttrs, transclude) { ... }
17369 * The compile function deals with transforming the template DOM. Since most directives do not do
17370 * template transformation, it is not used often. The compile function takes the following arguments:
17372 * * `tElement` - template element - The element where the directive has been declared. It is
17373 * safe to do template transformation on the element and child elements only.
17375 * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
17376 * between all directive compile functions.
17378 * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
17380 * <div class="alert alert-warning">
17381 * **Note:** The template instance and the link instance may be different objects if the template has
17382 * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
17383 * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
17384 * should be done in a linking function rather than in a compile function.
17387 * <div class="alert alert-warning">
17388 * **Note:** The compile function cannot handle directives that recursively use themselves in their
17389 * own templates or compile functions. Compiling these directives results in an infinite loop and
17390 * stack overflow errors.
17392 * This can be avoided by manually using $compile in the postLink function to imperatively compile
17393 * a directive's template instead of relying on automatic template compilation via `template` or
17394 * `templateUrl` declaration or manual compilation inside the compile function.
17397 * <div class="alert alert-danger">
17398 * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
17399 * e.g. does not know about the right outer scope. Please use the transclude function that is passed
17400 * to the link function instead.
17403 * A compile function can have a return value which can be either a function or an object.
17405 * * returning a (post-link) function - is equivalent to registering the linking function via the
17406 * `link` property of the config object when the compile function is empty.
17408 * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
17409 * control when a linking function should be called during the linking phase. See info about
17410 * pre-linking and post-linking functions below.
17414 * This property is used only if the `compile` property is not defined.
17417 * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
17420 * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
17421 * executed after the template has been cloned. This is where most of the directive logic will be
17424 * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
17425 * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
17427 * * `iElement` - instance element - The element where the directive is to be used. It is safe to
17428 * manipulate the children of the element only in `postLink` function since the children have
17429 * already been linked.
17431 * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
17432 * between all directive linking functions.
17434 * * `controller` - the directive's required controller instance(s) - Instances are shared
17435 * among all directives, which allows the directives to use the controllers as a communication
17436 * channel. The exact value depends on the directive's `require` property:
17437 * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
17438 * * `string`: the controller instance
17439 * * `array`: array of controller instances
17441 * If a required controller cannot be found, and it is optional, the instance is `null`,
17442 * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
17444 * Note that you can also require the directive's own controller - it will be made available like
17445 * any other controller.
17447 * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
17448 * This is the same as the `$transclude` parameter of directive controllers,
17449 * see {@link ng.$compile#-controller- the controller section for details}.
17450 * `function([scope], cloneLinkingFn, futureParentElement)`.
17452 * #### Pre-linking function
17454 * Executed before the child elements are linked. Not safe to do DOM transformation since the
17455 * compiler linking function will fail to locate the correct elements for linking.
17457 * #### Post-linking function
17459 * Executed after the child elements are linked.
17461 * Note that child elements that contain `templateUrl` directives will not have been compiled
17462 * and linked since they are waiting for their template to load asynchronously and their own
17463 * compilation and linking has been suspended until that occurs.
17465 * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
17466 * for their async templates to be resolved.
17471 * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
17472 * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
17473 * scope from where they were taken.
17475 * Transclusion is used (often with {@link ngTransclude}) to insert the
17476 * original contents of a directive's element into a specified place in the template of the directive.
17477 * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
17478 * content has access to the properties on the scope from which it was taken, even if the directive
17479 * has isolated scope.
17480 * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
17482 * This makes it possible for the widget to have private state for its template, while the transcluded
17483 * content has access to its originating scope.
17485 * <div class="alert alert-warning">
17486 * **Note:** When testing an element transclude directive you must not place the directive at the root of the
17487 * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
17488 * Testing Transclusion Directives}.
17491 * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
17492 * directive's element, the entire element or multiple parts of the element contents:
17494 * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
17495 * * `'element'` - transclude the whole of the directive's element including any directives on this
17496 * element that defined at a lower priority than this directive. When used, the `template`
17497 * property is ignored.
17498 * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
17500 * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
17502 * This object is a map where the keys are the name of the slot to fill and the value is an element selector
17503 * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
17504 * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
17506 * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
17508 * If the element selector is prefixed with a `?` then that slot is optional.
17510 * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
17511 * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
17513 * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
17514 * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
17515 * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
17516 * injectable into the directive's controller.
17519 * #### Transclusion Functions
17521 * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
17522 * function** to the directive's `link` function and `controller`. This transclusion function is a special
17523 * **linking function** that will return the compiled contents linked to a new transclusion scope.
17525 * <div class="alert alert-info">
17526 * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
17527 * ngTransclude will deal with it for us.
17530 * If you want to manually control the insertion and removal of the transcluded content in your directive
17531 * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
17532 * object that contains the compiled DOM, which is linked to the correct transclusion scope.
17534 * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
17535 * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
17536 * content and the `scope` is the newly created transclusion scope, which the clone will be linked to.
17538 * <div class="alert alert-info">
17539 * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
17540 * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
17543 * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
17544 * attach function**:
17547 * var transcludedContent, transclusionScope;
17549 * $transclude(function(clone, scope) {
17550 * element.append(clone);
17551 * transcludedContent = clone;
17552 * transclusionScope = scope;
17556 * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
17557 * associated transclusion scope:
17560 * transcludedContent.remove();
17561 * transclusionScope.$destroy();
17564 * <div class="alert alert-info">
17565 * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
17566 * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
17567 * then you are also responsible for calling `$destroy` on the transclusion scope.
17570 * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
17571 * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
17572 * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
17575 * #### Transclusion Scopes
17577 * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
17578 * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
17579 * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
17582 * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
17588 * <div transclusion>
17594 * The `$parent` scope hierarchy will look like this:
17602 * but the scopes will inherit prototypically from different scopes to their `$parent`.
17613 * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
17614 * `link()` or `compile()` functions. It has a variety of uses.
17616 * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
17617 * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
17618 * to the attributes.
17620 * * *Directive inter-communication:* All directives share the same instance of the attributes
17621 * object which allows the directives to use the attributes object as inter directive
17624 * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
17625 * allowing other directives to read the interpolated value.
17627 * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
17628 * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
17629 * the only way to easily get the actual value because during the linking phase the interpolation
17630 * hasn't been evaluated yet and so the value is at this time set to `undefined`.
17633 * function linkingFn(scope, elm, attrs, ctrl) {
17634 * // get the attribute value
17635 * console.log(attrs.ngModel);
17637 * // change the attribute
17638 * attrs.$set('ngModel', 'new value');
17640 * // observe changes to interpolated attribute
17641 * attrs.$observe('ngModel', function(value) {
17642 * console.log('ngModel has changed value to ' + value);
17649 * <div class="alert alert-warning">
17650 * **Note**: Typically directives are registered with `module.directive`. The example below is
17651 * to illustrate how `$compile` works.
17654 <example module="compileExample" name="compile">
17655 <file name="index.html">
17657 angular.module('compileExample', [], function($compileProvider) {
17658 // configure new 'compile' directive by passing a directive
17659 // factory function. The factory function injects the '$compile'
17660 $compileProvider.directive('compile', function($compile) {
17661 // directive factory creates a link function
17662 return function(scope, element, attrs) {
17665 // watch the 'compile' expression for changes
17666 return scope.$eval(attrs.compile);
17669 // when the 'compile' expression changes
17670 // assign it into the current DOM
17671 element.html(value);
17673 // compile the new DOM and link it to the current
17675 // NOTE: we only compile .childNodes so that
17676 // we don't get into infinite loop compiling ourselves
17677 $compile(element.contents())(scope);
17683 .controller('GreeterController', ['$scope', function($scope) {
17684 $scope.name = 'Angular';
17685 $scope.html = 'Hello {{name}}';
17688 <div ng-controller="GreeterController">
17689 <input ng-model="name"> <br/>
17690 <textarea ng-model="html"></textarea> <br/>
17691 <div compile="html"></div>
17694 <file name="protractor.js" type="protractor">
17695 it('should auto compile', function() {
17696 var textarea = $('textarea');
17697 var output = $('div[compile]');
17698 // The initial state reads 'Hello Angular'.
17699 expect(output.getText()).toBe('Hello Angular');
17701 textarea.sendKeys('{{name}}!');
17702 expect(output.getText()).toBe('Angular!');
17709 * @param {string|DOMElement} element Element or HTML string to compile into a template function.
17710 * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
17712 * <div class="alert alert-danger">
17713 * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
17714 * e.g. will not use the right outer scope. Please pass the transclude function as a
17715 * `parentBoundTranscludeFn` to the link function instead.
17718 * @param {number} maxPriority only apply directives lower than given priority (Only effects the
17719 * root element(s), not their children)
17720 * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
17721 * (a DOM element/tree) to a scope. Where:
17723 * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
17724 * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
17725 * `template` and call the `cloneAttachFn` function allowing the caller to attach the
17726 * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
17727 * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
17729 * * `clonedElement` - is a clone of the original `element` passed into the compiler.
17730 * * `scope` - is the current scope with which the linking function is working with.
17732 * * `options` - An optional object hash with linking options. If `options` is provided, then the following
17733 * keys may be used to control linking behavior:
17735 * * `parentBoundTranscludeFn` - the transclude function made available to
17736 * directives; if given, it will be passed through to the link functions of
17737 * directives found in `element` during compilation.
17738 * * `transcludeControllers` - an object hash with keys that map controller names
17739 * to a hash with the key `instance`, which maps to the controller instance;
17740 * if given, it will make the controllers available to directives on the compileNode:
17744 * instance: parentControllerInstance
17748 * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
17749 * the cloned elements; only needed for transcludes that are allowed to contain non html
17750 * elements (e.g. SVG elements). See also the directive.controller property.
17752 * Calling the linking function returns the element of the template. It is either the original
17753 * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
17755 * After linking the view is not updated until after a call to $digest which typically is done by
17756 * Angular automatically.
17758 * If you need access to the bound view, there are two ways to do it:
17760 * - If you are not asking the linking function to clone the template, create the DOM element(s)
17761 * before you send them to the compiler and keep this reference around.
17763 * var element = $compile('<p>{{total}}</p>')(scope);
17766 * - if on the other hand, you need the element to be cloned, the view reference from the original
17767 * example would not point to the clone, but rather to the original template that was cloned. In
17768 * this case, you can access the clone via the cloneAttachFn:
17770 * var templateElement = angular.element('<p>{{total}}</p>'),
17773 * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
17774 * //attach the clone to DOM document at the right place
17777 * //now we have reference to the cloned DOM via `clonedElement`
17781 * For information on how the compiler works, see the
17782 * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
17786 * ### Double Compilation
17788 Double compilation occurs when an already compiled part of the DOM gets
17789 compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues,
17790 and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it
17791 section on double compilation} for an in-depth explanation and ways to avoid it.
17795 var $compileMinErr = minErr('$compile');
17797 function UNINITIALIZED_VALUE() {}
17798 var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
17802 * @name $compileProvider
17806 $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
17808 function $CompileProvider($provide, $$sanitizeUriProvider) {
17809 var hasDirectives = {},
17810 Suffix = 'Directive',
17811 COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/,
17812 CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/,
17813 ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
17814 REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
17816 // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
17817 // The assumption is that future DOM event attribute names will begin with
17818 // 'on' and be composed of only English letters.
17819 var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
17820 var bindingCache = createMap();
17822 function parseIsolateBindings(scope, directiveName, isController) {
17823 var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*([\w$]*)\s*$/;
17825 var bindings = createMap();
17827 forEach(scope, function(definition, scopeName) {
17828 if (definition in bindingCache) {
17829 bindings[scopeName] = bindingCache[definition];
17832 var match = definition.match(LOCAL_REGEXP);
17835 throw $compileMinErr('iscp',
17836 'Invalid {3} for directive \'{0}\'.' +
17837 ' Definition: {... {1}: \'{2}\' ...}',
17838 directiveName, scopeName, definition,
17839 (isController ? 'controller bindings definition' :
17840 'isolate scope definition'));
17843 bindings[scopeName] = {
17845 collection: match[2] === '*',
17846 optional: match[3] === '?',
17847 attrName: match[4] || scopeName
17850 bindingCache[definition] = bindings[scopeName];
17857 function parseDirectiveBindings(directive, directiveName) {
17859 isolateScope: null,
17860 bindToController: null
17862 if (isObject(directive.scope)) {
17863 if (directive.bindToController === true) {
17864 bindings.bindToController = parseIsolateBindings(directive.scope,
17865 directiveName, true);
17866 bindings.isolateScope = {};
17868 bindings.isolateScope = parseIsolateBindings(directive.scope,
17869 directiveName, false);
17872 if (isObject(directive.bindToController)) {
17873 bindings.bindToController =
17874 parseIsolateBindings(directive.bindToController, directiveName, true);
17876 if (bindings.bindToController && !directive.controller) {
17877 // There is no controller
17878 throw $compileMinErr('noctrl',
17879 'Cannot bind to controller without directive \'{0}\'s controller.',
17885 function assertValidDirectiveName(name) {
17886 var letter = name.charAt(0);
17887 if (!letter || letter !== lowercase(letter)) {
17888 throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name);
17890 if (name !== name.trim()) {
17891 throw $compileMinErr('baddir',
17892 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces',
17897 function getDirectiveRequire(directive) {
17898 var require = directive.require || (directive.controller && directive.name);
17900 if (!isArray(require) && isObject(require)) {
17901 forEach(require, function(value, key) {
17902 var match = value.match(REQUIRE_PREFIX_REGEXP);
17903 var name = value.substring(match[0].length);
17904 if (!name) require[key] = match[0] + key;
17911 function getDirectiveRestrict(restrict, name) {
17912 if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) {
17913 throw $compileMinErr('badrestrict',
17914 'Restrict property \'{0}\' of directive \'{1}\' is invalid',
17919 return restrict || 'EA';
17924 * @name $compileProvider#directive
17928 * Register a new directive with the compiler.
17930 * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
17931 * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
17932 * names and the values are the factories.
17933 * @param {Function|Array} directiveFactory An injectable directive factory function. See the
17934 * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
17935 * @returns {ng.$compileProvider} Self for chaining.
17937 this.directive = function registerDirective(name, directiveFactory) {
17938 assertArg(name, 'name');
17939 assertNotHasOwnProperty(name, 'directive');
17940 if (isString(name)) {
17941 assertValidDirectiveName(name);
17942 assertArg(directiveFactory, 'directiveFactory');
17943 if (!hasDirectives.hasOwnProperty(name)) {
17944 hasDirectives[name] = [];
17945 $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
17946 function($injector, $exceptionHandler) {
17947 var directives = [];
17948 forEach(hasDirectives[name], function(directiveFactory, index) {
17950 var directive = $injector.invoke(directiveFactory);
17951 if (isFunction(directive)) {
17952 directive = { compile: valueFn(directive) };
17953 } else if (!directive.compile && directive.link) {
17954 directive.compile = valueFn(directive.link);
17956 directive.priority = directive.priority || 0;
17957 directive.index = index;
17958 directive.name = directive.name || name;
17959 directive.require = getDirectiveRequire(directive);
17960 directive.restrict = getDirectiveRestrict(directive.restrict, name);
17961 directive.$$moduleName = directiveFactory.$$moduleName;
17962 directives.push(directive);
17964 $exceptionHandler(e);
17970 hasDirectives[name].push(directiveFactory);
17972 forEach(name, reverseParams(registerDirective));
17979 * @name $compileProvider#component
17981 * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
17982 * @param {Object} options Component definition object (a simplified
17983 * {@link ng.$compile#directive-definition-object directive definition object}),
17984 * with the following properties (all optional):
17986 * - `controller` – `{(string|function()=}` – controller constructor function that should be
17987 * associated with newly created scope or the name of a {@link ng.$compile#-controller-
17988 * registered controller} if passed as a string. An empty `noop` function by default.
17989 * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
17990 * If present, the controller will be published to scope under the `controllerAs` name.
17991 * If not present, this will default to be `$ctrl`.
17992 * - `template` – `{string=|function()=}` – html template as a string or a function that
17993 * returns an html template as a string which should be used as the contents of this component.
17994 * Empty string by default.
17996 * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
17997 * the following locals:
17999 * - `$element` - Current element
18000 * - `$attrs` - Current attributes object for the element
18002 * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
18003 * template that should be used as the contents of this component.
18005 * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
18006 * the following locals:
18008 * - `$element` - Current element
18009 * - `$attrs` - Current attributes object for the element
18011 * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
18012 * Component properties are always bound to the component controller and not to the scope.
18013 * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
18014 * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
18015 * Disabled by default.
18016 * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to
18017 * this component's controller. The object keys specify the property names under which the required
18018 * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.
18019 * - `$...` – additional properties to attach to the directive factory function and the controller
18020 * constructor function. (This is used by the component router to annotate)
18022 * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
18024 * Register a **component definition** with the compiler. This is a shorthand for registering a special
18025 * type of directive, which represents a self-contained UI component in your application. Such components
18026 * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
18028 * Component definitions are very simple and do not require as much configuration as defining general
18029 * directives. Component definitions usually consist only of a template and a controller backing it.
18031 * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
18032 * `bindToController`. They always have **isolate scope** and are restricted to elements.
18034 * Here are a few examples of how you would usually define components:
18037 * var myMod = angular.module(...);
18038 * myMod.component('myComp', {
18039 * template: '<div>My name is {{$ctrl.name}}</div>',
18040 * controller: function() {
18041 * this.name = 'shahar';
18045 * myMod.component('myComp', {
18046 * template: '<div>My name is {{$ctrl.name}}</div>',
18047 * bindings: {name: '@'}
18050 * myMod.component('myComp', {
18051 * templateUrl: 'views/my-comp.html',
18052 * controller: 'MyCtrl',
18053 * controllerAs: 'ctrl',
18054 * bindings: {name: '@'}
18058 * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
18061 * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
18063 this.component = function registerComponent(name, options) {
18064 var controller = options.controller || function() {};
18066 function factory($injector) {
18067 function makeInjectable(fn) {
18068 if (isFunction(fn) || isArray(fn)) {
18069 return /** @this */ function(tElement, tAttrs) {
18070 return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
18077 var template = (!options.template && !options.templateUrl ? '' : options.template);
18079 controller: controller,
18080 controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
18081 template: makeInjectable(template),
18082 templateUrl: makeInjectable(options.templateUrl),
18083 transclude: options.transclude,
18085 bindToController: options.bindings || {},
18087 require: options.require
18090 // Copy annotations (starting with $) over to the DDO
18091 forEach(options, function(val, key) {
18092 if (key.charAt(0) === '$') ddo[key] = val;
18098 // TODO(pete) remove the following `forEach` before we release 1.6.0
18099 // The component-router@0.2.0 looks for the annotations on the controller constructor
18100 // Nothing in Angular looks for annotations on the factory function but we can't remove
18101 // it from 1.5.x yet.
18103 // Copy any annotation properties (starting with $) over to the factory and controller constructor functions
18104 // These could be used by libraries such as the new component router
18105 forEach(options, function(val, key) {
18106 if (key.charAt(0) === '$') {
18107 factory[key] = val;
18108 // Don't try to copy over annotations to named controller
18109 if (isFunction(controller)) controller[key] = val;
18113 factory.$inject = ['$injector'];
18115 return this.directive(name, factory);
18121 * @name $compileProvider#aHrefSanitizationWhitelist
18125 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
18126 * urls during a[href] sanitization.
18128 * The sanitization is a security measure aimed at preventing XSS attacks via html links.
18130 * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
18131 * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
18132 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
18133 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
18135 * @param {RegExp=} regexp New regexp to whitelist urls with.
18136 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
18137 * chaining otherwise.
18139 this.aHrefSanitizationWhitelist = function(regexp) {
18140 if (isDefined(regexp)) {
18141 $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
18144 return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
18151 * @name $compileProvider#imgSrcSanitizationWhitelist
18155 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
18156 * urls during img[src] sanitization.
18158 * The sanitization is a security measure aimed at prevent XSS attacks via html links.
18160 * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
18161 * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
18162 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
18163 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
18165 * @param {RegExp=} regexp New regexp to whitelist urls with.
18166 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
18167 * chaining otherwise.
18169 this.imgSrcSanitizationWhitelist = function(regexp) {
18170 if (isDefined(regexp)) {
18171 $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
18174 return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
18180 * @name $compileProvider#debugInfoEnabled
18182 * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
18183 * current debugInfoEnabled state
18184 * @returns {*} current value if used as getter or itself (chaining) if used as setter
18189 * Call this method to enable/disable various debug runtime information in the compiler such as adding
18190 * binding information and a reference to the current scope on to DOM elements.
18191 * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
18192 * * `ng-binding` CSS class
18193 * * `$binding` data property containing an array of the binding expressions
18195 * You may want to disable this in production for a significant performance boost. See
18196 * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
18198 * The default value is true.
18200 var debugInfoEnabled = true;
18201 this.debugInfoEnabled = function(enabled) {
18202 if (isDefined(enabled)) {
18203 debugInfoEnabled = enabled;
18206 return debugInfoEnabled;
18211 * @name $compileProvider#preAssignBindingsEnabled
18213 * @param {boolean=} enabled update the preAssignBindingsEnabled state if provided, otherwise just return the
18214 * current preAssignBindingsEnabled state
18215 * @returns {*} current value if used as getter or itself (chaining) if used as setter
18220 * Call this method to enable/disable whether directive controllers are assigned bindings before
18221 * calling the controller's constructor.
18222 * If enabled (true), the compiler assigns the value of each of the bindings to the
18223 * properties of the controller object before the constructor of this object is called.
18225 * If disabled (false), the compiler calls the constructor first before assigning bindings.
18227 * The default value is true in Angular 1.5.x but will switch to false in Angular 1.6.x.
18229 var preAssignBindingsEnabled = true;
18230 this.preAssignBindingsEnabled = function(enabled) {
18231 if (isDefined(enabled)) {
18232 preAssignBindingsEnabled = enabled;
18235 return preAssignBindingsEnabled;
18242 * @name $compileProvider#onChangesTtl
18245 * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
18246 * assuming that the model is unstable.
18248 * The current default is 10 iterations.
18250 * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
18251 * in several iterations of calls to these hooks. However if an application needs more than the default 10
18252 * iterations to stabilize then you should investigate what is causing the model to continuously change during
18253 * the `$onChanges` hook execution.
18255 * Increasing the TTL could have performance implications, so you should not change it without proper justification.
18257 * @param {number} limit The number of `$onChanges` hook iterations.
18258 * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
18260 this.onChangesTtl = function(value) {
18261 if (arguments.length) {
18268 var commentDirectivesEnabledConfig = true;
18271 * @name $compileProvider#commentDirectivesEnabled
18274 * It indicates to the compiler
18275 * whether or not directives on comments should be compiled.
18276 * Defaults to `true`.
18278 * Calling this function with false disables the compilation of directives
18279 * on comments for the whole application.
18280 * This results in a compilation performance gain,
18281 * as the compiler doesn't have to check comments when looking for directives.
18282 * This should however only be used if you are sure that no comment directives are used in
18283 * the application (including any 3rd party directives).
18285 * @param {boolean} enabled `false` if the compiler may ignore directives on comments
18286 * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
18288 this.commentDirectivesEnabled = function(value) {
18289 if (arguments.length) {
18290 commentDirectivesEnabledConfig = value;
18293 return commentDirectivesEnabledConfig;
18297 var cssClassDirectivesEnabledConfig = true;
18300 * @name $compileProvider#cssClassDirectivesEnabled
18303 * It indicates to the compiler
18304 * whether or not directives on element classes should be compiled.
18305 * Defaults to `true`.
18307 * Calling this function with false disables the compilation of directives
18308 * on element classes for the whole application.
18309 * This results in a compilation performance gain,
18310 * as the compiler doesn't have to check element classes when looking for directives.
18311 * This should however only be used if you are sure that no class directives are used in
18312 * the application (including any 3rd party directives).
18314 * @param {boolean} enabled `false` if the compiler may ignore directives on element classes
18315 * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
18317 this.cssClassDirectivesEnabled = function(value) {
18318 if (arguments.length) {
18319 cssClassDirectivesEnabledConfig = value;
18322 return cssClassDirectivesEnabledConfig;
18326 '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
18327 '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
18328 function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
18329 $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
18331 var SIMPLE_ATTR_NAME = /^\w/;
18332 var specialAttrHolder = window.document.createElement('div');
18335 var commentDirectivesEnabled = commentDirectivesEnabledConfig;
18336 var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;
18339 var onChangesTtl = TTL;
18340 // The onChanges hooks should all be run together in a single digest
18341 // When changes occur, the call to trigger their hooks will be added to this queue
18342 var onChangesQueue;
18344 // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
18345 function flushOnChangesQueue() {
18347 if (!(--onChangesTtl)) {
18348 // We have hit the TTL limit so reset everything
18349 onChangesQueue = undefined;
18350 throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
18352 // We must run this hook in an apply since the $$postDigest runs outside apply
18353 $rootScope.$apply(function() {
18355 for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
18357 onChangesQueue[i]();
18362 // Reset the queue to trigger a new schedule next time there is a change
18363 onChangesQueue = undefined;
18364 if (errors.length) {
18374 function Attributes(element, attributesToCopy) {
18375 if (attributesToCopy) {
18376 var keys = Object.keys(attributesToCopy);
18379 for (i = 0, l = keys.length; i < l; i++) {
18381 this[key] = attributesToCopy[key];
18387 this.$$element = element;
18390 Attributes.prototype = {
18393 * @name $compile.directive.Attributes#$normalize
18397 * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
18398 * `data-`) to its normalized, camelCase form.
18400 * Also there is special case for Moz prefix starting with upper case letter.
18402 * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
18404 * @param {string} name Name to normalize
18406 $normalize: directiveNormalize,
18411 * @name $compile.directive.Attributes#$addClass
18415 * Adds the CSS class value specified by the classVal parameter to the element. If animations
18416 * are enabled then an animation will be triggered for the class addition.
18418 * @param {string} classVal The className value that will be added to the element
18420 $addClass: function(classVal) {
18421 if (classVal && classVal.length > 0) {
18422 $animate.addClass(this.$$element, classVal);
18428 * @name $compile.directive.Attributes#$removeClass
18432 * Removes the CSS class value specified by the classVal parameter from the element. If
18433 * animations are enabled then an animation will be triggered for the class removal.
18435 * @param {string} classVal The className value that will be removed from the element
18437 $removeClass: function(classVal) {
18438 if (classVal && classVal.length > 0) {
18439 $animate.removeClass(this.$$element, classVal);
18445 * @name $compile.directive.Attributes#$updateClass
18449 * Adds and removes the appropriate CSS class values to the element based on the difference
18450 * between the new and old CSS class values (specified as newClasses and oldClasses).
18452 * @param {string} newClasses The current CSS className value
18453 * @param {string} oldClasses The former CSS className value
18455 $updateClass: function(newClasses, oldClasses) {
18456 var toAdd = tokenDifference(newClasses, oldClasses);
18457 if (toAdd && toAdd.length) {
18458 $animate.addClass(this.$$element, toAdd);
18461 var toRemove = tokenDifference(oldClasses, newClasses);
18462 if (toRemove && toRemove.length) {
18463 $animate.removeClass(this.$$element, toRemove);
18468 * Set a normalized attribute on the element in a way such that all directives
18469 * can share the attribute. This function properly handles boolean attributes.
18470 * @param {string} key Normalized key. (ie ngAttribute)
18471 * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
18472 * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
18473 * Defaults to true.
18474 * @param {string=} attrName Optional none normalized name. Defaults to key.
18476 $set: function(key, value, writeAttr, attrName) {
18477 // TODO: decide whether or not to throw an error if "class"
18478 //is set through this function since it may cause $updateClass to
18481 var node = this.$$element[0],
18482 booleanKey = getBooleanAttrName(node, key),
18483 aliasedKey = getAliasedAttrName(key),
18488 this.$$element.prop(key, value);
18489 attrName = booleanKey;
18490 } else if (aliasedKey) {
18491 this[aliasedKey] = value;
18492 observer = aliasedKey;
18497 // translate normalized key to actual key
18499 this.$attr[key] = attrName;
18501 attrName = this.$attr[key];
18503 this.$attr[key] = attrName = snake_case(key, '-');
18507 nodeName = nodeName_(this.$$element);
18509 if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
18510 (nodeName === 'img' && key === 'src')) {
18511 // sanitize a[href] and img[src] values
18512 this[key] = value = $$sanitizeUri(value, key === 'src');
18513 } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) {
18514 // sanitize img[srcset] values
18517 // first check if there are spaces because it's not the same pattern
18518 var trimmedSrcset = trim(value);
18519 // ( 999x ,| 999w ,| ,|, )
18520 var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
18521 var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
18523 // split srcset into tuple of uri and descriptor except for the last item
18524 var rawUris = trimmedSrcset.split(pattern);
18527 var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
18528 for (var i = 0; i < nbrUrisWith2parts; i++) {
18529 var innerIdx = i * 2;
18530 // sanitize the uri
18531 result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
18532 // add the descriptor
18533 result += (' ' + trim(rawUris[innerIdx + 1]));
18536 // split the last item into uri and descriptor
18537 var lastTuple = trim(rawUris[i * 2]).split(/\s/);
18539 // sanitize the last uri
18540 result += $$sanitizeUri(trim(lastTuple[0]), true);
18542 // and add the last descriptor if any
18543 if (lastTuple.length === 2) {
18544 result += (' ' + trim(lastTuple[1]));
18546 this[key] = value = result;
18549 if (writeAttr !== false) {
18550 if (value === null || isUndefined(value)) {
18551 this.$$element.removeAttr(attrName);
18553 if (SIMPLE_ATTR_NAME.test(attrName)) {
18554 this.$$element.attr(attrName, value);
18556 setSpecialAttr(this.$$element[0], attrName, value);
18562 var $$observers = this.$$observers;
18564 forEach($$observers[observer], function(fn) {
18568 $exceptionHandler(e);
18577 * @name $compile.directive.Attributes#$observe
18581 * Observes an interpolated attribute.
18583 * The observer function will be invoked once during the next `$digest` following
18584 * compilation. The observer is then invoked whenever the interpolated value
18587 * @param {string} key Normalized key. (ie ngAttribute) .
18588 * @param {function(interpolatedValue)} fn Function that will be called whenever
18589 the interpolated value of the attribute changes.
18590 * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
18591 * guide} for more info.
18592 * @returns {function()} Returns a deregistration function for this observer.
18594 $observe: function(key, fn) {
18596 $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
18597 listeners = ($$observers[key] || ($$observers[key] = []));
18599 listeners.push(fn);
18600 $rootScope.$evalAsync(function() {
18601 if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
18602 // no one registered attribute interpolation function, so lets call it manually
18607 return function() {
18608 arrayRemove(listeners, fn);
18613 function setSpecialAttr(element, attrName, value) {
18614 // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
18615 // so we have to jump through some hoops to get such an attribute
18616 // https://github.com/angular/angular.js/pull/13318
18617 specialAttrHolder.innerHTML = '<span ' + attrName + '>';
18618 var attributes = specialAttrHolder.firstChild.attributes;
18619 var attribute = attributes[0];
18620 // We have to remove the attribute from its container element before we can add it to the destination element
18621 attributes.removeNamedItem(attribute.name);
18622 attribute.value = value;
18623 element.attributes.setNamedItem(attribute);
18626 function safeAddClass($element, className) {
18628 $element.addClass(className);
18630 // ignore, since it means that we are trying to set class on
18631 // SVG element, where class name is read-only.
18636 var startSymbol = $interpolate.startSymbol(),
18637 endSymbol = $interpolate.endSymbol(),
18638 denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}')
18640 : function denormalizeTemplate(template) {
18641 return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
18643 NG_ATTR_BINDING = /^ngAttr[A-Z]/;
18644 var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
18646 compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
18647 var bindings = $element.data('$binding') || [];
18649 if (isArray(binding)) {
18650 bindings = bindings.concat(binding);
18652 bindings.push(binding);
18655 $element.data('$binding', bindings);
18658 compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
18659 safeAddClass($element, 'ng-binding');
18662 compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
18663 var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
18664 $element.data(dataName, scope);
18667 compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
18668 safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
18671 compile.$$createComment = function(directiveName, comment) {
18673 if (debugInfoEnabled) {
18674 content = ' ' + (directiveName || '') + ': ';
18675 if (comment) content += comment + ' ';
18677 return window.document.createComment(content);
18682 //================================
18684 function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
18685 previousCompileContext) {
18686 if (!($compileNodes instanceof jqLite)) {
18687 // jquery always rewraps, whereas we need to preserve the original selector so that we can
18689 $compileNodes = jqLite($compileNodes);
18692 var NOT_EMPTY = /\S+/;
18694 // We can not compile top level text elements since text nodes can be merged and we will
18695 // not be able to attach scope data to them, so we will wrap them in <span>
18696 for (var i = 0, len = $compileNodes.length; i < len; i++) {
18697 var domNode = $compileNodes[i];
18699 if (domNode.nodeType === NODE_TYPE_TEXT && domNode.nodeValue.match(NOT_EMPTY) /* non-empty */) {
18700 jqLiteWrapNode(domNode, $compileNodes[i] = window.document.createElement('span'));
18704 var compositeLinkFn =
18705 compileNodes($compileNodes, transcludeFn, $compileNodes,
18706 maxPriority, ignoreDirective, previousCompileContext);
18707 compile.$$addScopeClass($compileNodes);
18708 var namespace = null;
18709 return function publicLinkFn(scope, cloneConnectFn, options) {
18710 assertArg(scope, 'scope');
18712 if (previousCompileContext && previousCompileContext.needsNewScope) {
18713 // A parent directive did a replace and a directive on this element asked
18714 // for transclusion, which caused us to lose a layer of element on which
18715 // we could hold the new transclusion scope, so we will create it manually
18717 scope = scope.$parent.$new();
18720 options = options || {};
18721 var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
18722 transcludeControllers = options.transcludeControllers,
18723 futureParentElement = options.futureParentElement;
18725 // When `parentBoundTranscludeFn` is passed, it is a
18726 // `controllersBoundTransclude` function (it was previously passed
18727 // as `transclude` to directive.link) so we must unwrap it to get
18728 // its `boundTranscludeFn`
18729 if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
18730 parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
18734 namespace = detectNamespaceForChildElements(futureParentElement);
18737 if (namespace !== 'html') {
18738 // When using a directive with replace:true and templateUrl the $compileNodes
18739 // (or a child element inside of them)
18740 // might change, so we need to recreate the namespace adapted compileNodes
18741 // for call to the link function.
18742 // Note: This will already clone the nodes...
18743 $linkNode = jqLite(
18744 wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
18746 } else if (cloneConnectFn) {
18747 // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
18748 // and sometimes changes the structure of the DOM.
18749 $linkNode = JQLitePrototype.clone.call($compileNodes);
18751 $linkNode = $compileNodes;
18754 if (transcludeControllers) {
18755 for (var controllerName in transcludeControllers) {
18756 $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
18760 compile.$$addScopeInfo($linkNode, scope);
18762 if (cloneConnectFn) cloneConnectFn($linkNode, scope);
18763 if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
18768 function detectNamespaceForChildElements(parentElement) {
18769 // TODO: Make this detect MathML as well...
18770 var node = parentElement && parentElement[0];
18774 return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
18779 * Compile function matches each node in nodeList against the directives. Once all directives
18780 * for a particular node are collected their compile functions are executed. The compile
18781 * functions return values - the linking functions - are combined into a composite linking
18782 * function, which is the a linking function for the node.
18784 * @param {NodeList} nodeList an array of nodes or NodeList to compile
18785 * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
18786 * scope argument is auto-generated to the new child of the transcluded parent scope.
18787 * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
18788 * the rootElement must be set the jqLite collection of the compile root. This is
18789 * needed so that the jqLite collection items can be replaced with widgets.
18790 * @param {number=} maxPriority Max directive priority.
18791 * @returns {Function} A composite linking function of all of the matched directives or null.
18793 function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
18794 previousCompileContext) {
18796 attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
18798 for (var i = 0; i < nodeList.length; i++) {
18799 attrs = new Attributes();
18801 // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
18802 directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
18805 nodeLinkFn = (directives.length)
18806 ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
18807 null, [], [], previousCompileContext)
18810 if (nodeLinkFn && nodeLinkFn.scope) {
18811 compile.$$addScopeClass(attrs.$$element);
18814 childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
18815 !(childNodes = nodeList[i].childNodes) ||
18816 !childNodes.length)
18818 : compileNodes(childNodes,
18820 (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
18821 && nodeLinkFn.transclude) : transcludeFn);
18823 if (nodeLinkFn || childLinkFn) {
18824 linkFns.push(i, nodeLinkFn, childLinkFn);
18825 linkFnFound = true;
18826 nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
18829 //use the previous context only for the first element in the virtual group
18830 previousCompileContext = null;
18833 // return a linking function if we have found anything, null otherwise
18834 return linkFnFound ? compositeLinkFn : null;
18836 function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
18837 var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
18838 var stableNodeList;
18841 if (nodeLinkFnFound) {
18842 // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
18843 // offsets don't get screwed up
18844 var nodeListLength = nodeList.length;
18845 stableNodeList = new Array(nodeListLength);
18847 // create a sparse array by only copying the elements which have a linkFn
18848 for (i = 0; i < linkFns.length; i += 3) {
18850 stableNodeList[idx] = nodeList[idx];
18853 stableNodeList = nodeList;
18856 for (i = 0, ii = linkFns.length; i < ii;) {
18857 node = stableNodeList[linkFns[i++]];
18858 nodeLinkFn = linkFns[i++];
18859 childLinkFn = linkFns[i++];
18862 if (nodeLinkFn.scope) {
18863 childScope = scope.$new();
18864 compile.$$addScopeInfo(jqLite(node), childScope);
18866 childScope = scope;
18869 if (nodeLinkFn.transcludeOnThisElement) {
18870 childBoundTranscludeFn = createBoundTranscludeFn(
18871 scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
18873 } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
18874 childBoundTranscludeFn = parentBoundTranscludeFn;
18876 } else if (!parentBoundTranscludeFn && transcludeFn) {
18877 childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
18880 childBoundTranscludeFn = null;
18883 nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
18885 } else if (childLinkFn) {
18886 childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
18892 function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
18893 function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
18895 if (!transcludedScope) {
18896 transcludedScope = scope.$new(false, containingScope);
18897 transcludedScope.$$transcluded = true;
18900 return transcludeFn(transcludedScope, cloneFn, {
18901 parentBoundTranscludeFn: previousBoundTranscludeFn,
18902 transcludeControllers: controllers,
18903 futureParentElement: futureParentElement
18907 // We need to attach the transclusion slots onto the `boundTranscludeFn`
18908 // so that they are available inside the `controllersBoundTransclude` function
18909 var boundSlots = boundTranscludeFn.$$slots = createMap();
18910 for (var slotName in transcludeFn.$$slots) {
18911 if (transcludeFn.$$slots[slotName]) {
18912 boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
18914 boundSlots[slotName] = null;
18918 return boundTranscludeFn;
18922 * Looks for directives on the given node and adds them to the directive collection which is
18925 * @param node Node to search.
18926 * @param directives An array to which the directives are added to. This array is sorted before
18927 * the function returns.
18928 * @param attrs The shared attrs object which is used to populate the normalized attributes.
18929 * @param {number=} maxPriority Max directive priority.
18931 function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
18932 var nodeType = node.nodeType,
18933 attrsMap = attrs.$attr,
18938 switch (nodeType) {
18939 case NODE_TYPE_ELEMENT: /* Element */
18941 nodeName = nodeName_(node);
18943 // use the node name: <directive>
18944 addDirective(directives,
18945 directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective);
18947 // iterate over the attributes
18948 for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
18949 j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
18950 var attrStartName = false;
18951 var attrEndName = false;
18955 value = trim(attr.value);
18957 // support ngAttr attribute binding
18958 ngAttrName = directiveNormalize(name);
18959 isNgAttr = NG_ATTR_BINDING.test(ngAttrName);
18961 name = name.replace(PREFIX_REGEXP, '')
18962 .substr(8).replace(/_(.)/g, function(match, letter) {
18963 return letter.toUpperCase();
18967 var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
18968 if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
18969 attrStartName = name;
18970 attrEndName = name.substr(0, name.length - 5) + 'end';
18971 name = name.substr(0, name.length - 6);
18974 nName = directiveNormalize(name.toLowerCase());
18975 attrsMap[nName] = name;
18976 if (isNgAttr || !attrs.hasOwnProperty(nName)) {
18977 attrs[nName] = value;
18978 if (getBooleanAttrName(node, nName)) {
18979 attrs[nName] = true; // presence means true
18982 addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
18983 addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
18987 if (nodeName === 'input' && node.getAttribute('type') === 'hidden') {
18988 // Hidden input elements can have strange behaviour when navigating back to the page
18989 // This tells the browser not to try to cache and reinstate previous values
18990 node.setAttribute('autocomplete', 'off');
18993 // use class as directive
18994 if (!cssClassDirectivesEnabled) break;
18995 className = node.className;
18996 if (isObject(className)) {
18997 // Maybe SVGAnimatedString
18998 className = className.animVal;
19000 if (isString(className) && className !== '') {
19001 while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) {
19002 nName = directiveNormalize(match[2]);
19003 if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
19004 attrs[nName] = trim(match[3]);
19006 className = className.substr(match.index + match[0].length);
19010 case NODE_TYPE_TEXT: /* Text Node */
19012 // Workaround for #11781
19013 while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
19014 node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
19015 node.parentNode.removeChild(node.nextSibling);
19018 addTextInterpolateDirective(directives, node.nodeValue);
19020 case NODE_TYPE_COMMENT: /* Comment */
19021 if (!commentDirectivesEnabled) break;
19022 collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);
19026 directives.sort(byPriority);
19030 function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
19031 // function created because of performance, try/catch disables
19032 // the optimization of the whole function #14848
19034 var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
19036 var nName = directiveNormalize(match[1]);
19037 if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
19038 attrs[nName] = trim(match[2]);
19042 // turns out that under some circumstances IE9 throws errors when one attempts to read
19043 // comment's node value.
19044 // Just ignore it and continue. (Can't seem to reproduce in test case.)
19049 * Given a node with a directive-start it collects all of the siblings until it finds
19056 function groupScan(node, attrStart, attrEnd) {
19059 if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
19062 throw $compileMinErr('uterdir',
19063 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.',
19064 attrStart, attrEnd);
19066 if (node.nodeType === NODE_TYPE_ELEMENT) {
19067 if (node.hasAttribute(attrStart)) depth++;
19068 if (node.hasAttribute(attrEnd)) depth--;
19071 node = node.nextSibling;
19072 } while (depth > 0);
19077 return jqLite(nodes);
19081 * Wrapper for linking function which converts normal linking function into a grouped
19082 * linking function.
19086 * @returns {Function}
19088 function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
19089 return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
19090 element = groupScan(element[0], attrStart, attrEnd);
19091 return linkFn(scope, element, attrs, controllers, transcludeFn);
19096 * A function generator that is used to support both eager and lazy compilation
19097 * linking function.
19099 * @param $compileNodes
19100 * @param transcludeFn
19101 * @param maxPriority
19102 * @param ignoreDirective
19103 * @param previousCompileContext
19104 * @returns {Function}
19106 function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
19110 return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
19112 return /** @this */ function lazyCompilation() {
19114 compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
19116 // Null out all of these references in order to make them eligible for garbage collection
19117 // since this is a potentially long lived closure
19118 $compileNodes = transcludeFn = previousCompileContext = null;
19120 return compiled.apply(this, arguments);
19125 * Once the directives have been collected, their compile functions are executed. This method
19126 * is responsible for inlining directive templates as well as terminating the application
19127 * of the directives if the terminal directive has been reached.
19129 * @param {Array} directives Array of collected directives to execute their compile function.
19130 * this needs to be pre-sorted by priority order.
19131 * @param {Node} compileNode The raw DOM node to apply the compile functions to
19132 * @param {Object} templateAttrs The shared attribute function
19133 * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
19134 * scope argument is auto-generated to the new
19135 * child of the transcluded parent scope.
19136 * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
19137 * argument has the root jqLite array so that we can replace nodes
19139 * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
19140 * compiling the transclusion.
19141 * @param {Array.<Function>} preLinkFns
19142 * @param {Array.<Function>} postLinkFns
19143 * @param {Object} previousCompileContext Context used for previous compilation of the current
19145 * @returns {Function} linkFn
19147 function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
19148 jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
19149 previousCompileContext) {
19150 previousCompileContext = previousCompileContext || {};
19152 var terminalPriority = -Number.MAX_VALUE,
19153 newScopeDirective = previousCompileContext.newScopeDirective,
19154 controllerDirectives = previousCompileContext.controllerDirectives,
19155 newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
19156 templateDirective = previousCompileContext.templateDirective,
19157 nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
19158 hasTranscludeDirective = false,
19159 hasTemplate = false,
19160 hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
19161 $compileNode = templateAttrs.$$element = jqLite(compileNode),
19165 replaceDirective = originalReplaceDirective,
19166 childTranscludeFn = transcludeFn,
19168 didScanForMultipleTransclusion = false,
19169 mightHaveMultipleTransclusionError = false,
19172 // executes all directives on the current element
19173 for (var i = 0, ii = directives.length; i < ii; i++) {
19174 directive = directives[i];
19175 var attrStart = directive.$$start;
19176 var attrEnd = directive.$$end;
19178 // collect multiblock sections
19180 $compileNode = groupScan(compileNode, attrStart, attrEnd);
19182 $template = undefined;
19184 if (terminalPriority > directive.priority) {
19185 break; // prevent further processing of directives
19188 directiveValue = directive.scope;
19190 if (directiveValue) {
19192 // skip the check for directives with async templates, we'll check the derived sync
19193 // directive when the template arrives
19194 if (!directive.templateUrl) {
19195 if (isObject(directiveValue)) {
19196 // This directive is trying to add an isolated scope.
19197 // Check that there is no scope of any kind already
19198 assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
19199 directive, $compileNode);
19200 newIsolateScopeDirective = directive;
19202 // This directive is trying to add a child scope.
19203 // Check that there is no isolated scope already
19204 assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
19209 newScopeDirective = newScopeDirective || directive;
19212 directiveName = directive.name;
19214 // If we encounter a condition that can result in transclusion on the directive,
19215 // then scan ahead in the remaining directives for others that may cause a multiple
19216 // transclusion error to be thrown during the compilation process. If a matching directive
19217 // is found, then we know that when we encounter a transcluded directive, we need to eagerly
19218 // compile the `transclude` function rather than doing it lazily in order to throw
19219 // exceptions at the correct time
19220 if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
19221 || (directive.transclude && !directive.$$tlb))) {
19222 var candidateDirective;
19224 for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) {
19225 if ((candidateDirective.transclude && !candidateDirective.$$tlb)
19226 || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
19227 mightHaveMultipleTransclusionError = true;
19232 didScanForMultipleTransclusion = true;
19235 if (!directive.templateUrl && directive.controller) {
19236 controllerDirectives = controllerDirectives || createMap();
19237 assertNoDuplicate('\'' + directiveName + '\' controller',
19238 controllerDirectives[directiveName], directive, $compileNode);
19239 controllerDirectives[directiveName] = directive;
19242 directiveValue = directive.transclude;
19244 if (directiveValue) {
19245 hasTranscludeDirective = true;
19247 // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
19248 // This option should only be used by directives that know how to safely handle element transclusion,
19249 // where the transcluded nodes are added or replaced after linking.
19250 if (!directive.$$tlb) {
19251 assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
19252 nonTlbTranscludeDirective = directive;
19255 if (directiveValue === 'element') {
19256 hasElementTranscludeDirective = true;
19257 terminalPriority = directive.priority;
19258 $template = $compileNode;
19259 $compileNode = templateAttrs.$$element =
19260 jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
19261 compileNode = $compileNode[0];
19262 replaceWith(jqCollection, sliceArgs($template), compileNode);
19264 // Support: Chrome < 50
19265 // https://github.com/angular/angular.js/issues/14041
19267 // In the versions of V8 prior to Chrome 50, the document fragment that is created
19268 // in the `replaceWith` function is improperly garbage collected despite still
19269 // being referenced by the `parentNode` property of all of the child nodes. By adding
19270 // a reference to the fragment via a different property, we can avoid that incorrect
19272 // TODO: remove this line after Chrome 50 has been released
19273 $template[0].$$parentNode = $template[0].parentNode;
19275 childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
19276 replaceDirective && replaceDirective.name, {
19278 // - controllerDirectives - otherwise we'll create duplicates controllers
19279 // - newIsolateScopeDirective or templateDirective - combining templates with
19280 // element transclusion doesn't make sense.
19282 // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
19283 // on the same element more than once.
19284 nonTlbTranscludeDirective: nonTlbTranscludeDirective
19288 var slots = createMap();
19290 $template = jqLite(jqLiteClone(compileNode)).contents();
19292 if (isObject(directiveValue)) {
19294 // We have transclusion slots,
19295 // collect them up, compile them and store their transclusion functions
19298 var slotMap = createMap();
19299 var filledSlots = createMap();
19301 // Parse the element selectors
19302 forEach(directiveValue, function(elementSelector, slotName) {
19303 // If an element selector starts with a ? then it is optional
19304 var optional = (elementSelector.charAt(0) === '?');
19305 elementSelector = optional ? elementSelector.substring(1) : elementSelector;
19307 slotMap[elementSelector] = slotName;
19309 // We explicitly assign `null` since this implies that a slot was defined but not filled.
19310 // Later when calling boundTransclusion functions with a slot name we only error if the
19311 // slot is `undefined`
19312 slots[slotName] = null;
19314 // filledSlots contains `true` for all slots that are either optional or have been
19315 // filled. This is used to check that we have not missed any required slots
19316 filledSlots[slotName] = optional;
19319 // Add the matching elements into their slot
19320 forEach($compileNode.contents(), function(node) {
19321 var slotName = slotMap[directiveNormalize(nodeName_(node))];
19323 filledSlots[slotName] = true;
19324 slots[slotName] = slots[slotName] || [];
19325 slots[slotName].push(node);
19327 $template.push(node);
19331 // Check for required slots that were not filled
19332 forEach(filledSlots, function(filled, slotName) {
19334 throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
19338 for (var slotName in slots) {
19339 if (slots[slotName]) {
19340 // Only define a transclusion function if the slot was filled
19341 slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
19346 $compileNode.empty(); // clear contents
19347 childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
19348 undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
19349 childTranscludeFn.$$slots = slots;
19353 if (directive.template) {
19354 hasTemplate = true;
19355 assertNoDuplicate('template', templateDirective, directive, $compileNode);
19356 templateDirective = directive;
19358 directiveValue = (isFunction(directive.template))
19359 ? directive.template($compileNode, templateAttrs)
19360 : directive.template;
19362 directiveValue = denormalizeTemplate(directiveValue);
19364 if (directive.replace) {
19365 replaceDirective = directive;
19366 if (jqLiteIsTextNode(directiveValue)) {
19369 $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
19371 compileNode = $template[0];
19373 if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
19374 throw $compileMinErr('tplrt',
19375 'Template for directive \'{0}\' must have exactly one root element. {1}',
19376 directiveName, '');
19379 replaceWith(jqCollection, $compileNode, compileNode);
19381 var newTemplateAttrs = {$attr: {}};
19383 // combine directives from the original node and from the template:
19384 // - take the array of directives for this element
19385 // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
19386 // - collect directives from the template and sort them by priority
19387 // - combine directives as: processed + template + unprocessed
19388 var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
19389 var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
19391 if (newIsolateScopeDirective || newScopeDirective) {
19392 // The original directive caused the current element to be replaced but this element
19393 // also needs to have a new scope, so we need to tell the template directives
19394 // that they would need to get their scope from further up, if they require transclusion
19395 markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
19397 directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
19398 mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
19400 ii = directives.length;
19402 $compileNode.html(directiveValue);
19406 if (directive.templateUrl) {
19407 hasTemplate = true;
19408 assertNoDuplicate('template', templateDirective, directive, $compileNode);
19409 templateDirective = directive;
19411 if (directive.replace) {
19412 replaceDirective = directive;
19415 // eslint-disable-next-line no-func-assign
19416 nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
19417 templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
19418 controllerDirectives: controllerDirectives,
19419 newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
19420 newIsolateScopeDirective: newIsolateScopeDirective,
19421 templateDirective: templateDirective,
19422 nonTlbTranscludeDirective: nonTlbTranscludeDirective
19424 ii = directives.length;
19425 } else if (directive.compile) {
19427 linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
19428 var context = directive.$$originalDirective || directive;
19429 if (isFunction(linkFn)) {
19430 addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);
19431 } else if (linkFn) {
19432 addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);
19435 $exceptionHandler(e, startingTag($compileNode));
19439 if (directive.terminal) {
19440 nodeLinkFn.terminal = true;
19441 terminalPriority = Math.max(terminalPriority, directive.priority);
19446 nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
19447 nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
19448 nodeLinkFn.templateOnThisElement = hasTemplate;
19449 nodeLinkFn.transclude = childTranscludeFn;
19451 previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
19453 // might be normal or delayed nodeLinkFn depending on if templateUrl is present
19456 ////////////////////
19458 function addLinkFns(pre, post, attrStart, attrEnd) {
19460 if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
19461 pre.require = directive.require;
19462 pre.directiveName = directiveName;
19463 if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
19464 pre = cloneAndAnnotateFn(pre, {isolateScope: true});
19466 preLinkFns.push(pre);
19469 if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
19470 post.require = directive.require;
19471 post.directiveName = directiveName;
19472 if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
19473 post = cloneAndAnnotateFn(post, {isolateScope: true});
19475 postLinkFns.push(post);
19479 function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
19480 var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
19481 attrs, scopeBindingInfo;
19483 if (compileNode === linkNode) {
19484 attrs = templateAttrs;
19485 $element = templateAttrs.$$element;
19487 $element = jqLite(linkNode);
19488 attrs = new Attributes($element, templateAttrs);
19491 controllerScope = scope;
19492 if (newIsolateScopeDirective) {
19493 isolateScope = scope.$new(true);
19494 } else if (newScopeDirective) {
19495 controllerScope = scope.$parent;
19498 if (boundTranscludeFn) {
19499 // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
19500 // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
19501 transcludeFn = controllersBoundTransclude;
19502 transcludeFn.$$boundTransclude = boundTranscludeFn;
19503 // expose the slots on the `$transclude` function
19504 transcludeFn.isSlotFilled = function(slotName) {
19505 return !!boundTranscludeFn.$$slots[slotName];
19509 if (controllerDirectives) {
19510 elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
19513 if (newIsolateScopeDirective) {
19514 // Initialize isolate scope bindings for new isolate scope directive.
19515 compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
19516 templateDirective === newIsolateScopeDirective.$$originalDirective)));
19517 compile.$$addScopeClass($element, true);
19518 isolateScope.$$isolateBindings =
19519 newIsolateScopeDirective.$$isolateBindings;
19520 scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,
19521 isolateScope.$$isolateBindings,
19522 newIsolateScopeDirective);
19523 if (scopeBindingInfo.removeWatches) {
19524 isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);
19528 // Initialize bindToController bindings
19529 for (var name in elementControllers) {
19530 var controllerDirective = controllerDirectives[name];
19531 var controller = elementControllers[name];
19532 var bindings = controllerDirective.$$bindings.bindToController;
19534 if (preAssignBindingsEnabled) {
19536 controller.bindingInfo =
19537 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
19539 controller.bindingInfo = {};
19542 var controllerResult = controller();
19543 if (controllerResult !== controller.instance) {
19544 // If the controller constructor has a return value, overwrite the instance
19545 // from setupControllers
19546 controller.instance = controllerResult;
19547 $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
19548 if (controller.bindingInfo.removeWatches) {
19549 controller.bindingInfo.removeWatches();
19551 controller.bindingInfo =
19552 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
19555 controller.instance = controller();
19556 $element.data('$' + controllerDirective.name + 'Controller', controller.instance);
19557 controller.bindingInfo =
19558 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
19562 // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
19563 forEach(controllerDirectives, function(controllerDirective, name) {
19564 var require = controllerDirective.require;
19565 if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
19566 extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
19570 // Handle the init and destroy lifecycle hooks on all controllers that have them
19571 forEach(elementControllers, function(controller) {
19572 var controllerInstance = controller.instance;
19573 if (isFunction(controllerInstance.$onChanges)) {
19575 controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
19577 $exceptionHandler(e);
19580 if (isFunction(controllerInstance.$onInit)) {
19582 controllerInstance.$onInit();
19584 $exceptionHandler(e);
19587 if (isFunction(controllerInstance.$doCheck)) {
19588 controllerScope.$watch(function() { controllerInstance.$doCheck(); });
19589 controllerInstance.$doCheck();
19591 if (isFunction(controllerInstance.$onDestroy)) {
19592 controllerScope.$on('$destroy', function callOnDestroyHook() {
19593 controllerInstance.$onDestroy();
19599 for (i = 0, ii = preLinkFns.length; i < ii; i++) {
19600 linkFn = preLinkFns[i];
19601 invokeLinkFn(linkFn,
19602 linkFn.isolateScope ? isolateScope : scope,
19605 linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
19611 // We only pass the isolate scope, if the isolate directive has a template,
19612 // otherwise the child elements do not belong to the isolate directive.
19613 var scopeToChild = scope;
19614 if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
19615 scopeToChild = isolateScope;
19618 childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
19622 for (i = postLinkFns.length - 1; i >= 0; i--) {
19623 linkFn = postLinkFns[i];
19624 invokeLinkFn(linkFn,
19625 linkFn.isolateScope ? isolateScope : scope,
19628 linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
19633 // Trigger $postLink lifecycle hooks
19634 forEach(elementControllers, function(controller) {
19635 var controllerInstance = controller.instance;
19636 if (isFunction(controllerInstance.$postLink)) {
19637 controllerInstance.$postLink();
19641 // This is the function that is injected as `$transclude`.
19642 // Note: all arguments are optional!
19643 function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
19644 var transcludeControllers;
19645 // No scope passed in:
19646 if (!isScope(scope)) {
19647 slotName = futureParentElement;
19648 futureParentElement = cloneAttachFn;
19649 cloneAttachFn = scope;
19653 if (hasElementTranscludeDirective) {
19654 transcludeControllers = elementControllers;
19656 if (!futureParentElement) {
19657 futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
19660 // slotTranscludeFn can be one of three things:
19661 // * a transclude function - a filled slot
19662 // * `null` - an optional slot that was not filled
19663 // * `undefined` - a slot that was not declared (i.e. invalid)
19664 var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
19665 if (slotTranscludeFn) {
19666 return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
19667 } else if (isUndefined(slotTranscludeFn)) {
19668 throw $compileMinErr('noslot',
19669 'No parent directive that requires a transclusion with slot name "{0}". ' +
19671 slotName, startingTag($element));
19674 return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
19680 function getControllers(directiveName, require, $element, elementControllers) {
19683 if (isString(require)) {
19684 var match = require.match(REQUIRE_PREFIX_REGEXP);
19685 var name = require.substring(match[0].length);
19686 var inheritType = match[1] || match[3];
19687 var optional = match[2] === '?';
19689 //If only parents then start at the parent element
19690 if (inheritType === '^^') {
19691 $element = $element.parent();
19692 //Otherwise attempt getting the controller from elementControllers in case
19693 //the element is transcluded (and has no data) and to avoid .data if possible
19695 value = elementControllers && elementControllers[name];
19696 value = value && value.instance;
19700 var dataName = '$' + name + 'Controller';
19701 value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
19704 if (!value && !optional) {
19705 throw $compileMinErr('ctreq',
19706 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!',
19707 name, directiveName);
19709 } else if (isArray(require)) {
19711 for (var i = 0, ii = require.length; i < ii; i++) {
19712 value[i] = getControllers(directiveName, require[i], $element, elementControllers);
19714 } else if (isObject(require)) {
19716 forEach(require, function(controller, property) {
19717 value[property] = getControllers(directiveName, controller, $element, elementControllers);
19721 return value || null;
19724 function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
19725 var elementControllers = createMap();
19726 for (var controllerKey in controllerDirectives) {
19727 var directive = controllerDirectives[controllerKey];
19729 $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
19730 $element: $element,
19732 $transclude: transcludeFn
19735 var controller = directive.controller;
19736 if (controller === '@') {
19737 controller = attrs[directive.name];
19740 var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
19742 // For directives with element transclusion the element is a comment.
19743 // In this case .data will not attach any data.
19744 // Instead, we save the controllers for the element in a local hash and attach to .data
19745 // later, once we have the actual element.
19746 elementControllers[directive.name] = controllerInstance;
19747 $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
19749 return elementControllers;
19752 // Depending upon the context in which a directive finds itself it might need to have a new isolated
19753 // or child scope created. For instance:
19754 // * if the directive has been pulled into a template because another directive with a higher priority
19755 // asked for element transclusion
19756 // * if the directive itself asks for transclusion but it is at the root of a template and the original
19757 // element was replaced. See https://github.com/angular/angular.js/issues/12936
19758 function markDirectiveScope(directives, isolateScope, newScope) {
19759 for (var j = 0, jj = directives.length; j < jj; j++) {
19760 directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
19765 * looks up the directive and decorates it with exception handling and proper parameters. We
19766 * call this the boundDirective.
19768 * @param {string} name name of the directive to look up.
19769 * @param {string} location The directive must be found in specific format.
19770 * String containing any of theses characters:
19772 * * `E`: element name
19776 * @returns {boolean} true if directive was added.
19778 function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
19780 if (name === ignoreDirective) return null;
19782 if (hasDirectives.hasOwnProperty(name)) {
19783 for (var directive, directives = $injector.get(name + Suffix),
19784 i = 0, ii = directives.length; i < ii; i++) {
19785 directive = directives[i];
19786 if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
19787 directive.restrict.indexOf(location) !== -1) {
19788 if (startAttrName) {
19789 directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
19791 if (!directive.$$bindings) {
19792 var bindings = directive.$$bindings =
19793 parseDirectiveBindings(directive, directive.name);
19794 if (isObject(bindings.isolateScope)) {
19795 directive.$$isolateBindings = bindings.isolateScope;
19798 tDirectives.push(directive);
19808 * looks up the directive and returns true if it is a multi-element directive,
19809 * and therefore requires DOM nodes between -start and -end markers to be grouped
19812 * @param {string} name name of the directive to look up.
19813 * @returns true if directive was registered as multi-element.
19815 function directiveIsMultiElement(name) {
19816 if (hasDirectives.hasOwnProperty(name)) {
19817 for (var directive, directives = $injector.get(name + Suffix),
19818 i = 0, ii = directives.length; i < ii; i++) {
19819 directive = directives[i];
19820 if (directive.multiElement) {
19829 * When the element is replaced with HTML template then the new attributes
19830 * on the template need to be merged with the existing attributes in the DOM.
19831 * The desired effect is to have both of the attributes present.
19833 * @param {object} dst destination attributes (original DOM)
19834 * @param {object} src source attributes (from the directive template)
19836 function mergeTemplateAttributes(dst, src) {
19837 var srcAttr = src.$attr,
19838 dstAttr = dst.$attr;
19840 // reapply the old attributes to the new element
19841 forEach(dst, function(value, key) {
19842 if (key.charAt(0) !== '$') {
19843 if (src[key] && src[key] !== value) {
19844 value += (key === 'style' ? ';' : ' ') + src[key];
19846 dst.$set(key, value, true, srcAttr[key]);
19850 // copy the new attributes on the old attrs object
19851 forEach(src, function(value, key) {
19852 // Check if we already set this attribute in the loop above.
19853 // `dst` will never contain hasOwnProperty as DOM parser won't let it.
19854 // You will get an "InvalidCharacterError: DOM Exception 5" error if you
19855 // have an attribute like "has-own-property" or "data-has-own-property", etc.
19856 if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {
19859 if (key !== 'class' && key !== 'style') {
19860 dstAttr[key] = srcAttr[key];
19867 function compileTemplateUrl(directives, $compileNode, tAttrs,
19868 $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
19869 var linkQueue = [],
19870 afterTemplateNodeLinkFn,
19871 afterTemplateChildLinkFn,
19872 beforeTemplateCompileNode = $compileNode[0],
19873 origAsyncDirective = directives.shift(),
19874 derivedSyncDirective = inherit(origAsyncDirective, {
19875 templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
19877 templateUrl = (isFunction(origAsyncDirective.templateUrl))
19878 ? origAsyncDirective.templateUrl($compileNode, tAttrs)
19879 : origAsyncDirective.templateUrl,
19880 templateNamespace = origAsyncDirective.templateNamespace;
19882 $compileNode.empty();
19884 $templateRequest(templateUrl)
19885 .then(function(content) {
19886 var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
19888 content = denormalizeTemplate(content);
19890 if (origAsyncDirective.replace) {
19891 if (jqLiteIsTextNode(content)) {
19894 $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
19896 compileNode = $template[0];
19898 if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
19899 throw $compileMinErr('tplrt',
19900 'Template for directive \'{0}\' must have exactly one root element. {1}',
19901 origAsyncDirective.name, templateUrl);
19904 tempTemplateAttrs = {$attr: {}};
19905 replaceWith($rootElement, $compileNode, compileNode);
19906 var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
19908 if (isObject(origAsyncDirective.scope)) {
19909 // the original directive that caused the template to be loaded async required
19910 // an isolate scope
19911 markDirectiveScope(templateDirectives, true);
19913 directives = templateDirectives.concat(directives);
19914 mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
19916 compileNode = beforeTemplateCompileNode;
19917 $compileNode.html(content);
19920 directives.unshift(derivedSyncDirective);
19922 afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
19923 childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
19924 previousCompileContext);
19925 forEach($rootElement, function(node, i) {
19926 if (node === compileNode) {
19927 $rootElement[i] = $compileNode[0];
19930 afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
19932 while (linkQueue.length) {
19933 var scope = linkQueue.shift(),
19934 beforeTemplateLinkNode = linkQueue.shift(),
19935 linkRootElement = linkQueue.shift(),
19936 boundTranscludeFn = linkQueue.shift(),
19937 linkNode = $compileNode[0];
19939 if (scope.$$destroyed) continue;
19941 if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
19942 var oldClasses = beforeTemplateLinkNode.className;
19944 if (!(previousCompileContext.hasElementTranscludeDirective &&
19945 origAsyncDirective.replace)) {
19946 // it was cloned therefore we have to clone as well.
19947 linkNode = jqLiteClone(compileNode);
19949 replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
19951 // Copy in CSS classes from original node
19952 safeAddClass(jqLite(linkNode), oldClasses);
19954 if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
19955 childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
19957 childBoundTranscludeFn = boundTranscludeFn;
19959 afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
19960 childBoundTranscludeFn);
19965 return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
19966 var childBoundTranscludeFn = boundTranscludeFn;
19967 if (scope.$$destroyed) return;
19969 linkQueue.push(scope,
19972 childBoundTranscludeFn);
19974 if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
19975 childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
19977 afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
19984 * Sorting function for bound directives.
19986 function byPriority(a, b) {
19987 var diff = b.priority - a.priority;
19988 if (diff !== 0) return diff;
19989 if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
19990 return a.index - b.index;
19993 function assertNoDuplicate(what, previousDirective, directive, element) {
19995 function wrapModuleNameIfDefined(moduleName) {
19996 return moduleName ?
19997 (' (module: ' + moduleName + ')') :
20001 if (previousDirective) {
20002 throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
20003 previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
20004 directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
20009 function addTextInterpolateDirective(directives, text) {
20010 var interpolateFn = $interpolate(text, true);
20011 if (interpolateFn) {
20014 compile: function textInterpolateCompileFn(templateNode) {
20015 var templateNodeParent = templateNode.parent(),
20016 hasCompileParent = !!templateNodeParent.length;
20018 // When transcluding a template that has bindings in the root
20019 // we don't have a parent and thus need to add the class during linking fn.
20020 if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
20022 return function textInterpolateLinkFn(scope, node) {
20023 var parent = node.parent();
20024 if (!hasCompileParent) compile.$$addBindingClass(parent);
20025 compile.$$addBindingInfo(parent, interpolateFn.expressions);
20026 scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
20027 node[0].nodeValue = value;
20036 function wrapTemplate(type, template) {
20037 type = lowercase(type || 'html');
20041 var wrapper = window.document.createElement('div');
20042 wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
20043 return wrapper.childNodes[0].childNodes;
20050 function getTrustedContext(node, attrNormalizedName) {
20051 if (attrNormalizedName === 'srcdoc') {
20054 var tag = nodeName_(node);
20055 // All tags with src attributes require a RESOURCE_URL value, except for
20056 // img and various html5 media tags.
20057 if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') {
20058 if (['img', 'video', 'audio', 'source', 'track'].indexOf(tag) === -1) {
20059 return $sce.RESOURCE_URL;
20061 // maction[xlink:href] can source SVG. It's not limited to <maction>.
20062 } else if (attrNormalizedName === 'xlinkHref' ||
20063 (tag === 'form' && attrNormalizedName === 'action')
20065 return $sce.RESOURCE_URL;
20070 function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) {
20071 var trustedContext = getTrustedContext(node, name);
20072 var mustHaveExpression = !isNgAttr;
20073 var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr;
20075 var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing);
20077 // no interpolation found -> ignore
20078 if (!interpolateFn) return;
20080 if (name === 'multiple' && nodeName_(node) === 'select') {
20081 throw $compileMinErr('selmulti',
20082 'Binding to the \'multiple\' attribute is not supported. Element: {0}',
20083 startingTag(node));
20088 compile: function() {
20090 pre: function attrInterpolatePreLinkFn(scope, element, attr) {
20091 var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
20093 if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
20094 throw $compileMinErr('nodomevents',
20095 'Interpolations for HTML DOM event attributes are disallowed. Please use the ' +
20096 'ng- versions (such as ng-click instead of onclick) instead.');
20099 // If the attribute has changed since last $interpolate()ed
20100 var newValue = attr[name];
20101 if (newValue !== value) {
20102 // we need to interpolate again since the attribute value has been updated
20103 // (e.g. by another directive's compile function)
20104 // ensure unset/empty values make interpolateFn falsy
20105 interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
20109 // if attribute was updated so that there is no interpolation going on we don't want to
20110 // register any observers
20111 if (!interpolateFn) return;
20113 // initialize attr object so that it's ready in case we need the value for isolate
20114 // scope initialization, otherwise the value would not be available from isolate
20115 // directive's linking fn during linking phase
20116 attr[name] = interpolateFn(scope);
20118 ($$observers[name] || ($$observers[name] = [])).$$inter = true;
20119 (attr.$$observers && attr.$$observers[name].$$scope || scope).
20120 $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
20121 //special case for class attribute addition + removal
20122 //so that class changes can tap into the animation
20123 //hooks provided by the $animate service. Be sure to
20124 //skip animations when the first digest occurs (when
20125 //both the new and the old values are the same) since
20126 //the CSS classes are the non-interpolated values
20127 if (name === 'class' && newValue !== oldValue) {
20128 attr.$updateClass(newValue, oldValue);
20130 attr.$set(name, newValue);
20141 * This is a special jqLite.replaceWith, which can replace items which
20142 * have no parents, provided that the containing jqLite collection is provided.
20144 * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
20145 * in the root of the tree.
20146 * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
20147 * the shell, but replace its DOM node reference.
20148 * @param {Node} newNode The new DOM node.
20150 function replaceWith($rootElement, elementsToRemove, newNode) {
20151 var firstElementToRemove = elementsToRemove[0],
20152 removeCount = elementsToRemove.length,
20153 parent = firstElementToRemove.parentNode,
20156 if ($rootElement) {
20157 for (i = 0, ii = $rootElement.length; i < ii; i++) {
20158 if ($rootElement[i] === firstElementToRemove) {
20159 $rootElement[i++] = newNode;
20160 for (var j = i, j2 = j + removeCount - 1,
20161 jj = $rootElement.length;
20162 j < jj; j++, j2++) {
20164 $rootElement[j] = $rootElement[j2];
20166 delete $rootElement[j];
20169 $rootElement.length -= removeCount - 1;
20171 // If the replaced element is also the jQuery .context then replace it
20172 // .context is a deprecated jQuery api, so we should set it only when jQuery set it
20173 // http://api.jquery.com/context/
20174 if ($rootElement.context === firstElementToRemove) {
20175 $rootElement.context = newNode;
20183 parent.replaceChild(newNode, firstElementToRemove);
20186 // Append all the `elementsToRemove` to a fragment. This will...
20187 // - remove them from the DOM
20188 // - allow them to still be traversed with .nextSibling
20189 // - allow a single fragment.qSA to fetch all elements being removed
20190 var fragment = window.document.createDocumentFragment();
20191 for (i = 0; i < removeCount; i++) {
20192 fragment.appendChild(elementsToRemove[i]);
20195 if (jqLite.hasData(firstElementToRemove)) {
20196 // Copy over user data (that includes Angular's $scope etc.). Don't copy private
20197 // data here because there's no public interface in jQuery to do that and copying over
20198 // event listeners (which is the main use of private data) wouldn't work anyway.
20199 jqLite.data(newNode, jqLite.data(firstElementToRemove));
20201 // Remove $destroy event listeners from `firstElementToRemove`
20202 jqLite(firstElementToRemove).off('$destroy');
20205 // Cleanup any data/listeners on the elements and children.
20206 // This includes invoking the $destroy event on any elements with listeners.
20207 jqLite.cleanData(fragment.querySelectorAll('*'));
20209 // Update the jqLite collection to only contain the `newNode`
20210 for (i = 1; i < removeCount; i++) {
20211 delete elementsToRemove[i];
20213 elementsToRemove[0] = newNode;
20214 elementsToRemove.length = 1;
20218 function cloneAndAnnotateFn(fn, annotation) {
20219 return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
20223 function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
20225 linkFn(scope, $element, attrs, controllers, transcludeFn);
20227 $exceptionHandler(e, startingTag($element));
20232 // Set up $watches for isolate scope and controller bindings.
20233 function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
20234 var removeWatchCollection = [];
20235 var initialChanges = {};
20237 forEach(bindings, function initializeBinding(definition, scopeName) {
20238 var attrName = definition.attrName,
20239 optional = definition.optional,
20240 mode = definition.mode, // @, =, <, or &
20242 parentGet, parentSet, compare, removeWatch;
20247 if (!optional && !hasOwnProperty.call(attrs, attrName)) {
20248 destination[scopeName] = attrs[attrName] = undefined;
20250 removeWatch = attrs.$observe(attrName, function(value) {
20251 if (isString(value) || isBoolean(value)) {
20252 var oldValue = destination[scopeName];
20253 recordChanges(scopeName, value, oldValue);
20254 destination[scopeName] = value;
20257 attrs.$$observers[attrName].$$scope = scope;
20258 lastValue = attrs[attrName];
20259 if (isString(lastValue)) {
20260 // If the attribute has been provided then we trigger an interpolation to ensure
20261 // the value is there for use in the link fn
20262 destination[scopeName] = $interpolate(lastValue)(scope);
20263 } else if (isBoolean(lastValue)) {
20264 // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
20265 // the value to boolean rather than a string, so we special case this situation
20266 destination[scopeName] = lastValue;
20268 initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
20269 removeWatchCollection.push(removeWatch);
20273 if (!hasOwnProperty.call(attrs, attrName)) {
20274 if (optional) break;
20275 attrs[attrName] = undefined;
20277 if (optional && !attrs[attrName]) break;
20279 parentGet = $parse(attrs[attrName]);
20280 if (parentGet.literal) {
20283 // eslint-disable-next-line no-self-compare
20284 compare = function simpleCompare(a, b) { return a === b || (a !== a && b !== b); };
20286 parentSet = parentGet.assign || function() {
20287 // reset the change, or we will throw this exception on every $digest
20288 lastValue = destination[scopeName] = parentGet(scope);
20289 throw $compileMinErr('nonassign',
20290 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!',
20291 attrs[attrName], attrName, directive.name);
20293 lastValue = destination[scopeName] = parentGet(scope);
20294 var parentValueWatch = function parentValueWatch(parentValue) {
20295 if (!compare(parentValue, destination[scopeName])) {
20296 // we are out of sync and need to copy
20297 if (!compare(parentValue, lastValue)) {
20298 // parent changed and it has precedence
20299 destination[scopeName] = parentValue;
20301 // if the parent can be assigned then do so
20302 parentSet(scope, parentValue = destination[scopeName]);
20305 lastValue = parentValue;
20308 parentValueWatch.$stateful = true;
20309 if (definition.collection) {
20310 removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
20312 removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
20314 removeWatchCollection.push(removeWatch);
20318 if (!hasOwnProperty.call(attrs, attrName)) {
20319 if (optional) break;
20320 attrs[attrName] = undefined;
20322 if (optional && !attrs[attrName]) break;
20324 parentGet = $parse(attrs[attrName]);
20325 var deepWatch = parentGet.literal;
20327 var initialValue = destination[scopeName] = parentGet(scope);
20328 initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
20330 removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) {
20331 if (oldValue === newValue) {
20332 if (oldValue === initialValue || (deepWatch && equals(oldValue, initialValue))) {
20335 oldValue = initialValue;
20337 recordChanges(scopeName, newValue, oldValue);
20338 destination[scopeName] = newValue;
20341 removeWatchCollection.push(removeWatch);
20345 // Don't assign Object.prototype method to scope
20346 parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
20348 // Don't assign noop to destination if expression is not valid
20349 if (parentGet === noop && optional) break;
20351 destination[scopeName] = function(locals) {
20352 return parentGet(scope, locals);
20358 function recordChanges(key, currentValue, previousValue) {
20359 if (isFunction(destination.$onChanges) && currentValue !== previousValue &&
20360 // eslint-disable-next-line no-self-compare
20361 (currentValue === currentValue || previousValue === previousValue)) {
20362 // If we have not already scheduled the top level onChangesQueue handler then do so now
20363 if (!onChangesQueue) {
20364 scope.$$postDigest(flushOnChangesQueue);
20365 onChangesQueue = [];
20367 // If we have not already queued a trigger of onChanges for this controller then do so now
20370 onChangesQueue.push(triggerOnChangesHook);
20372 // If the has been a change on this property already then we need to reuse the previous value
20373 if (changes[key]) {
20374 previousValue = changes[key].previousValue;
20376 // Store this change
20377 changes[key] = new SimpleChange(previousValue, currentValue);
20381 function triggerOnChangesHook() {
20382 destination.$onChanges(changes);
20383 // Now clear the changes so that we schedule onChanges when more changes arrive
20384 changes = undefined;
20388 initialChanges: initialChanges,
20389 removeWatches: removeWatchCollection.length && function removeWatches() {
20390 for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
20391 removeWatchCollection[i]();
20399 function SimpleChange(previous, current) {
20400 this.previousValue = previous;
20401 this.currentValue = current;
20403 SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
20406 var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i;
20408 * Converts all accepted directives format into proper directive name.
20409 * @param name Name to normalize
20411 function directiveNormalize(name) {
20412 return camelCase(name.replace(PREFIX_REGEXP, ''));
20417 * @name $compile.directive.Attributes
20420 * A shared object between directive compile / linking functions which contains normalized DOM
20421 * element attributes. The values reflect current binding state `{{ }}`. The normalization is
20422 * needed since all of these are treated as equivalent in Angular:
20425 * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
20431 * @name $compile.directive.Attributes#$attr
20434 * A map of DOM element attribute names to the normalized name. This is
20435 * needed to do reverse lookup from normalized name back to actual name.
20441 * @name $compile.directive.Attributes#$set
20445 * Set DOM element attribute value.
20448 * @param {string} name Normalized element attribute name of the property to modify. The name is
20449 * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
20450 * property to the original name.
20451 * @param {string} value Value to set the attribute to. The value can be an interpolated string.
20457 * Closure compiler type information
20460 function nodesetLinkingFn(
20461 /* angular.Scope */ scope,
20462 /* NodeList */ nodeList,
20463 /* Element */ rootElement,
20464 /* function(Function) */ boundTranscludeFn
20467 function directiveLinkingFn(
20468 /* nodesetLinkingFn */ nodesetLinkingFn,
20469 /* angular.Scope */ scope,
20471 /* Element */ rootElement,
20472 /* function(Function) */ boundTranscludeFn
20475 function tokenDifference(str1, str2) {
20477 tokens1 = str1.split(/\s+/),
20478 tokens2 = str2.split(/\s+/);
20481 for (var i = 0; i < tokens1.length; i++) {
20482 var token = tokens1[i];
20483 for (var j = 0; j < tokens2.length; j++) {
20484 if (token === tokens2[j]) continue outer;
20486 values += (values.length > 0 ? ' ' : '') + token;
20491 function removeComments(jqNodes) {
20492 jqNodes = jqLite(jqNodes);
20493 var i = jqNodes.length;
20500 var node = jqNodes[i];
20501 if (node.nodeType === NODE_TYPE_COMMENT ||
20502 (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) {
20503 splice.call(jqNodes, i, 1);
20509 var $controllerMinErr = minErr('$controller');
20512 var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
20513 function identifierForController(controller, ident) {
20514 if (ident && isString(ident)) return ident;
20515 if (isString(controller)) {
20516 var match = CNTRL_REG.exec(controller);
20517 if (match) return match[3];
20524 * @name $controllerProvider
20528 * The {@link ng.$controller $controller service} is used by Angular to create new
20531 * This provider allows controller registration via the
20532 * {@link ng.$controllerProvider#register register} method.
20534 function $ControllerProvider() {
20535 var controllers = {},
20540 * @name $controllerProvider#has
20541 * @param {string} name Controller name to check.
20543 this.has = function(name) {
20544 return controllers.hasOwnProperty(name);
20549 * @name $controllerProvider#register
20550 * @param {string|Object} name Controller name, or an object map of controllers where the keys are
20551 * the names and the values are the constructors.
20552 * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
20553 * annotations in the array notation).
20555 this.register = function(name, constructor) {
20556 assertNotHasOwnProperty(name, 'controller');
20557 if (isObject(name)) {
20558 extend(controllers, name);
20560 controllers[name] = constructor;
20566 * @name $controllerProvider#allowGlobals
20569 * sinceVersion="v1.3.0"
20570 * removeVersion="v1.7.0"
20571 * This method of finding controllers has been deprecated.
20573 * @description If called, allows `$controller` to find controller constructors on `window` *
20575 this.allowGlobals = function() {
20580 this.$get = ['$injector', '$window', function($injector, $window) {
20584 * @name $controller
20585 * @requires $injector
20587 * @param {Function|string} constructor If called with a function then it's considered to be the
20588 * controller constructor function. Otherwise it's considered to be a string which is used
20589 * to retrieve the controller constructor using the following steps:
20591 * * check if a controller with given name is registered via `$controllerProvider`
20592 * * check if evaluating the string on the current scope returns a constructor
20593 * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
20594 * `window` object (not recommended)
20596 * The string can use the `controller as property` syntax, where the controller instance is published
20597 * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
20598 * to work correctly.
20600 * @param {Object} locals Injection locals for Controller.
20601 * @return {Object} Instance of given controller.
20604 * `$controller` service is responsible for instantiating controllers.
20606 * It's just a simple call to {@link auto.$injector $injector}, but extracted into
20607 * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
20609 return function $controller(expression, locals, later, ident) {
20611 // param `later` --- indicates that the controller's constructor is invoked at a later time.
20612 // If true, $controller will allocate the object with the correct
20613 // prototype chain, but will not invoke the controller until a returned
20614 // callback is invoked.
20615 // param `ident` --- An optional label which overrides the label parsed from the controller
20616 // expression, if any.
20617 var instance, match, constructor, identifier;
20618 later = later === true;
20619 if (ident && isString(ident)) {
20620 identifier = ident;
20623 if (isString(expression)) {
20624 match = expression.match(CNTRL_REG);
20626 throw $controllerMinErr('ctrlfmt',
20627 'Badly formed controller string \'{0}\'. ' +
20628 'Must match `__name__ as __id__` or `__name__`.', expression);
20630 constructor = match[1];
20631 identifier = identifier || match[3];
20632 expression = controllers.hasOwnProperty(constructor)
20633 ? controllers[constructor]
20634 : getter(locals.$scope, constructor, true) ||
20635 (globals ? getter($window, constructor, true) : undefined);
20638 throw $controllerMinErr('ctrlreg',
20639 'The controller with the name \'{0}\' is not registered.', constructor);
20642 assertArgFn(expression, constructor, true);
20646 // Instantiate controller later:
20647 // This machinery is used to create an instance of the object before calling the
20648 // controller's constructor itself.
20650 // This allows properties to be added to the controller before the constructor is
20651 // invoked. Primarily, this is used for isolate scope bindings in $compile.
20653 // This feature is not intended for use by applications, and is thus not documented
20655 // Object creation: http://jsperf.com/create-constructor/2
20656 var controllerPrototype = (isArray(expression) ?
20657 expression[expression.length - 1] : expression).prototype;
20658 instance = Object.create(controllerPrototype || null);
20661 addIdentifier(locals, identifier, instance, constructor || expression.name);
20664 return extend(function $controllerInit() {
20665 var result = $injector.invoke(expression, instance, locals, constructor);
20666 if (result !== instance && (isObject(result) || isFunction(result))) {
20669 // If result changed, re-assign controllerAs value to scope.
20670 addIdentifier(locals, identifier, instance, constructor || expression.name);
20675 instance: instance,
20676 identifier: identifier
20680 instance = $injector.instantiate(expression, locals, constructor);
20683 addIdentifier(locals, identifier, instance, constructor || expression.name);
20689 function addIdentifier(locals, identifier, instance, name) {
20690 if (!(locals && isObject(locals.$scope))) {
20691 throw minErr('$controller')('noscp',
20692 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.',
20696 locals.$scope[identifier] = instance;
20704 * @requires $window
20708 * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
20711 <example module="documentExample" name="document">
20712 <file name="index.html">
20713 <div ng-controller="ExampleController">
20714 <p>$document title: <b ng-bind="title"></b></p>
20715 <p>window.document title: <b ng-bind="windowTitle"></b></p>
20718 <file name="script.js">
20719 angular.module('documentExample', [])
20720 .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
20721 $scope.title = $document[0].title;
20722 $scope.windowTitle = angular.element(window.document)[0].title;
20727 function $DocumentProvider() {
20728 this.$get = ['$window', function(window) {
20729 return jqLite(window.document);
20735 * @name $exceptionHandler
20736 * @requires ng.$log
20740 * Any uncaught exception in angular expressions is delegated to this service.
20741 * The default implementation simply delegates to `$log.error` which logs it into
20742 * the browser console.
20744 * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
20745 * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
20749 * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
20750 * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
20751 * of `$log.error()`.
20755 * module('exceptionOverwrite', []).
20756 * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
20757 * return function myExceptionHandler(exception, cause) {
20758 * logErrorsToBackend(exception, cause);
20759 * $log.warn(exception, cause);
20765 * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
20766 * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
20767 * (unless executed during a digest).
20769 * If you wish, you can manually delegate exceptions, e.g.
20770 * `try { ... } catch(e) { $exceptionHandler(e); }`
20772 * @param {Error} exception Exception associated with the error.
20773 * @param {string=} cause Optional information about the context in which
20774 * the error was thrown.
20777 function $ExceptionHandlerProvider() {
20778 this.$get = ['$log', function($log) {
20779 return function(exception, cause) {
20780 $log.error.apply($log, arguments);
20785 var $$ForceReflowProvider = /** @this */ function() {
20786 this.$get = ['$document', function($document) {
20787 return function(domNode) {
20788 //the line below will force the browser to perform a repaint so
20789 //that all the animated elements within the animation frame will
20790 //be properly updated and drawn on screen. This is required to
20791 //ensure that the preparation animation is properly flushed so that
20792 //the active state picks up from there. DO NOT REMOVE THIS LINE.
20793 //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
20794 //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
20795 //WILL TAKE YEARS AWAY FROM YOUR LIFE.
20797 if (!domNode.nodeType && domNode instanceof jqLite) {
20798 domNode = domNode[0];
20801 domNode = $document[0].body;
20803 return domNode.offsetWidth + 1;
20808 var APPLICATION_JSON = 'application/json';
20809 var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
20810 var JSON_START = /^\[|^\{(?!\{)/;
20815 var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/;
20816 var $httpMinErr = minErr('$http');
20817 var $httpMinErrLegacyFn = function(method) {
20818 return function() {
20819 throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
20823 function serializeValue(v) {
20825 return isDate(v) ? v.toISOString() : toJson(v);
20832 function $HttpParamSerializerProvider() {
20835 * @name $httpParamSerializer
20838 * Default {@link $http `$http`} params serializer that converts objects to strings
20839 * according to the following rules:
20841 * * `{'foo': 'bar'}` results in `foo=bar`
20842 * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
20843 * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
20844 * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
20846 * Note that serializer will sort the request parameters alphabetically.
20849 this.$get = function() {
20850 return function ngParamSerializer(params) {
20851 if (!params) return '';
20853 forEachSorted(params, function(value, key) {
20854 if (value === null || isUndefined(value)) return;
20855 if (isArray(value)) {
20856 forEach(value, function(v) {
20857 parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
20860 parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
20864 return parts.join('&');
20870 function $HttpParamSerializerJQLikeProvider() {
20873 * @name $httpParamSerializerJQLike
20877 * Alternative {@link $http `$http`} params serializer that follows
20878 * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
20879 * The serializer will also sort the params alphabetically.
20881 * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
20887 * params: myParams,
20888 * paramSerializer: '$httpParamSerializerJQLike'
20892 * It is also possible to set it as the default `paramSerializer` in the
20893 * {@link $httpProvider#defaults `$httpProvider`}.
20895 * Additionally, you can inject the serializer and use it explicitly, for example to serialize
20896 * form data for submission:
20899 * .controller(function($http, $httpParamSerializerJQLike) {
20905 * data: $httpParamSerializerJQLike(myData),
20907 * 'Content-Type': 'application/x-www-form-urlencoded'
20915 this.$get = function() {
20916 return function jQueryLikeParamSerializer(params) {
20917 if (!params) return '';
20919 serialize(params, '', true);
20920 return parts.join('&');
20922 function serialize(toSerialize, prefix, topLevel) {
20923 if (toSerialize === null || isUndefined(toSerialize)) return;
20924 if (isArray(toSerialize)) {
20925 forEach(toSerialize, function(value, index) {
20926 serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
20928 } else if (isObject(toSerialize) && !isDate(toSerialize)) {
20929 forEachSorted(toSerialize, function(value, key) {
20930 serialize(value, prefix +
20931 (topLevel ? '' : '[') +
20933 (topLevel ? '' : ']'));
20936 parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
20943 function defaultHttpResponseTransform(data, headers) {
20944 if (isString(data)) {
20945 // Strip json vulnerability protection prefix and trim whitespace
20946 var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
20949 var contentType = headers('Content-Type');
20950 if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
20951 data = fromJson(tempData);
20959 function isJsonLike(str) {
20960 var jsonStart = str.match(JSON_START);
20961 return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
20965 * Parse headers into key value object
20967 * @param {string} headers Raw headers as a string
20968 * @returns {Object} Parsed headers as key value object
20970 function parseHeaders(headers) {
20971 var parsed = createMap(), i;
20973 function fillInParsed(key, val) {
20975 parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
20979 if (isString(headers)) {
20980 forEach(headers.split('\n'), function(line) {
20981 i = line.indexOf(':');
20982 fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
20984 } else if (isObject(headers)) {
20985 forEach(headers, function(headerVal, headerKey) {
20986 fillInParsed(lowercase(headerKey), trim(headerVal));
20995 * Returns a function that provides access to parsed headers.
20997 * Headers are lazy parsed when first requested.
20998 * @see parseHeaders
21000 * @param {(string|Object)} headers Headers to provide access to.
21001 * @returns {function(string=)} Returns a getter function which if called with:
21003 * - if called with an argument returns a single header value or null
21004 * - if called with no arguments returns an object containing all headers.
21006 function headersGetter(headers) {
21009 return function(name) {
21010 if (!headersObj) headersObj = parseHeaders(headers);
21013 var value = headersObj[lowercase(name)];
21014 if (value === undefined) {
21026 * Chain all given functions
21028 * This function is used for both request and response transforming
21030 * @param {*} data Data to transform.
21031 * @param {function(string=)} headers HTTP headers getter fn.
21032 * @param {number} status HTTP status code of the response.
21033 * @param {(Function|Array.<Function>)} fns Function or an array of functions.
21034 * @returns {*} Transformed data.
21036 function transformData(data, headers, status, fns) {
21037 if (isFunction(fns)) {
21038 return fns(data, headers, status);
21041 forEach(fns, function(fn) {
21042 data = fn(data, headers, status);
21049 function isSuccess(status) {
21050 return 200 <= status && status < 300;
21056 * @name $httpProvider
21060 * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
21062 function $HttpProvider() {
21065 * @name $httpProvider#defaults
21068 * Object containing default values for all {@link ng.$http $http} requests.
21070 * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
21071 * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
21072 * by default. See {@link $http#caching $http Caching} for more information.
21074 * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
21075 * Defaults value is `'XSRF-TOKEN'`.
21077 * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
21078 * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
21080 * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
21081 * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
21082 * setting default headers.
21083 * - **`defaults.headers.common`**
21084 * - **`defaults.headers.post`**
21085 * - **`defaults.headers.put`**
21086 * - **`defaults.headers.patch`**
21089 * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
21090 * used to the prepare string representation of request parameters (specified as an object).
21091 * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
21092 * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
21095 var defaults = this.defaults = {
21096 // transform incoming response data
21097 transformResponse: [defaultHttpResponseTransform],
21099 // transform outgoing request data
21100 transformRequest: [function(d) {
21101 return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
21107 'Accept': 'application/json, text/plain, */*'
21109 post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
21110 put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
21111 patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
21114 xsrfCookieName: 'XSRF-TOKEN',
21115 xsrfHeaderName: 'X-XSRF-TOKEN',
21117 paramSerializer: '$httpParamSerializer'
21120 var useApplyAsync = false;
21123 * @name $httpProvider#useApplyAsync
21126 * Configure $http service to combine processing of multiple http responses received at around
21127 * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
21128 * significant performance improvement for bigger applications that make many HTTP requests
21129 * concurrently (common during application bootstrap).
21131 * Defaults to false. If no value is specified, returns the current configured value.
21133 * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
21134 * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
21135 * to load and share the same digest cycle.
21137 * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
21138 * otherwise, returns the current configured value.
21140 this.useApplyAsync = function(value) {
21141 if (isDefined(value)) {
21142 useApplyAsync = !!value;
21145 return useApplyAsync;
21148 var useLegacyPromise = true;
21151 * @name $httpProvider#useLegacyPromiseExtensions
21155 * sinceVersion="v1.4.4"
21156 * removeVersion="v1.6.0"
21157 * This method will be removed in v1.6.0 along with the legacy promise methods.
21159 * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
21160 * This should be used to make sure that applications work without these methods.
21162 * Defaults to true. If no value is specified, returns the current configured value.
21164 * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
21166 * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
21167 * otherwise, returns the current configured value.
21169 this.useLegacyPromiseExtensions = function(value) {
21170 if (isDefined(value)) {
21171 useLegacyPromise = !!value;
21174 return useLegacyPromise;
21179 * @name $httpProvider#interceptors
21182 * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
21183 * pre-processing of request or postprocessing of responses.
21185 * These service factories are ordered by request, i.e. they are applied in the same order as the
21186 * array, on request, but reverse order, on response.
21188 * {@link ng.$http#interceptors Interceptors detailed info}
21190 var interceptorFactories = this.interceptors = [];
21192 this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
21193 function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
21195 var defaultCache = $cacheFactory('$http');
21198 * Make sure that default param serializer is exposed as a function
21200 defaults.paramSerializer = isString(defaults.paramSerializer) ?
21201 $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
21204 * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
21205 * The reversal is needed so that we can build up the interception chain around the
21208 var reversedInterceptors = [];
21210 forEach(interceptorFactories, function(interceptorFactory) {
21211 reversedInterceptors.unshift(isString(interceptorFactory)
21212 ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
21219 * @requires ng.$httpBackend
21220 * @requires $cacheFactory
21221 * @requires $rootScope
21223 * @requires $injector
21226 * The `$http` service is a core Angular service that facilitates communication with the remote
21227 * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
21228 * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
21230 * For unit testing applications that use `$http` service, see
21231 * {@link ngMock.$httpBackend $httpBackend mock}.
21233 * For a higher level of abstraction, please check out the {@link ngResource.$resource
21234 * $resource} service.
21236 * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
21237 * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
21238 * it is important to familiarize yourself with these APIs and the guarantees they provide.
21242 * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
21243 * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
21246 * // Simple GET request example:
21250 * }).then(function successCallback(response) {
21251 * // this callback will be called asynchronously
21252 * // when the response is available
21253 * }, function errorCallback(response) {
21254 * // called asynchronously if an error occurs
21255 * // or server returns response with an error status.
21259 * The response object has these properties:
21261 * - **data** – `{string|Object}` – The response body transformed with the transform
21263 * - **status** – `{number}` – HTTP status code of the response.
21264 * - **headers** – `{function([headerName])}` – Header getter function.
21265 * - **config** – `{Object}` – The configuration object that was used to generate the request.
21266 * - **statusText** – `{string}` – HTTP status text of the response.
21268 * A response status code between 200 and 299 is considered a success status and will result in
21269 * the success callback being called. Any response status code outside of that range is
21270 * considered an error status and will result in the error callback being called.
21271 * Also, status codes less than -1 are normalized to zero. -1 usually means the request was
21272 * aborted, e.g. using a `config.timeout`.
21273 * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning
21274 * that the outcome (success or error) will be determined by the final response status code.
21277 * ## Shortcut methods
21279 * Shortcut methods are also available. All shortcut methods require passing in the URL, and
21280 * request data must be passed in for POST/PUT requests. An optional config can be passed as the
21284 * $http.get('/someUrl', config).then(successCallback, errorCallback);
21285 * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
21288 * Complete list of shortcut methods:
21290 * - {@link ng.$http#get $http.get}
21291 * - {@link ng.$http#head $http.head}
21292 * - {@link ng.$http#post $http.post}
21293 * - {@link ng.$http#put $http.put}
21294 * - {@link ng.$http#delete $http.delete}
21295 * - {@link ng.$http#jsonp $http.jsonp}
21296 * - {@link ng.$http#patch $http.patch}
21299 * ## Writing Unit Tests that use $http
21300 * When unit testing (using {@link ngMock ngMock}), it is necessary to call
21301 * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
21302 * request using trained responses.
21305 * $httpBackend.expectGET(...);
21307 * $httpBackend.flush();
21310 * ## Deprecation Notice
21311 * <div class="alert alert-danger">
21312 * The `$http` legacy promise methods `success` and `error` have been deprecated and will be
21313 * removed in v1.6.0.
21314 * Use the standard `then` method instead.
21315 * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
21316 * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
21319 * ## Setting HTTP Headers
21321 * The $http service will automatically add certain HTTP headers to all requests. These defaults
21322 * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
21323 * object, which currently contains this default configuration:
21325 * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
21326 * - <code>Accept: application/json, text/plain, \*/\*</code>
21327 * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
21328 * - `Content-Type: application/json`
21329 * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
21330 * - `Content-Type: application/json`
21332 * To add or overwrite these defaults, simply add or remove a property from these configuration
21333 * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
21334 * with the lowercased HTTP method name as the key, e.g.
21335 * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
21337 * The defaults can also be set at runtime via the `$http.defaults` object in the same
21338 * fashion. For example:
21341 * module.run(function($http) {
21342 * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
21346 * In addition, you can supply a `headers` property in the config object passed when
21347 * calling `$http(config)`, which overrides the defaults without changing them globally.
21349 * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
21350 * Use the `headers` property, setting the desired header to `undefined`. For example:
21355 * url: 'http://example.com',
21357 * 'Content-Type': undefined
21359 * data: { test: 'test' }
21362 * $http(req).then(function(){...}, function(){...});
21365 * ## Transforming Requests and Responses
21367 * Both requests and responses can be transformed using transformation functions: `transformRequest`
21368 * and `transformResponse`. These properties can be a single function that returns
21369 * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
21370 * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
21372 * <div class="alert alert-warning">
21373 * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
21374 * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
21375 * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
21376 * function will be reflected on the scope and in any templates where the object is data-bound.
21377 * To prevent this, transform functions should have no side-effects.
21378 * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
21381 * ### Default Transformations
21383 * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
21384 * `defaults.transformResponse` properties. If a request does not provide its own transformations
21385 * then these will be applied.
21387 * You can augment or replace the default transformations by modifying these properties by adding to or
21388 * replacing the array.
21390 * Angular provides the following default transformations:
21392 * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
21394 * - If the `data` property of the request configuration object contains an object, serialize it
21395 * into JSON format.
21397 * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
21399 * - If XSRF prefix is detected, strip it (see Security Considerations section below).
21400 * - If JSON response is detected, deserialize it using a JSON parser.
21403 * ### Overriding the Default Transformations Per Request
21405 * If you wish to override the request/response transformations only for a single request then provide
21406 * `transformRequest` and/or `transformResponse` properties on the configuration object passed
21409 * Note that if you provide these properties on the config object the default transformations will be
21410 * overwritten. If you wish to augment the default transformations then you must include them in your
21411 * local transformation array.
21413 * The following code demonstrates adding a new response transformation to be run after the default response
21414 * transformations have been run.
21417 * function appendTransform(defaults, transform) {
21419 * // We can't guarantee that the default transformation is an array
21420 * defaults = angular.isArray(defaults) ? defaults : [defaults];
21422 * // Append the new transformation to the defaults
21423 * return defaults.concat(transform);
21429 * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
21430 * return doTransform(value);
21438 * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
21439 * set the config.cache value or the default cache value to TRUE or to a cache object (created
21440 * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
21441 * precedence over the default cache value.
21444 * * cache all responses - set the default cache value to TRUE or to a cache object
21445 * * cache a specific response - set config.cache value to TRUE or to a cache object
21447 * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
21448 * then the default `$cacheFactory("$http")` object is used.
21450 * The default cache value can be set by updating the
21451 * {@link ng.$http#defaults `$http.defaults.cache`} property or the
21452 * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
21454 * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
21455 * the relevant cache object. The next time the same request is made, the response is returned
21456 * from the cache without sending a request to the server.
21460 * * Only GET and JSONP requests are cached.
21461 * * The cache key is the request URL including search parameters; headers are not considered.
21462 * * Cached responses are returned asynchronously, in the same way as responses from the server.
21463 * * If multiple identical requests are made using the same cache, which is not yet populated,
21464 * one request will be made to the server and remaining requests will return the same response.
21465 * * A cache-control header on the response does not affect if or how responses are cached.
21470 * Before you start creating interceptors, be sure to understand the
21471 * {@link ng.$q $q and deferred/promise APIs}.
21473 * For purposes of global error handling, authentication, or any kind of synchronous or
21474 * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
21475 * able to intercept requests before they are handed to the server and
21476 * responses before they are handed over to the application code that
21477 * initiated these requests. The interceptors leverage the {@link ng.$q
21478 * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
21480 * The interceptors are service factories that are registered with the `$httpProvider` by
21481 * adding them to the `$httpProvider.interceptors` array. The factory is called and
21482 * injected with dependencies (if specified) and returns the interceptor.
21484 * There are two kinds of interceptors (and two kinds of rejection interceptors):
21486 * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
21487 * modify the `config` object or create a new one. The function needs to return the `config`
21488 * object directly, or a promise containing the `config` or a new `config` object.
21489 * * `requestError`: interceptor gets called when a previous interceptor threw an error or
21490 * resolved with a rejection.
21491 * * `response`: interceptors get called with http `response` object. The function is free to
21492 * modify the `response` object or create a new one. The function needs to return the `response`
21493 * object directly, or as a promise containing the `response` or a new `response` object.
21494 * * `responseError`: interceptor gets called when a previous interceptor threw an error or
21495 * resolved with a rejection.
21499 * // register the interceptor as a service
21500 * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
21502 * // optional method
21503 * 'request': function(config) {
21504 * // do something on success
21508 * // optional method
21509 * 'requestError': function(rejection) {
21510 * // do something on error
21511 * if (canRecover(rejection)) {
21512 * return responseOrNewPromise
21514 * return $q.reject(rejection);
21519 * // optional method
21520 * 'response': function(response) {
21521 * // do something on success
21525 * // optional method
21526 * 'responseError': function(rejection) {
21527 * // do something on error
21528 * if (canRecover(rejection)) {
21529 * return responseOrNewPromise
21531 * return $q.reject(rejection);
21536 * $httpProvider.interceptors.push('myHttpInterceptor');
21539 * // alternatively, register the interceptor via an anonymous factory
21540 * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
21542 * 'request': function(config) {
21546 * 'response': function(response) {
21553 * ## Security Considerations
21555 * When designing web applications, consider security threats from:
21557 * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
21558 * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
21560 * Both server and the client must cooperate in order to eliminate these threats. Angular comes
21561 * pre-configured with strategies that address these issues, but for this to work backend server
21562 * cooperation is required.
21564 * ### JSON Vulnerability Protection
21566 * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
21567 * allows third party website to turn your JSON resource URL into
21568 * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
21569 * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
21570 * Angular will automatically strip the prefix before processing it as JSON.
21572 * For example if your server needs to return:
21577 * which is vulnerable to attack, your server can return:
21583 * Angular will strip the prefix, before processing the JSON.
21586 * ### Cross Site Request Forgery (XSRF) Protection
21588 * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
21589 * which the attacker can trick an authenticated user into unknowingly executing actions on your
21590 * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
21591 * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
21592 * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
21593 * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
21594 * The header will not be set for cross-domain requests.
21596 * To take advantage of this, your server needs to set a token in a JavaScript readable session
21597 * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
21598 * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
21599 * that only JavaScript running on your domain could have sent the request. The token must be
21600 * unique for each user and must be verifiable by the server (to prevent the JavaScript from
21601 * making up its own tokens). We recommend that the token is a digest of your site's
21602 * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))
21603 * for added security.
21605 * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
21606 * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
21607 * or the per-request config object.
21609 * In order to prevent collisions in environments where multiple Angular apps share the
21610 * same domain or subdomain, we recommend that each application uses unique cookie name.
21612 * @param {object} config Object describing the request to be made and how it should be
21613 * processed. The object has following properties:
21615 * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
21616 * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
21617 * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
21618 * with the `paramSerializer` and appended as GET parameters.
21619 * - **data** – `{string|Object}` – Data to be sent as the request message data.
21620 * - **headers** – `{Object}` – Map of strings or functions which return strings representing
21621 * HTTP headers to send to the server. If the return value of a function is null, the
21622 * header will not be sent. Functions accept a config object as an argument.
21623 * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.
21624 * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.
21625 * The handler will be called in the context of a `$apply` block.
21626 * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload
21627 * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.
21628 * The handler will be called in the context of a `$apply` block.
21629 * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
21630 * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
21631 * - **transformRequest** –
21632 * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
21633 * transform function or an array of such functions. The transform function takes the http
21634 * request body and headers and returns its transformed (typically serialized) version.
21635 * See {@link ng.$http#overriding-the-default-transformations-per-request
21636 * Overriding the Default Transformations}
21637 * - **transformResponse** –
21638 * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
21639 * transform function or an array of such functions. The transform function takes the http
21640 * response body, headers and status and returns its transformed (typically deserialized) version.
21641 * See {@link ng.$http#overriding-the-default-transformations-per-request
21642 * Overriding the Default Transformations}
21643 * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
21644 * prepare the string representation of request parameters (specified as an object).
21645 * If specified as string, it is interpreted as function registered with the
21646 * {@link $injector $injector}, which means you can create your own serializer
21647 * by registering it as a {@link auto.$provide#service service}.
21648 * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
21649 * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
21650 * - **cache** – `{boolean|Object}` – A boolean value or object created with
21651 * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
21652 * See {@link $http#caching $http Caching} for more information.
21653 * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
21654 * that should abort the request when resolved.
21655 * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
21656 * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
21657 * for more information.
21658 * - **responseType** - `{string}` - see
21659 * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
21661 * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
21662 * when the request succeeds or fails.
21665 * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
21666 * requests. This is primarily meant to be used for debugging purposes.
21670 <example module="httpExample" name="http-service">
21671 <file name="index.html">
21672 <div ng-controller="FetchController">
21673 <select ng-model="method" aria-label="Request method">
21674 <option>GET</option>
21675 <option>JSONP</option>
21677 <input type="text" ng-model="url" size="80" aria-label="URL" />
21678 <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
21679 <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
21680 <button id="samplejsonpbtn"
21681 ng-click="updateModel('JSONP',
21682 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
21685 <button id="invalidjsonpbtn"
21686 ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
21689 <pre>http status code: {{status}}</pre>
21690 <pre>http response data: {{data}}</pre>
21693 <file name="script.js">
21694 angular.module('httpExample', [])
21695 .controller('FetchController', ['$scope', '$http', '$templateCache',
21696 function($scope, $http, $templateCache) {
21697 $scope.method = 'GET';
21698 $scope.url = 'http-hello.html';
21700 $scope.fetch = function() {
21701 $scope.code = null;
21702 $scope.response = null;
21704 $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
21705 then(function(response) {
21706 $scope.status = response.status;
21707 $scope.data = response.data;
21708 }, function(response) {
21709 $scope.data = response.data || 'Request failed';
21710 $scope.status = response.status;
21714 $scope.updateModel = function(method, url) {
21715 $scope.method = method;
21720 <file name="http-hello.html">
21723 <file name="protractor.js" type="protractor">
21724 var status = element(by.binding('status'));
21725 var data = element(by.binding('data'));
21726 var fetchBtn = element(by.id('fetchbtn'));
21727 var sampleGetBtn = element(by.id('samplegetbtn'));
21728 var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
21730 it('should make an xhr GET request', function() {
21731 sampleGetBtn.click();
21733 expect(status.getText()).toMatch('200');
21734 expect(data.getText()).toMatch(/Hello, \$http!/);
21737 // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
21738 // it('should make a JSONP request to angularjs.org', function() {
21739 // var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
21740 // sampleJsonpBtn.click();
21741 // fetchBtn.click();
21742 // expect(status.getText()).toMatch('200');
21743 // expect(data.getText()).toMatch(/Super Hero!/);
21746 it('should make JSONP request to invalid URL and invoke the error handler',
21748 invalidJsonpBtn.click();
21750 expect(status.getText()).toMatch('0');
21751 expect(data.getText()).toMatch('Request failed');
21756 function $http(requestConfig) {
21758 if (!isObject(requestConfig)) {
21759 throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
21762 if (!isString(requestConfig.url)) {
21763 throw minErr('$http')('badreq', 'Http request configuration url must be a string. Received: {0}', requestConfig.url);
21766 var config = extend({
21768 transformRequest: defaults.transformRequest,
21769 transformResponse: defaults.transformResponse,
21770 paramSerializer: defaults.paramSerializer
21773 config.headers = mergeHeaders(requestConfig);
21774 config.method = uppercase(config.method);
21775 config.paramSerializer = isString(config.paramSerializer) ?
21776 $injector.get(config.paramSerializer) : config.paramSerializer;
21778 var requestInterceptors = [];
21779 var responseInterceptors = [];
21780 var promise = $q.when(config);
21782 // apply interceptors
21783 forEach(reversedInterceptors, function(interceptor) {
21784 if (interceptor.request || interceptor.requestError) {
21785 requestInterceptors.unshift(interceptor.request, interceptor.requestError);
21787 if (interceptor.response || interceptor.responseError) {
21788 responseInterceptors.push(interceptor.response, interceptor.responseError);
21792 promise = chainInterceptors(promise, requestInterceptors);
21793 promise = promise.then(serverRequest);
21794 promise = chainInterceptors(promise, responseInterceptors);
21796 if (useLegacyPromise) {
21797 promise.success = function(fn) {
21798 assertArgFn(fn, 'fn');
21800 promise.then(function(response) {
21801 fn(response.data, response.status, response.headers, config);
21806 promise.error = function(fn) {
21807 assertArgFn(fn, 'fn');
21809 promise.then(null, function(response) {
21810 fn(response.data, response.status, response.headers, config);
21815 promise.success = $httpMinErrLegacyFn('success');
21816 promise.error = $httpMinErrLegacyFn('error');
21822 function chainInterceptors(promise, interceptors) {
21823 for (var i = 0, ii = interceptors.length; i < ii;) {
21824 var thenFn = interceptors[i++];
21825 var rejectFn = interceptors[i++];
21827 promise = promise.then(thenFn, rejectFn);
21830 interceptors.length = 0;
21835 function executeHeaderFns(headers, config) {
21836 var headerContent, processedHeaders = {};
21838 forEach(headers, function(headerFn, header) {
21839 if (isFunction(headerFn)) {
21840 headerContent = headerFn(config);
21841 if (headerContent != null) {
21842 processedHeaders[header] = headerContent;
21845 processedHeaders[header] = headerFn;
21849 return processedHeaders;
21852 function mergeHeaders(config) {
21853 var defHeaders = defaults.headers,
21854 reqHeaders = extend({}, config.headers),
21855 defHeaderName, lowercaseDefHeaderName, reqHeaderName;
21857 defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
21859 // using for-in instead of forEach to avoid unnecessary iteration after header has been found
21860 defaultHeadersIteration:
21861 for (defHeaderName in defHeaders) {
21862 lowercaseDefHeaderName = lowercase(defHeaderName);
21864 for (reqHeaderName in reqHeaders) {
21865 if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
21866 continue defaultHeadersIteration;
21870 reqHeaders[defHeaderName] = defHeaders[defHeaderName];
21873 // execute if header value is a function for merged headers
21874 return executeHeaderFns(reqHeaders, shallowCopy(config));
21877 function serverRequest(config) {
21878 var headers = config.headers;
21879 var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
21881 // strip content-type if data is undefined
21882 if (isUndefined(reqData)) {
21883 forEach(headers, function(value, header) {
21884 if (lowercase(header) === 'content-type') {
21885 delete headers[header];
21890 if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
21891 config.withCredentials = defaults.withCredentials;
21895 return sendReq(config, reqData).then(transformResponse, transformResponse);
21898 function transformResponse(response) {
21899 // make a copy since the response must be cacheable
21900 var resp = extend({}, response);
21901 resp.data = transformData(response.data, response.headers, response.status,
21902 config.transformResponse);
21903 return (isSuccess(response.status))
21909 $http.pendingRequests = [];
21916 * Shortcut method to perform `GET` request.
21918 * @param {string} url Relative or absolute URL specifying the destination of the request
21919 * @param {Object=} config Optional configuration object
21920 * @returns {HttpPromise} Future object
21925 * @name $http#delete
21928 * Shortcut method to perform `DELETE` request.
21930 * @param {string} url Relative or absolute URL specifying the destination of the request
21931 * @param {Object=} config Optional configuration object
21932 * @returns {HttpPromise} Future object
21940 * Shortcut method to perform `HEAD` request.
21942 * @param {string} url Relative or absolute URL specifying the destination of the request
21943 * @param {Object=} config Optional configuration object
21944 * @returns {HttpPromise} Future object
21949 * @name $http#jsonp
21952 * Shortcut method to perform `JSONP` request.
21953 * If you would like to customize where and how the callbacks are stored then try overriding
21954 * or decorating the {@link $jsonpCallbacks} service.
21956 * @param {string} url Relative or absolute URL specifying the destination of the request.
21957 * The name of the callback should be the string `JSON_CALLBACK`.
21958 * @param {Object=} config Optional configuration object
21959 * @returns {HttpPromise} Future object
21961 createShortMethods('get', 'delete', 'head', 'jsonp');
21968 * Shortcut method to perform `POST` request.
21970 * @param {string} url Relative or absolute URL specifying the destination of the request
21971 * @param {*} data Request content
21972 * @param {Object=} config Optional configuration object
21973 * @returns {HttpPromise} Future object
21981 * Shortcut method to perform `PUT` request.
21983 * @param {string} url Relative or absolute URL specifying the destination of the request
21984 * @param {*} data Request content
21985 * @param {Object=} config Optional configuration object
21986 * @returns {HttpPromise} Future object
21991 * @name $http#patch
21994 * Shortcut method to perform `PATCH` request.
21996 * @param {string} url Relative or absolute URL specifying the destination of the request
21997 * @param {*} data Request content
21998 * @param {Object=} config Optional configuration object
21999 * @returns {HttpPromise} Future object
22001 createShortMethodsWithData('post', 'put', 'patch');
22005 * @name $http#defaults
22008 * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
22009 * default headers, withCredentials as well as request and response transformations.
22011 * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
22013 $http.defaults = defaults;
22019 function createShortMethods(names) {
22020 forEach(arguments, function(name) {
22021 $http[name] = function(url, config) {
22022 return $http(extend({}, config || {}, {
22031 function createShortMethodsWithData(name) {
22032 forEach(arguments, function(name) {
22033 $http[name] = function(url, data, config) {
22034 return $http(extend({}, config || {}, {
22045 * Makes the request.
22047 * !!! ACCESSES CLOSURE VARS:
22048 * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
22050 function sendReq(config, reqData) {
22051 var deferred = $q.defer(),
22052 promise = deferred.promise,
22055 reqHeaders = config.headers,
22056 url = buildUrl(config.url, config.paramSerializer(config.params));
22058 $http.pendingRequests.push(config);
22059 promise.then(removePendingReq, removePendingReq);
22062 if ((config.cache || defaults.cache) && config.cache !== false &&
22063 (config.method === 'GET' || config.method === 'JSONP')) {
22064 cache = isObject(config.cache) ? config.cache
22065 : isObject(defaults.cache) ? defaults.cache
22070 cachedResp = cache.get(url);
22071 if (isDefined(cachedResp)) {
22072 if (isPromiseLike(cachedResp)) {
22073 // cached request has already been sent, but there is no response yet
22074 cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
22076 // serving from cache
22077 if (isArray(cachedResp)) {
22078 resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
22080 resolvePromise(cachedResp, 200, {}, 'OK');
22084 // put the promise for the non-transformed response into cache as a placeholder
22085 cache.put(url, promise);
22090 // if we won't have the response in cache, set the xsrf headers and
22091 // send the request to the backend
22092 if (isUndefined(cachedResp)) {
22093 var xsrfValue = urlIsSameOrigin(config.url)
22094 ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
22097 reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
22100 $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
22101 config.withCredentials, config.responseType,
22102 createApplyHandlers(config.eventHandlers),
22103 createApplyHandlers(config.uploadEventHandlers));
22108 function createApplyHandlers(eventHandlers) {
22109 if (eventHandlers) {
22110 var applyHandlers = {};
22111 forEach(eventHandlers, function(eventHandler, key) {
22112 applyHandlers[key] = function(event) {
22113 if (useApplyAsync) {
22114 $rootScope.$applyAsync(callEventHandler);
22115 } else if ($rootScope.$$phase) {
22116 callEventHandler();
22118 $rootScope.$apply(callEventHandler);
22121 function callEventHandler() {
22122 eventHandler(event);
22126 return applyHandlers;
22132 * Callback registered to $httpBackend():
22133 * - caches the response if desired
22134 * - resolves the raw $http promise
22137 function done(status, response, headersString, statusText) {
22139 if (isSuccess(status)) {
22140 cache.put(url, [status, response, parseHeaders(headersString), statusText]);
22142 // remove promise from the cache
22147 function resolveHttpPromise() {
22148 resolvePromise(response, status, headersString, statusText);
22151 if (useApplyAsync) {
22152 $rootScope.$applyAsync(resolveHttpPromise);
22154 resolveHttpPromise();
22155 if (!$rootScope.$$phase) $rootScope.$apply();
22161 * Resolves the raw $http promise.
22163 function resolvePromise(response, status, headers, statusText) {
22164 //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
22165 status = status >= -1 ? status : 0;
22167 (isSuccess(status) ? deferred.resolve : deferred.reject)({
22170 headers: headersGetter(headers),
22172 statusText: statusText
22176 function resolvePromiseWithResult(result) {
22177 resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
22180 function removePendingReq() {
22181 var idx = $http.pendingRequests.indexOf(config);
22182 if (idx !== -1) $http.pendingRequests.splice(idx, 1);
22187 function buildUrl(url, serializedParams) {
22188 if (serializedParams.length > 0) {
22189 url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
22198 * @name $xhrFactory
22202 * Factory function used to create XMLHttpRequest objects.
22204 * Replace or decorate this service to create your own custom XMLHttpRequest objects.
22207 * angular.module('myApp', [])
22208 * .factory('$xhrFactory', function() {
22209 * return function createXhr(method, url) {
22210 * return new window.XMLHttpRequest({mozSystem: true});
22215 * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
22216 * @param {string} url URL of the request.
22218 function $xhrFactoryProvider() {
22219 this.$get = function() {
22220 return function createXhr() {
22221 return new window.XMLHttpRequest();
22228 * @name $httpBackend
22229 * @requires $jsonpCallbacks
22230 * @requires $document
22231 * @requires $xhrFactory
22235 * HTTP backend used by the {@link ng.$http service} that delegates to
22236 * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
22238 * You should never need to use this service directly, instead use the higher-level abstractions:
22239 * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
22241 * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
22242 * $httpBackend} which can be trained with responses.
22244 function $HttpBackendProvider() {
22245 this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {
22246 return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);
22250 function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
22251 // TODO(vojta): fix the signature
22252 return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
22253 $browser.$$incOutstandingRequestCount();
22254 url = url || $browser.url();
22256 if (lowercase(method) === 'jsonp') {
22257 var callbackPath = callbacks.createCallback(url);
22258 var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {
22259 // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)
22260 var response = (status === 200) && callbacks.getResponse(callbackPath);
22261 completeRequest(callback, status, response, '', text);
22262 callbacks.removeCallback(callbackPath);
22266 var xhr = createXhr(method, url);
22268 xhr.open(method, url, true);
22269 forEach(headers, function(value, key) {
22270 if (isDefined(value)) {
22271 xhr.setRequestHeader(key, value);
22275 xhr.onload = function requestLoaded() {
22276 var statusText = xhr.statusText || '';
22278 // responseText is the old-school way of retrieving response (supported by IE9)
22279 // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
22280 var response = ('response' in xhr) ? xhr.response : xhr.responseText;
22282 // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
22283 var status = xhr.status === 1223 ? 204 : xhr.status;
22285 // fix status code when it is 0 (0 status is undocumented).
22286 // Occurs when accessing file resources or on Android 4.1 stock browser
22287 // while retrieving files from application cache.
22288 if (status === 0) {
22289 status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
22292 completeRequest(callback,
22295 xhr.getAllResponseHeaders(),
22299 var requestError = function() {
22300 // The response is always empty
22301 // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
22302 completeRequest(callback, -1, null, null, '');
22305 xhr.onerror = requestError;
22306 xhr.onabort = requestError;
22307 xhr.ontimeout = requestError;
22309 forEach(eventHandlers, function(value, key) {
22310 xhr.addEventListener(key, value);
22313 forEach(uploadEventHandlers, function(value, key) {
22314 xhr.upload.addEventListener(key, value);
22317 if (withCredentials) {
22318 xhr.withCredentials = true;
22321 if (responseType) {
22323 xhr.responseType = responseType;
22325 // WebKit added support for the json responseType value on 09/03/2013
22326 // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
22327 // known to throw when setting the value "json" as the response type. Other older
22328 // browsers implementing the responseType
22330 // The json response type can be ignored if not supported, because JSON payloads are
22331 // parsed on the client-side regardless.
22332 if (responseType !== 'json') {
22338 xhr.send(isUndefined(post) ? null : post);
22342 var timeoutId = $browserDefer(timeoutRequest, timeout);
22343 } else if (isPromiseLike(timeout)) {
22344 timeout.then(timeoutRequest);
22348 function timeoutRequest() {
22357 function completeRequest(callback, status, response, headersString, statusText) {
22358 // cancel timeout and subsequent timeout promise resolution
22359 if (isDefined(timeoutId)) {
22360 $browserDefer.cancel(timeoutId);
22362 jsonpDone = xhr = null;
22364 callback(status, response, headersString, statusText);
22365 $browser.$$completeOutstandingRequest(noop);
22369 function jsonpReq(url, callbackPath, done) {
22370 url = url.replace('JSON_CALLBACK', callbackPath);
22371 // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
22372 // - fetches local scripts via XHR and evals them
22373 // - adds and immediately removes script elements from the document
22374 var script = rawDocument.createElement('script'), callback = null;
22375 script.type = 'text/javascript';
22377 script.async = true;
22379 callback = function(event) {
22380 removeEventListenerFn(script, 'load', callback);
22381 removeEventListenerFn(script, 'error', callback);
22382 rawDocument.body.removeChild(script);
22385 var text = 'unknown';
22388 if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {
22389 event = { type: 'error' };
22392 status = event.type === 'error' ? 404 : 200;
22396 done(status, text);
22400 addEventListenerFn(script, 'load', callback);
22401 addEventListenerFn(script, 'error', callback);
22402 rawDocument.body.appendChild(script);
22407 var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
22408 $interpolateMinErr.throwNoconcat = function(text) {
22409 throw $interpolateMinErr('noconcat',
22410 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' +
22411 'interpolations that concatenate multiple expressions when a trusted value is ' +
22412 'required. See http://docs.angularjs.org/api/ng.$sce', text);
22415 $interpolateMinErr.interr = function(text, err) {
22416 return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString());
22421 * @name $interpolateProvider
22426 * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
22428 * <div class="alert alert-danger">
22429 * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
22430 * template within a Python Jinja template (or any other template language). Mixing templating
22431 * languages is **very dangerous**. The embedding template language will not safely escape Angular
22432 * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
22437 <example name="custom-interpolation-markup" module="customInterpolationApp">
22438 <file name="index.html">
22440 var customInterpolationApp = angular.module('customInterpolationApp', []);
22442 customInterpolationApp.config(function($interpolateProvider) {
22443 $interpolateProvider.startSymbol('//');
22444 $interpolateProvider.endSymbol('//');
22448 customInterpolationApp.controller('DemoController', function() {
22449 this.label = "This binding is brought you by // interpolation symbols.";
22452 <div ng-controller="DemoController as demo">
22456 <file name="protractor.js" type="protractor">
22457 it('should interpolate binding with custom symbols', function() {
22458 expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
22463 function $InterpolateProvider() {
22464 var startSymbol = '{{';
22465 var endSymbol = '}}';
22469 * @name $interpolateProvider#startSymbol
22471 * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
22473 * @param {string=} value new value to set the starting symbol to.
22474 * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
22476 this.startSymbol = function(value) {
22478 startSymbol = value;
22481 return startSymbol;
22487 * @name $interpolateProvider#endSymbol
22489 * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
22491 * @param {string=} value new value to set the ending symbol to.
22492 * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
22494 this.endSymbol = function(value) {
22504 this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
22505 var startSymbolLength = startSymbol.length,
22506 endSymbolLength = endSymbol.length,
22507 escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
22508 escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
22510 function escape(ch) {
22511 return '\\\\\\' + ch;
22514 function unescapeText(text) {
22515 return text.replace(escapedStartRegexp, startSymbol).
22516 replace(escapedEndRegexp, endSymbol);
22519 function stringify(value) {
22520 if (value == null) { // null || undefined
22523 switch (typeof value) {
22527 value = '' + value;
22530 value = toJson(value);
22536 // TODO: this is the same as the constantWatchDelegate in parse.js
22537 function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
22538 var unwatch = scope.$watch(function constantInterpolateWatch(scope) {
22540 return constantInterp(scope);
22541 }, listener, objectEquality);
22547 * @name $interpolate
22555 * Compiles a string with markup into an interpolation function. This service is used by the
22556 * HTML {@link ng.$compile $compile} service for data binding. See
22557 * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
22558 * interpolation markup.
22562 * var $interpolate = ...; // injected
22563 * var exp = $interpolate('Hello {{name | uppercase}}!');
22564 * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
22567 * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
22568 * `true`, the interpolation function will return `undefined` unless all embedded expressions
22569 * evaluate to a value other than `undefined`.
22572 * var $interpolate = ...; // injected
22573 * var context = {greeting: 'Hello', name: undefined };
22575 * // default "forgiving" mode
22576 * var exp = $interpolate('{{greeting}} {{name}}!');
22577 * expect(exp(context)).toEqual('Hello !');
22579 * // "allOrNothing" mode
22580 * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
22581 * expect(exp(context)).toBeUndefined();
22582 * context.name = 'Angular';
22583 * expect(exp(context)).toEqual('Hello Angular!');
22586 * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
22588 * #### Escaped Interpolation
22589 * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
22590 * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
22591 * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
22594 * This enables web-servers to prevent script injection attacks and defacing attacks, to some
22595 * degree, while also enabling code examples to work without relying on the
22596 * {@link ng.directive:ngNonBindable ngNonBindable} directive.
22598 * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
22599 * replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all
22600 * interpolation start/end markers with their escaped counterparts.**
22602 * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
22603 * output when the $interpolate service processes the text. So, for HTML elements interpolated
22604 * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
22605 * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
22606 * this is typically useful only when user-data is used in rendering a template from the server, or
22607 * when otherwise untrusted data is used by a directive.
22609 * <example name="interpolation">
22610 * <file name="index.html">
22611 * <div ng-init="username='A user'">
22612 * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
22614 * <p><strong>{{username}}</strong> attempts to inject code which will deface the
22615 * application, but fails to accomplish their task, because the server has correctly
22616 * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
22618 * <p>Instead, the result of the attempted script injection is visible, and can be removed
22619 * from the database by an administrator.</p>
22625 * It is currently not possible for an interpolated expression to contain the interpolation end
22626 * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.
22627 * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.
22630 * All directives and components must use the standard `{{` `}}` interpolation symbols
22631 * in their templates. If you change the application interpolation symbols the {@link $compile}
22632 * service will attempt to denormalize the standard symbols to the custom symbols.
22633 * The denormalization process is not clever enough to know not to replace instances of the standard
22634 * symbols where they would not normally be treated as interpolation symbols. For example in the following
22635 * code snippet the closing braces of the literal object will get incorrectly denormalized:
22638 * <div data-context='{"context":{"id":3,"type":"page"}}">
22641 * The workaround is to ensure that such instances are separated by whitespace:
22643 * <div data-context='{"context":{"id":3,"type":"page"} }">
22646 * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
22648 * @param {string} text The text with markup to interpolate.
22649 * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
22650 * embedded expression in order to return an interpolation function. Strings with no
22651 * embedded expression will return null for the interpolation function.
22652 * @param {string=} trustedContext when provided, the returned function passes the interpolated
22653 * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
22654 * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
22655 * provides Strict Contextual Escaping for details.
22656 * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
22657 * unless all embedded expressions evaluate to a value other than `undefined`.
22658 * @returns {function(context)} an interpolation function which is used to compute the
22659 * interpolated string. The function has these parameters:
22661 * - `context`: evaluation context for all expressions embedded in the interpolated text
22663 function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
22664 // Provide a quick exit and simplified result function for text with no interpolation
22665 if (!text.length || text.indexOf(startSymbol) === -1) {
22666 var constantInterp;
22667 if (!mustHaveExpression) {
22668 var unescapedText = unescapeText(text);
22669 constantInterp = valueFn(unescapedText);
22670 constantInterp.exp = text;
22671 constantInterp.expressions = [];
22672 constantInterp.$$watchDelegate = constantWatchDelegate;
22674 return constantInterp;
22677 allOrNothing = !!allOrNothing;
22683 textLength = text.length,
22686 expressionPositions = [];
22688 while (index < textLength) {
22689 if (((startIndex = text.indexOf(startSymbol, index)) !== -1) &&
22690 ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) {
22691 if (index !== startIndex) {
22692 concat.push(unescapeText(text.substring(index, startIndex)));
22694 exp = text.substring(startIndex + startSymbolLength, endIndex);
22695 expressions.push(exp);
22696 parseFns.push($parse(exp, parseStringifyInterceptor));
22697 index = endIndex + endSymbolLength;
22698 expressionPositions.push(concat.length);
22701 // we did not find an interpolation, so we have to add the remainder to the separators array
22702 if (index !== textLength) {
22703 concat.push(unescapeText(text.substring(index)));
22709 // Concatenating expressions makes it hard to reason about whether some combination of
22710 // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
22711 // single expression be used for iframe[src], object[src], etc., we ensure that the value
22712 // that's used is assigned or constructed by some JS code somewhere that is more testable or
22713 // make it obvious that you bound the value to some user controlled value. This helps reduce
22714 // the load when auditing for XSS issues.
22715 if (trustedContext && concat.length > 1) {
22716 $interpolateMinErr.throwNoconcat(text);
22719 if (!mustHaveExpression || expressions.length) {
22720 var compute = function(values) {
22721 for (var i = 0, ii = expressions.length; i < ii; i++) {
22722 if (allOrNothing && isUndefined(values[i])) return;
22723 concat[expressionPositions[i]] = values[i];
22725 return concat.join('');
22728 var getValue = function(value) {
22729 return trustedContext ?
22730 $sce.getTrusted(trustedContext, value) :
22731 $sce.valueOf(value);
22734 return extend(function interpolationFn(context) {
22736 var ii = expressions.length;
22737 var values = new Array(ii);
22740 for (; i < ii; i++) {
22741 values[i] = parseFns[i](context);
22744 return compute(values);
22746 $exceptionHandler($interpolateMinErr.interr(text, err));
22750 // all of these properties are undocumented for now
22751 exp: text, //just for compatibility with regular watchers created via $watch
22752 expressions: expressions,
22753 $$watchDelegate: function(scope, listener) {
22755 return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {
22756 var currValue = compute(values);
22757 if (isFunction(listener)) {
22758 listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
22760 lastValue = currValue;
22766 function parseStringifyInterceptor(value) {
22768 value = getValue(value);
22769 return allOrNothing && !isDefined(value) ? value : stringify(value);
22771 $exceptionHandler($interpolateMinErr.interr(text, err));
22779 * @name $interpolate#startSymbol
22781 * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
22783 * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
22786 * @returns {string} start symbol.
22788 $interpolate.startSymbol = function() {
22789 return startSymbol;
22795 * @name $interpolate#endSymbol
22797 * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
22799 * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
22802 * @returns {string} end symbol.
22804 $interpolate.endSymbol = function() {
22808 return $interpolate;
22813 function $IntervalProvider() {
22814 this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
22815 function($rootScope, $window, $q, $$q, $browser) {
22816 var intervals = {};
22824 * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
22827 * The return value of registering an interval function is a promise. This promise will be
22828 * notified upon each tick of the interval, and will be resolved after `count` iterations, or
22829 * run indefinitely if `count` is not defined. The value of the notification will be the
22830 * number of iterations that have run.
22831 * To cancel an interval, call `$interval.cancel(promise)`.
22833 * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
22834 * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
22837 * <div class="alert alert-warning">
22838 * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
22839 * with them. In particular they are not automatically destroyed when a controller's scope or a
22840 * directive's element are destroyed.
22841 * You should take this into consideration and make sure to always cancel the interval at the
22842 * appropriate moment. See the example below for more details on how and when to do this.
22845 * @param {function()} fn A function that should be called repeatedly. If no additional arguments
22846 * are passed (see below), the function is called with the current iteration count.
22847 * @param {number} delay Number of milliseconds between each function call.
22848 * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
22850 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
22851 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
22852 * @param {...*=} Pass additional parameters to the executed function.
22853 * @returns {promise} A promise which will be notified on each iteration.
22856 * <example module="intervalExample" name="interval-service">
22857 * <file name="index.html">
22859 * angular.module('intervalExample', [])
22860 * .controller('ExampleController', ['$scope', '$interval',
22861 * function($scope, $interval) {
22862 * $scope.format = 'M/d/yy h:mm:ss a';
22863 * $scope.blood_1 = 100;
22864 * $scope.blood_2 = 120;
22867 * $scope.fight = function() {
22868 * // Don't start a new fight if we are already fighting
22869 * if ( angular.isDefined(stop) ) return;
22871 * stop = $interval(function() {
22872 * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
22873 * $scope.blood_1 = $scope.blood_1 - 3;
22874 * $scope.blood_2 = $scope.blood_2 - 4;
22876 * $scope.stopFight();
22881 * $scope.stopFight = function() {
22882 * if (angular.isDefined(stop)) {
22883 * $interval.cancel(stop);
22884 * stop = undefined;
22888 * $scope.resetFight = function() {
22889 * $scope.blood_1 = 100;
22890 * $scope.blood_2 = 120;
22893 * $scope.$on('$destroy', function() {
22894 * // Make sure that the interval is destroyed too
22895 * $scope.stopFight();
22898 * // Register the 'myCurrentTime' directive factory method.
22899 * // We inject $interval and dateFilter service since the factory method is DI.
22900 * .directive('myCurrentTime', ['$interval', 'dateFilter',
22901 * function($interval, dateFilter) {
22902 * // return the directive link function. (compile function not needed)
22903 * return function(scope, element, attrs) {
22904 * var format, // date format
22905 * stopTime; // so that we can cancel the time updates
22907 * // used to update the UI
22908 * function updateTime() {
22909 * element.text(dateFilter(new Date(), format));
22912 * // watch the expression, and update the UI on change.
22913 * scope.$watch(attrs.myCurrentTime, function(value) {
22918 * stopTime = $interval(updateTime, 1000);
22920 * // listen on DOM destroy (removal) event, and cancel the next UI update
22921 * // to prevent updating time after the DOM element was removed.
22922 * element.on('$destroy', function() {
22923 * $interval.cancel(stopTime);
22930 * <div ng-controller="ExampleController">
22931 * <label>Date format: <input ng-model="format"></label> <hr/>
22932 * Current time is: <span my-current-time="format"></span>
22934 * Blood 1 : <font color='red'>{{blood_1}}</font>
22935 * Blood 2 : <font color='red'>{{blood_2}}</font>
22936 * <button type="button" data-ng-click="fight()">Fight</button>
22937 * <button type="button" data-ng-click="stopFight()">StopFight</button>
22938 * <button type="button" data-ng-click="resetFight()">resetFight</button>
22945 function interval(fn, delay, count, invokeApply) {
22946 var hasParams = arguments.length > 4,
22947 args = hasParams ? sliceArgs(arguments, 4) : [],
22948 setInterval = $window.setInterval,
22949 clearInterval = $window.clearInterval,
22951 skipApply = (isDefined(invokeApply) && !invokeApply),
22952 deferred = (skipApply ? $$q : $q).defer(),
22953 promise = deferred.promise;
22955 count = isDefined(count) ? count : 0;
22957 promise.$$intervalId = setInterval(function tick() {
22959 $browser.defer(callback);
22961 $rootScope.$evalAsync(callback);
22963 deferred.notify(iteration++);
22965 if (count > 0 && iteration >= count) {
22966 deferred.resolve(iteration);
22967 clearInterval(promise.$$intervalId);
22968 delete intervals[promise.$$intervalId];
22971 if (!skipApply) $rootScope.$apply();
22975 intervals[promise.$$intervalId] = deferred;
22979 function callback() {
22983 fn.apply(null, args);
22991 * @name $interval#cancel
22994 * Cancels a task associated with the `promise`.
22996 * @param {Promise=} promise returned by the `$interval` function.
22997 * @returns {boolean} Returns `true` if the task was successfully canceled.
22999 interval.cancel = function(promise) {
23000 if (promise && promise.$$intervalId in intervals) {
23001 intervals[promise.$$intervalId].reject('canceled');
23002 $window.clearInterval(promise.$$intervalId);
23003 delete intervals[promise.$$intervalId];
23015 * @name $jsonpCallbacks
23016 * @requires $window
23018 * This service handles the lifecycle of callbacks to handle JSONP requests.
23019 * Override this service if you wish to customise where the callbacks are stored and
23020 * how they vary compared to the requested url.
23022 var $jsonpCallbacksProvider = /** @this */ function() {
23023 this.$get = ['$window', function($window) {
23024 var callbacks = $window.angular.callbacks;
23025 var callbackMap = {};
23027 function createCallback(callbackId) {
23028 var callback = function(data) {
23029 callback.data = data;
23030 callback.called = true;
23032 callback.id = callbackId;
23039 * @name $jsonpCallbacks#createCallback
23040 * @param {string} url the url of the JSONP request
23041 * @returns {string} the callback path to send to the server as part of the JSONP request
23043 * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback
23044 * to pass to the server, which will be used to call the callback with its payload in the JSONP response.
23046 createCallback: function(url) {
23047 var callbackId = '_' + (callbacks.$$counter++).toString(36);
23048 var callbackPath = 'angular.callbacks.' + callbackId;
23049 var callback = createCallback(callbackId);
23050 callbackMap[callbackPath] = callbacks[callbackId] = callback;
23051 return callbackPath;
23055 * @name $jsonpCallbacks#wasCalled
23056 * @param {string} callbackPath the path to the callback that was sent in the JSONP request
23057 * @returns {boolean} whether the callback has been called, as a result of the JSONP response
23059 * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the
23060 * callback that was passed in the request.
23062 wasCalled: function(callbackPath) {
23063 return callbackMap[callbackPath].called;
23067 * @name $jsonpCallbacks#getResponse
23068 * @param {string} callbackPath the path to the callback that was sent in the JSONP request
23069 * @returns {*} the data received from the response via the registered callback
23071 * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback
23072 * in the JSONP response.
23074 getResponse: function(callbackPath) {
23075 return callbackMap[callbackPath].data;
23079 * @name $jsonpCallbacks#removeCallback
23080 * @param {string} callbackPath the path to the callback that was sent in the JSONP request
23082 * {@link $httpBackend} calls this method to remove the callback after the JSONP request has
23083 * completed or timed-out.
23085 removeCallback: function(callbackPath) {
23086 var callback = callbackMap[callbackPath];
23087 delete callbacks[callback.id];
23088 delete callbackMap[callbackPath];
23099 * $locale service provides localization rules for various Angular components. As of right now the
23100 * only public api is:
23102 * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
23105 var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/,
23106 DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
23107 var $locationMinErr = minErr('$location');
23111 * Encode path using encodeUriSegment, ignoring forward slashes
23113 * @param {string} path Path to encode
23114 * @returns {string}
23116 function encodePath(path) {
23117 var segments = path.split('/'),
23118 i = segments.length;
23121 segments[i] = encodeUriSegment(segments[i]);
23124 return segments.join('/');
23127 function parseAbsoluteUrl(absoluteUrl, locationObj) {
23128 var parsedUrl = urlResolve(absoluteUrl);
23130 locationObj.$$protocol = parsedUrl.protocol;
23131 locationObj.$$host = parsedUrl.hostname;
23132 locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
23135 var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
23136 function parseAppUrl(url, locationObj) {
23138 if (DOUBLE_SLASH_REGEX.test(url)) {
23139 throw $locationMinErr('badpath', 'Invalid url "{0}".', url);
23142 var prefixed = (url.charAt(0) !== '/');
23146 var match = urlResolve(url);
23147 locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
23148 match.pathname.substring(1) : match.pathname);
23149 locationObj.$$search = parseKeyValue(match.search);
23150 locationObj.$$hash = decodeURIComponent(match.hash);
23152 // make sure path starts with '/';
23153 if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {
23154 locationObj.$$path = '/' + locationObj.$$path;
23158 function startsWith(str, search) {
23159 return str.slice(0, search.length) === search;
23164 * @param {string} base
23165 * @param {string} url
23166 * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with
23167 * the expected string.
23169 function stripBaseUrl(base, url) {
23170 if (startsWith(url, base)) {
23171 return url.substr(base.length);
23176 function stripHash(url) {
23177 var index = url.indexOf('#');
23178 return index === -1 ? url : url.substr(0, index);
23181 function trimEmptyHash(url) {
23182 return url.replace(/(#.+)|#$/, '$1');
23186 function stripFile(url) {
23187 return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
23190 /* return the server only (scheme://host:port) */
23191 function serverBase(url) {
23192 return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
23197 * LocationHtml5Url represents a URL
23198 * This object is exposed as $location service when HTML5 mode is enabled and supported
23201 * @param {string} appBase application base URL
23202 * @param {string} appBaseNoFile application base URL stripped of any filename
23203 * @param {string} basePrefix URL path prefix
23205 function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
23206 this.$$html5 = true;
23207 basePrefix = basePrefix || '';
23208 parseAbsoluteUrl(appBase, this);
23212 * Parse given HTML5 (regular) URL string into properties
23213 * @param {string} url HTML5 URL
23216 this.$$parse = function(url) {
23217 var pathUrl = stripBaseUrl(appBaseNoFile, url);
23218 if (!isString(pathUrl)) {
23219 throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
23223 parseAppUrl(pathUrl, this);
23225 if (!this.$$path) {
23233 * Compose url and update `absUrl` property
23236 this.$$compose = function() {
23237 var search = toKeyValue(this.$$search),
23238 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
23240 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
23241 this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
23244 this.$$parseLinkUrl = function(url, relHref) {
23245 if (relHref && relHref[0] === '#') {
23246 // special case for links to hash fragments:
23247 // keep the old url and only replace the hash fragment
23248 this.hash(relHref.slice(1));
23251 var appUrl, prevAppUrl;
23255 if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
23256 prevAppUrl = appUrl;
23257 if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
23258 rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
23260 rewrittenUrl = appBase + prevAppUrl;
23262 } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
23263 rewrittenUrl = appBaseNoFile + appUrl;
23264 } else if (appBaseNoFile === url + '/') {
23265 rewrittenUrl = appBaseNoFile;
23267 if (rewrittenUrl) {
23268 this.$$parse(rewrittenUrl);
23270 return !!rewrittenUrl;
23276 * LocationHashbangUrl represents URL
23277 * This object is exposed as $location service when developer doesn't opt into html5 mode.
23278 * It also serves as the base class for html5 mode fallback on legacy browsers.
23281 * @param {string} appBase application base URL
23282 * @param {string} appBaseNoFile application base URL stripped of any filename
23283 * @param {string} hashPrefix hashbang prefix
23285 function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
23287 parseAbsoluteUrl(appBase, this);
23291 * Parse given hashbang URL into properties
23292 * @param {string} url Hashbang URL
23295 this.$$parse = function(url) {
23296 var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
23297 var withoutHashUrl;
23299 if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
23301 // The rest of the URL starts with a hash so we have
23302 // got either a hashbang path or a plain hash fragment
23303 withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);
23304 if (isUndefined(withoutHashUrl)) {
23305 // There was no hashbang prefix so we just have a hash fragment
23306 withoutHashUrl = withoutBaseUrl;
23310 // There was no hashbang path nor hash fragment:
23311 // If we are in HTML5 mode we use what is left as the path;
23312 // Otherwise we ignore what is left
23313 if (this.$$html5) {
23314 withoutHashUrl = withoutBaseUrl;
23316 withoutHashUrl = '';
23317 if (isUndefined(withoutBaseUrl)) {
23324 parseAppUrl(withoutHashUrl, this);
23326 this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
23331 * In Windows, on an anchor node on documents loaded from
23332 * the filesystem, the browser will return a pathname
23333 * prefixed with the drive name ('/C:/path') when a
23334 * pathname without a drive is set:
23335 * * a.setAttribute('href', '/foo')
23336 * * a.pathname === '/C:/foo' //true
23338 * Inside of Angular, we're always using pathnames that
23339 * do not include drive names for routing.
23341 function removeWindowsDriveName(path, url, base) {
23343 Matches paths for file protocol on windows,
23344 such as /C:/foo/bar, and captures only /foo/bar.
23346 var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
23348 var firstPathSegmentMatch;
23350 //Get the relative path from the input URL.
23351 if (startsWith(url, base)) {
23352 url = url.replace(base, '');
23355 // The input URL intentionally contains a first path segment that ends with a colon.
23356 if (windowsFilePathExp.exec(url)) {
23360 firstPathSegmentMatch = windowsFilePathExp.exec(path);
23361 return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
23366 * Compose hashbang URL and update `absUrl` property
23369 this.$$compose = function() {
23370 var search = toKeyValue(this.$$search),
23371 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
23373 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
23374 this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
23377 this.$$parseLinkUrl = function(url, relHref) {
23378 if (stripHash(appBase) === stripHash(url)) {
23388 * LocationHashbangUrl represents URL
23389 * This object is exposed as $location service when html5 history api is enabled but the browser
23390 * does not support it.
23393 * @param {string} appBase application base URL
23394 * @param {string} appBaseNoFile application base URL stripped of any filename
23395 * @param {string} hashPrefix hashbang prefix
23397 function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
23398 this.$$html5 = true;
23399 LocationHashbangUrl.apply(this, arguments);
23401 this.$$parseLinkUrl = function(url, relHref) {
23402 if (relHref && relHref[0] === '#') {
23403 // special case for links to hash fragments:
23404 // keep the old url and only replace the hash fragment
23405 this.hash(relHref.slice(1));
23412 if (appBase === stripHash(url)) {
23413 rewrittenUrl = url;
23414 } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {
23415 rewrittenUrl = appBase + hashPrefix + appUrl;
23416 } else if (appBaseNoFile === url + '/') {
23417 rewrittenUrl = appBaseNoFile;
23419 if (rewrittenUrl) {
23420 this.$$parse(rewrittenUrl);
23422 return !!rewrittenUrl;
23425 this.$$compose = function() {
23426 var search = toKeyValue(this.$$search),
23427 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
23429 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
23430 // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
23431 this.$$absUrl = appBase + hashPrefix + this.$$url;
23437 var locationPrototype = {
23440 * Ensure absolute URL is initialized.
23446 * Are we in html5 mode?
23452 * Has any change been replacing?
23459 * @name $location#absUrl
23462 * This method is getter only.
23464 * Return full URL representation with all segments encoded according to rules specified in
23465 * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
23469 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
23470 * var absUrl = $location.absUrl();
23471 * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
23474 * @return {string} full URL
23476 absUrl: locationGetter('$$absUrl'),
23480 * @name $location#url
23483 * This method is getter / setter.
23485 * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.
23487 * Change path, search and hash, when called with parameter and return `$location`.
23491 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
23492 * var url = $location.url();
23493 * // => "/some/path?foo=bar&baz=xoxo"
23496 * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)
23497 * @return {string} url
23499 url: function(url) {
23500 if (isUndefined(url)) {
23504 var match = PATH_MATCH.exec(url);
23505 if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
23506 if (match[2] || match[1] || url === '') this.search(match[3] || '');
23507 this.hash(match[5] || '');
23514 * @name $location#protocol
23517 * This method is getter only.
23519 * Return protocol of current URL.
23523 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
23524 * var protocol = $location.protocol();
23528 * @return {string} protocol of current URL
23530 protocol: locationGetter('$$protocol'),
23534 * @name $location#host
23537 * This method is getter only.
23539 * Return host of current URL.
23541 * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
23545 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
23546 * var host = $location.host();
23547 * // => "example.com"
23549 * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
23550 * host = $location.host();
23551 * // => "example.com"
23552 * host = location.host;
23553 * // => "example.com:8080"
23556 * @return {string} host of current URL.
23558 host: locationGetter('$$host'),
23562 * @name $location#port
23565 * This method is getter only.
23567 * Return port of current URL.
23571 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
23572 * var port = $location.port();
23576 * @return {Number} port
23578 port: locationGetter('$$port'),
23582 * @name $location#path
23585 * This method is getter / setter.
23587 * Return path of current URL when called without any parameter.
23589 * Change path when called with parameter and return `$location`.
23591 * Note: Path should always begin with forward slash (/), this method will add the forward slash
23592 * if it is missing.
23596 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
23597 * var path = $location.path();
23598 * // => "/some/path"
23601 * @param {(string|number)=} path New path
23602 * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
23604 path: locationGetterSetter('$$path', function(path) {
23605 path = path !== null ? path.toString() : '';
23606 return path.charAt(0) === '/' ? path : '/' + path;
23611 * @name $location#search
23614 * This method is getter / setter.
23616 * Return search part (as object) of current URL when called without any parameter.
23618 * Change search part when called with parameter and return `$location`.
23622 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
23623 * var searchObject = $location.search();
23624 * // => {foo: 'bar', baz: 'xoxo'}
23626 * // set foo to 'yipee'
23627 * $location.search('foo', 'yipee');
23628 * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
23631 * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
23634 * When called with a single argument the method acts as a setter, setting the `search` component
23635 * of `$location` to the specified value.
23637 * If the argument is a hash object containing an array of values, these values will be encoded
23638 * as duplicate search parameters in the URL.
23640 * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
23641 * will override only a single search property.
23643 * If `paramValue` is an array, it will override the property of the `search` component of
23644 * `$location` specified via the first argument.
23646 * If `paramValue` is `null`, the property specified via the first argument will be deleted.
23648 * If `paramValue` is `true`, the property specified via the first argument will be added with no
23649 * value nor trailing equal sign.
23651 * @return {Object} If called with no arguments returns the parsed `search` object. If called with
23652 * one or more arguments returns `$location` object itself.
23654 search: function(search, paramValue) {
23655 switch (arguments.length) {
23657 return this.$$search;
23659 if (isString(search) || isNumber(search)) {
23660 search = search.toString();
23661 this.$$search = parseKeyValue(search);
23662 } else if (isObject(search)) {
23663 search = copy(search, {});
23664 // remove object undefined or null properties
23665 forEach(search, function(value, key) {
23666 if (value == null) delete search[key];
23669 this.$$search = search;
23671 throw $locationMinErr('isrcharg',
23672 'The first argument of the `$location#search()` call must be a string or an object.');
23676 if (isUndefined(paramValue) || paramValue === null) {
23677 delete this.$$search[search];
23679 this.$$search[search] = paramValue;
23689 * @name $location#hash
23692 * This method is getter / setter.
23694 * Returns the hash fragment when called without any parameters.
23696 * Changes the hash fragment when called with a parameter and returns `$location`.
23700 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
23701 * var hash = $location.hash();
23702 * // => "hashValue"
23705 * @param {(string|number)=} hash New hash fragment
23706 * @return {string} hash
23708 hash: locationGetterSetter('$$hash', function(hash) {
23709 return hash !== null ? hash.toString() : '';
23714 * @name $location#replace
23717 * If called, all changes to $location during the current `$digest` will replace the current history
23718 * record, instead of adding a new one.
23720 replace: function() {
23721 this.$$replace = true;
23726 forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
23727 Location.prototype = Object.create(locationPrototype);
23731 * @name $location#state
23734 * This method is getter / setter.
23736 * Return the history state object when called without any parameter.
23738 * Change the history state object when called with one parameter and return `$location`.
23739 * The state object is later passed to `pushState` or `replaceState`.
23741 * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
23742 * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
23743 * older browsers (like IE9 or Android < 4.0), don't use this method.
23745 * @param {object=} state State object for pushState or replaceState
23746 * @return {object} state
23748 Location.prototype.state = function(state) {
23749 if (!arguments.length) {
23750 return this.$$state;
23753 if (Location !== LocationHtml5Url || !this.$$html5) {
23754 throw $locationMinErr('nostate', 'History API state support is available only ' +
23755 'in HTML5 mode and only in browsers supporting HTML5 History API');
23757 // The user might modify `stateObject` after invoking `$location.state(stateObject)`
23758 // but we're changing the $$state reference to $browser.state() during the $digest
23759 // so the modification window is narrow.
23760 this.$$state = isUndefined(state) ? null : state;
23767 function locationGetter(property) {
23768 return /** @this */ function() {
23769 return this[property];
23774 function locationGetterSetter(property, preprocess) {
23775 return /** @this */ function(value) {
23776 if (isUndefined(value)) {
23777 return this[property];
23780 this[property] = preprocess(value);
23792 * @requires $rootElement
23795 * The $location service parses the URL in the browser address bar (based on the
23796 * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
23797 * available to your application. Changes to the URL in the address bar are reflected into
23798 * $location service and changes to $location are reflected into the browser address bar.
23800 * **The $location service:**
23802 * - Exposes the current URL in the browser address bar, so you can
23803 * - Watch and observe the URL.
23804 * - Change the URL.
23805 * - Synchronizes the URL with the browser when the user
23806 * - Changes the address bar.
23807 * - Clicks the back or forward button (or clicks a History link).
23808 * - Clicks on a link.
23809 * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
23811 * For more information see {@link guide/$location Developer Guide: Using $location}
23816 * @name $locationProvider
23820 * Use the `$locationProvider` to configure how the application deep linking paths are stored.
23822 function $LocationProvider() {
23823 var hashPrefix = '',
23832 * @name $locationProvider#hashPrefix
23834 * The default value for the prefix is `''`.
23835 * @param {string=} prefix Prefix for hash part (containing path and search)
23836 * @returns {*} current value if used as getter or itself (chaining) if used as setter
23838 this.hashPrefix = function(prefix) {
23839 if (isDefined(prefix)) {
23840 hashPrefix = prefix;
23849 * @name $locationProvider#html5Mode
23851 * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
23852 * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
23854 * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
23855 * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
23856 * support `pushState`.
23857 * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
23858 * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
23859 * true, and a base tag is not present, an error will be thrown when `$location` is injected.
23860 * See the {@link guide/$location $location guide for more information}
23861 * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled,
23862 * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will
23863 * only happen on links with an attribute that matches the given string. For example, if set
23864 * to `'internal-link'`, then the URL will only be rewritten for `<a internal-link>` links.
23865 * Note that [attribute name normalization](guide/directive#normalization) does not apply
23866 * here, so `'internalLink'` will **not** match `'internal-link'`.
23868 * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
23870 this.html5Mode = function(mode) {
23871 if (isBoolean(mode)) {
23872 html5Mode.enabled = mode;
23874 } else if (isObject(mode)) {
23876 if (isBoolean(mode.enabled)) {
23877 html5Mode.enabled = mode.enabled;
23880 if (isBoolean(mode.requireBase)) {
23881 html5Mode.requireBase = mode.requireBase;
23884 if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {
23885 html5Mode.rewriteLinks = mode.rewriteLinks;
23896 * @name $location#$locationChangeStart
23897 * @eventType broadcast on root scope
23899 * Broadcasted before a URL will change.
23901 * This change can be prevented by calling
23902 * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
23903 * details about event object. Upon successful change
23904 * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
23906 * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
23907 * the browser supports the HTML5 History API.
23909 * @param {Object} angularEvent Synthetic event object.
23910 * @param {string} newUrl New URL
23911 * @param {string=} oldUrl URL that was before it was changed.
23912 * @param {string=} newState New history state object
23913 * @param {string=} oldState History state object that was before it was changed.
23918 * @name $location#$locationChangeSuccess
23919 * @eventType broadcast on root scope
23921 * Broadcasted after a URL was changed.
23923 * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
23924 * the browser supports the HTML5 History API.
23926 * @param {Object} angularEvent Synthetic event object.
23927 * @param {string} newUrl New URL
23928 * @param {string=} oldUrl URL that was before it was changed.
23929 * @param {string=} newState New history state object
23930 * @param {string=} oldState History state object that was before it was changed.
23933 this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
23934 function($rootScope, $browser, $sniffer, $rootElement, $window) {
23937 baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
23938 initialUrl = $browser.url(),
23941 if (html5Mode.enabled) {
23942 if (!baseHref && html5Mode.requireBase) {
23943 throw $locationMinErr('nobase',
23944 '$location in HTML5 mode requires a <base> tag to be present!');
23946 appBase = serverBase(initialUrl) + (baseHref || '/');
23947 LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
23949 appBase = stripHash(initialUrl);
23950 LocationMode = LocationHashbangUrl;
23952 var appBaseNoFile = stripFile(appBase);
23954 $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
23955 $location.$$parseLinkUrl(initialUrl, initialUrl);
23957 $location.$$state = $browser.state();
23959 var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
23961 function setBrowserUrlWithFallback(url, replace, state) {
23962 var oldUrl = $location.url();
23963 var oldState = $location.$$state;
23965 $browser.url(url, replace, state);
23967 // Make sure $location.state() returns referentially identical (not just deeply equal)
23968 // state object; this makes possible quick checking if the state changed in the digest
23969 // loop. Checking deep equality would be too expensive.
23970 $location.$$state = $browser.state();
23972 // Restore old values if pushState fails
23973 $location.url(oldUrl);
23974 $location.$$state = oldState;
23980 $rootElement.on('click', function(event) {
23981 var rewriteLinks = html5Mode.rewriteLinks;
23982 // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
23983 // currently we open nice url link and redirect then
23985 if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;
23987 var elm = jqLite(event.target);
23989 // traverse the DOM up to find first A tag
23990 while (nodeName_(elm[0]) !== 'a') {
23991 // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
23992 if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
23995 if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;
23997 var absHref = elm.prop('href');
23998 // get the actual href attribute - see
23999 // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
24000 var relHref = elm.attr('href') || elm.attr('xlink:href');
24002 if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
24003 // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
24005 absHref = urlResolve(absHref.animVal).href;
24008 // Ignore when url is started with javascript: or mailto:
24009 if (IGNORE_URI_REGEXP.test(absHref)) return;
24011 if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
24012 if ($location.$$parseLinkUrl(absHref, relHref)) {
24013 // We do a preventDefault for all urls that are part of the angular application,
24014 // in html5mode and also without, so that we are able to abort navigation without
24015 // getting double entries in the location history.
24016 event.preventDefault();
24017 // update location manually
24018 if ($location.absUrl() !== $browser.url()) {
24019 $rootScope.$apply();
24020 // hack to work around FF6 bug 684208 when scenario runner clicks on links
24021 $window.angular['ff-684208-preventDefault'] = true;
24028 // rewrite hashbang url <> html5 url
24029 if (trimEmptyHash($location.absUrl()) !== trimEmptyHash(initialUrl)) {
24030 $browser.url($location.absUrl(), true);
24033 var initializing = true;
24035 // update $location when $browser url changes
24036 $browser.onUrlChange(function(newUrl, newState) {
24038 if (isUndefined(stripBaseUrl(appBaseNoFile, newUrl))) {
24039 // If we are navigating outside of the app then force a reload
24040 $window.location.href = newUrl;
24044 $rootScope.$evalAsync(function() {
24045 var oldUrl = $location.absUrl();
24046 var oldState = $location.$$state;
24047 var defaultPrevented;
24048 newUrl = trimEmptyHash(newUrl);
24049 $location.$$parse(newUrl);
24050 $location.$$state = newState;
24052 defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
24053 newState, oldState).defaultPrevented;
24055 // if the location was changed by a `$locationChangeStart` handler then stop
24056 // processing this location change
24057 if ($location.absUrl() !== newUrl) return;
24059 if (defaultPrevented) {
24060 $location.$$parse(oldUrl);
24061 $location.$$state = oldState;
24062 setBrowserUrlWithFallback(oldUrl, false, oldState);
24064 initializing = false;
24065 afterLocationChange(oldUrl, oldState);
24068 if (!$rootScope.$$phase) $rootScope.$digest();
24072 $rootScope.$watch(function $locationWatch() {
24073 var oldUrl = trimEmptyHash($browser.url());
24074 var newUrl = trimEmptyHash($location.absUrl());
24075 var oldState = $browser.state();
24076 var currentReplace = $location.$$replace;
24077 var urlOrStateChanged = oldUrl !== newUrl ||
24078 ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
24080 if (initializing || urlOrStateChanged) {
24081 initializing = false;
24083 $rootScope.$evalAsync(function() {
24084 var newUrl = $location.absUrl();
24085 var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
24086 $location.$$state, oldState).defaultPrevented;
24088 // if the location was changed by a `$locationChangeStart` handler then stop
24089 // processing this location change
24090 if ($location.absUrl() !== newUrl) return;
24092 if (defaultPrevented) {
24093 $location.$$parse(oldUrl);
24094 $location.$$state = oldState;
24096 if (urlOrStateChanged) {
24097 setBrowserUrlWithFallback(newUrl, currentReplace,
24098 oldState === $location.$$state ? null : $location.$$state);
24100 afterLocationChange(oldUrl, oldState);
24105 $location.$$replace = false;
24107 // we don't need to return anything because $evalAsync will make the digest loop dirty when
24108 // there is a change
24113 function afterLocationChange(oldUrl, oldState) {
24114 $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
24115 $location.$$state, oldState);
24123 * @requires $window
24126 * Simple service for logging. Default implementation safely writes the message
24127 * into the browser's console (if present).
24129 * The main purpose of this service is to simplify debugging and troubleshooting.
24131 * The default is to log `debug` messages. You can use
24132 * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
24135 <example module="logExample" name="log-service">
24136 <file name="script.js">
24137 angular.module('logExample', [])
24138 .controller('LogController', ['$scope', '$log', function($scope, $log) {
24139 $scope.$log = $log;
24140 $scope.message = 'Hello World!';
24143 <file name="index.html">
24144 <div ng-controller="LogController">
24145 <p>Reload this page with open console, enter text and hit the log button...</p>
24147 <input type="text" ng-model="message" /></label>
24148 <button ng-click="$log.log(message)">log</button>
24149 <button ng-click="$log.warn(message)">warn</button>
24150 <button ng-click="$log.info(message)">info</button>
24151 <button ng-click="$log.error(message)">error</button>
24152 <button ng-click="$log.debug(message)">debug</button>
24160 * @name $logProvider
24164 * Use the `$logProvider` to configure how the application logs messages
24166 function $LogProvider() {
24172 * @name $logProvider#debugEnabled
24174 * @param {boolean=} flag enable or disable debug level messages
24175 * @returns {*} current value if used as getter or itself (chaining) if used as setter
24177 this.debugEnabled = function(flag) {
24178 if (isDefined(flag)) {
24186 this.$get = ['$window', function($window) {
24193 * Write a log message
24195 log: consoleLog('log'),
24202 * Write an information message
24204 info: consoleLog('info'),
24211 * Write a warning message
24213 warn: consoleLog('warn'),
24220 * Write an error message
24222 error: consoleLog('error'),
24229 * Write a debug message
24231 debug: (function() {
24232 var fn = consoleLog('debug');
24234 return function() {
24236 fn.apply(self, arguments);
24242 function formatError(arg) {
24243 if (arg instanceof Error) {
24245 arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
24246 ? 'Error: ' + arg.message + '\n' + arg.stack
24248 } else if (arg.sourceURL) {
24249 arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
24255 function consoleLog(type) {
24256 var console = $window.console || {},
24257 logFn = console[type] || console.log || noop,
24260 // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
24261 // The reason behind this is that console.log has type "object" in IE8...
24263 hasApply = !!logFn.apply;
24264 } catch (e) { /* empty */ }
24267 return function() {
24269 forEach(arguments, function(arg) {
24270 args.push(formatError(arg));
24272 return logFn.apply(console, args);
24276 // we are IE which either doesn't have window.console => this is noop and we do nothing,
24277 // or we are IE where console.log doesn't have apply so we log at least first 2 args
24278 return function(arg1, arg2) {
24279 logFn(arg1, arg2 == null ? '' : arg2);
24285 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
24286 * Any commits to this file should be reviewed with security in mind. *
24287 * Changes to this file can potentially create security vulnerabilities. *
24288 * An approval from 2 Core members with history of modifying *
24289 * this file is required. *
24291 * Does the change somehow allow for arbitrary javascript to be executed? *
24292 * Or allows for someone to change the prototype of built-in objects? *
24293 * Or gives undesired access to variables likes document or window? *
24294 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
24296 var $parseMinErr = minErr('$parse');
24298 var ARRAY_CTOR = [].constructor;
24299 var BOOLEAN_CTOR = (false).constructor;
24300 var FUNCTION_CTOR = Function.constructor;
24301 var NUMBER_CTOR = (0).constructor;
24302 var OBJECT_CTOR = {}.constructor;
24303 var STRING_CTOR = ''.constructor;
24304 var ARRAY_CTOR_PROTO = ARRAY_CTOR.prototype;
24305 var BOOLEAN_CTOR_PROTO = BOOLEAN_CTOR.prototype;
24306 var FUNCTION_CTOR_PROTO = FUNCTION_CTOR.prototype;
24307 var NUMBER_CTOR_PROTO = NUMBER_CTOR.prototype;
24308 var OBJECT_CTOR_PROTO = OBJECT_CTOR.prototype;
24309 var STRING_CTOR_PROTO = STRING_CTOR.prototype;
24311 var CALL = FUNCTION_CTOR_PROTO.call;
24312 var APPLY = FUNCTION_CTOR_PROTO.apply;
24313 var BIND = FUNCTION_CTOR_PROTO.bind;
24315 var objectValueOf = OBJECT_CTOR_PROTO.valueOf;
24317 // Sandboxing Angular Expressions
24318 // ------------------------------
24319 // Angular expressions are generally considered safe because these expressions only have direct
24320 // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
24321 // obtaining a reference to native JS functions such as the Function constructor.
24323 // As an example, consider the following Angular expression:
24325 // {}.toString.constructor('alert("evil JS code")')
24327 // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
24328 // against the expression language, but not to prevent exploits that were enabled by exposing
24329 // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
24330 // practice and therefore we are not even trying to protect against interaction with an object
24331 // explicitly exposed in this way.
24333 // In general, it is not possible to access a Window object from an angular expression unless a
24334 // window or some DOM object that has a reference to window is published onto a Scope.
24335 // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
24338 // See https://docs.angularjs.org/guide/security
24341 function ensureSafeMemberName(name, fullExpression) {
24342 if (name === '__defineGetter__' || name === '__defineSetter__'
24343 || name === '__lookupGetter__' || name === '__lookupSetter__'
24344 || name === '__proto__') {
24345 throw $parseMinErr('isecfld',
24346 'Attempting to access a disallowed field in Angular expressions! '
24347 + 'Expression: {0}', fullExpression);
24352 function getStringValue(name) {
24353 // Property names must be strings. This means that non-string objects cannot be used
24354 // as keys in an object. Any non-string object, including a number, is typecasted
24355 // into a string via the toString method.
24356 // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
24358 // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
24359 // to a string. It's not always possible. If `name` is an object and its `toString` method is
24360 // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
24362 // TypeError: Cannot convert object to primitive value
24364 // For performance reasons, we don't catch this error here and allow it to propagate up the call
24365 // stack. Note that you'll get the same error in JavaScript if you try to access a property using
24366 // such a 'broken' object as a key.
24370 function ensureSafeObject(obj, fullExpression) {
24371 // nifty check if obj is Function that is fast and works across iframes and other contexts
24373 if (obj.constructor === obj) {
24374 throw $parseMinErr('isecfn',
24375 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
24377 } else if (// isWindow(obj)
24378 obj.window === obj) {
24379 throw $parseMinErr('isecwindow',
24380 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
24382 } else if (// isElement(obj)
24383 obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
24384 throw $parseMinErr('isecdom',
24385 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
24387 } else if (// block Object so that we can't get hold of dangerous Object.* methods
24389 throw $parseMinErr('isecobj',
24390 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
24397 function ensureSafeFunction(obj, fullExpression) {
24399 if (obj.constructor === obj) {
24400 throw $parseMinErr('isecfn',
24401 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
24403 } else if (obj === CALL || obj === APPLY || obj === BIND) {
24404 throw $parseMinErr('isecff',
24405 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
24411 function ensureSafeAssignContext(obj, fullExpression) {
24413 if (obj === ARRAY_CTOR ||
24414 obj === BOOLEAN_CTOR ||
24415 obj === FUNCTION_CTOR ||
24416 obj === NUMBER_CTOR ||
24417 obj === OBJECT_CTOR ||
24418 obj === STRING_CTOR ||
24419 obj === ARRAY_CTOR_PROTO ||
24420 obj === BOOLEAN_CTOR_PROTO ||
24421 obj === FUNCTION_CTOR_PROTO ||
24422 obj === NUMBER_CTOR_PROTO ||
24423 obj === OBJECT_CTOR_PROTO ||
24424 obj === STRING_CTOR_PROTO) {
24425 throw $parseMinErr('isecaf',
24426 'Assigning to a constructor or its prototype is disallowed! Expression: {0}',
24432 var OPERATORS = createMap();
24433 forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
24434 var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'};
24437 /////////////////////////////////////////
24443 var Lexer = function Lexer(options) {
24444 this.options = options;
24447 Lexer.prototype = {
24448 constructor: Lexer,
24450 lex: function(text) {
24455 while (this.index < this.text.length) {
24456 var ch = this.text.charAt(this.index);
24457 if (ch === '"' || ch === '\'') {
24458 this.readString(ch);
24459 } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
24461 } else if (this.isIdentifierStart(this.peekMultichar())) {
24463 } else if (this.is(ch, '(){}[].,;:?')) {
24464 this.tokens.push({index: this.index, text: ch});
24466 } else if (this.isWhitespace(ch)) {
24469 var ch2 = ch + this.peek();
24470 var ch3 = ch2 + this.peek(2);
24471 var op1 = OPERATORS[ch];
24472 var op2 = OPERATORS[ch2];
24473 var op3 = OPERATORS[ch3];
24474 if (op1 || op2 || op3) {
24475 var token = op3 ? ch3 : (op2 ? ch2 : ch);
24476 this.tokens.push({index: this.index, text: token, operator: true});
24477 this.index += token.length;
24479 this.throwError('Unexpected next character ', this.index, this.index + 1);
24483 return this.tokens;
24486 is: function(ch, chars) {
24487 return chars.indexOf(ch) !== -1;
24490 peek: function(i) {
24492 return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
24495 isNumber: function(ch) {
24496 return ('0' <= ch && ch <= '9') && typeof ch === 'string';
24499 isWhitespace: function(ch) {
24500 // IE treats non-breaking space as \u00A0
24501 return (ch === ' ' || ch === '\r' || ch === '\t' ||
24502 ch === '\n' || ch === '\v' || ch === '\u00A0');
24505 isIdentifierStart: function(ch) {
24506 return this.options.isIdentifierStart ?
24507 this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
24508 this.isValidIdentifierStart(ch);
24511 isValidIdentifierStart: function(ch) {
24512 return ('a' <= ch && ch <= 'z' ||
24513 'A' <= ch && ch <= 'Z' ||
24514 '_' === ch || ch === '$');
24517 isIdentifierContinue: function(ch) {
24518 return this.options.isIdentifierContinue ?
24519 this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
24520 this.isValidIdentifierContinue(ch);
24523 isValidIdentifierContinue: function(ch, cp) {
24524 return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
24527 codePointAt: function(ch) {
24528 if (ch.length === 1) return ch.charCodeAt(0);
24529 // eslint-disable-next-line no-bitwise
24530 return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
24533 peekMultichar: function() {
24534 var ch = this.text.charAt(this.index);
24535 var peek = this.peek();
24539 var cp1 = ch.charCodeAt(0);
24540 var cp2 = peek.charCodeAt(0);
24541 if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
24547 isExpOperator: function(ch) {
24548 return (ch === '-' || ch === '+' || this.isNumber(ch));
24551 throwError: function(error, start, end) {
24552 end = end || this.index;
24553 var colStr = (isDefined(start)
24554 ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
24556 throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
24557 error, colStr, this.text);
24560 readNumber: function() {
24562 var start = this.index;
24563 while (this.index < this.text.length) {
24564 var ch = lowercase(this.text.charAt(this.index));
24565 if (ch === '.' || this.isNumber(ch)) {
24568 var peekCh = this.peek();
24569 if (ch === 'e' && this.isExpOperator(peekCh)) {
24571 } else if (this.isExpOperator(ch) &&
24572 peekCh && this.isNumber(peekCh) &&
24573 number.charAt(number.length - 1) === 'e') {
24575 } else if (this.isExpOperator(ch) &&
24576 (!peekCh || !this.isNumber(peekCh)) &&
24577 number.charAt(number.length - 1) === 'e') {
24578 this.throwError('Invalid exponent');
24589 value: Number(number)
24593 readIdent: function() {
24594 var start = this.index;
24595 this.index += this.peekMultichar().length;
24596 while (this.index < this.text.length) {
24597 var ch = this.peekMultichar();
24598 if (!this.isIdentifierContinue(ch)) {
24601 this.index += ch.length;
24605 text: this.text.slice(start, this.index),
24610 readString: function(quote) {
24611 var start = this.index;
24614 var rawString = quote;
24615 var escape = false;
24616 while (this.index < this.text.length) {
24617 var ch = this.text.charAt(this.index);
24621 var hex = this.text.substring(this.index + 1, this.index + 5);
24622 if (!hex.match(/[\da-f]{4}/i)) {
24623 this.throwError('Invalid unicode escape [\\u' + hex + ']');
24626 string += String.fromCharCode(parseInt(hex, 16));
24628 var rep = ESCAPE[ch];
24629 string = string + (rep || ch);
24632 } else if (ch === '\\') {
24634 } else if (ch === quote) {
24648 this.throwError('Unterminated quote', start);
24652 var AST = function AST(lexer, options) {
24653 this.lexer = lexer;
24654 this.options = options;
24657 AST.Program = 'Program';
24658 AST.ExpressionStatement = 'ExpressionStatement';
24659 AST.AssignmentExpression = 'AssignmentExpression';
24660 AST.ConditionalExpression = 'ConditionalExpression';
24661 AST.LogicalExpression = 'LogicalExpression';
24662 AST.BinaryExpression = 'BinaryExpression';
24663 AST.UnaryExpression = 'UnaryExpression';
24664 AST.CallExpression = 'CallExpression';
24665 AST.MemberExpression = 'MemberExpression';
24666 AST.Identifier = 'Identifier';
24667 AST.Literal = 'Literal';
24668 AST.ArrayExpression = 'ArrayExpression';
24669 AST.Property = 'Property';
24670 AST.ObjectExpression = 'ObjectExpression';
24671 AST.ThisExpression = 'ThisExpression';
24672 AST.LocalsExpression = 'LocalsExpression';
24674 // Internal use only
24675 AST.NGValueParameter = 'NGValueParameter';
24678 ast: function(text) {
24680 this.tokens = this.lexer.lex(text);
24682 var value = this.program();
24684 if (this.tokens.length !== 0) {
24685 this.throwError('is an unexpected token', this.tokens[0]);
24691 program: function() {
24694 if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
24695 body.push(this.expressionStatement());
24696 if (!this.expect(';')) {
24697 return { type: AST.Program, body: body};
24702 expressionStatement: function() {
24703 return { type: AST.ExpressionStatement, expression: this.filterChain() };
24706 filterChain: function() {
24707 var left = this.expression();
24708 while (this.expect('|')) {
24709 left = this.filter(left);
24714 expression: function() {
24715 return this.assignment();
24718 assignment: function() {
24719 var result = this.ternary();
24720 if (this.expect('=')) {
24721 if (!isAssignable(result)) {
24722 throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
24725 result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
24730 ternary: function() {
24731 var test = this.logicalOR();
24734 if (this.expect('?')) {
24735 alternate = this.expression();
24736 if (this.consume(':')) {
24737 consequent = this.expression();
24738 return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
24744 logicalOR: function() {
24745 var left = this.logicalAND();
24746 while (this.expect('||')) {
24747 left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
24752 logicalAND: function() {
24753 var left = this.equality();
24754 while (this.expect('&&')) {
24755 left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
24760 equality: function() {
24761 var left = this.relational();
24763 while ((token = this.expect('==','!=','===','!=='))) {
24764 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
24769 relational: function() {
24770 var left = this.additive();
24772 while ((token = this.expect('<', '>', '<=', '>='))) {
24773 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
24778 additive: function() {
24779 var left = this.multiplicative();
24781 while ((token = this.expect('+','-'))) {
24782 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
24787 multiplicative: function() {
24788 var left = this.unary();
24790 while ((token = this.expect('*','/','%'))) {
24791 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
24796 unary: function() {
24798 if ((token = this.expect('+', '-', '!'))) {
24799 return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
24801 return this.primary();
24805 primary: function() {
24807 if (this.expect('(')) {
24808 primary = this.filterChain();
24810 } else if (this.expect('[')) {
24811 primary = this.arrayDeclaration();
24812 } else if (this.expect('{')) {
24813 primary = this.object();
24814 } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
24815 primary = copy(this.selfReferential[this.consume().text]);
24816 } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
24817 primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
24818 } else if (this.peek().identifier) {
24819 primary = this.identifier();
24820 } else if (this.peek().constant) {
24821 primary = this.constant();
24823 this.throwError('not a primary expression', this.peek());
24827 while ((next = this.expect('(', '[', '.'))) {
24828 if (next.text === '(') {
24829 primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
24831 } else if (next.text === '[') {
24832 primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
24834 } else if (next.text === '.') {
24835 primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
24837 this.throwError('IMPOSSIBLE');
24843 filter: function(baseExpression) {
24844 var args = [baseExpression];
24845 var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
24847 while (this.expect(':')) {
24848 args.push(this.expression());
24854 parseArguments: function() {
24856 if (this.peekToken().text !== ')') {
24858 args.push(this.filterChain());
24859 } while (this.expect(','));
24864 identifier: function() {
24865 var token = this.consume();
24866 if (!token.identifier) {
24867 this.throwError('is not a valid identifier', token);
24869 return { type: AST.Identifier, name: token.text };
24872 constant: function() {
24873 // TODO check that it is a constant
24874 return { type: AST.Literal, value: this.consume().value };
24877 arrayDeclaration: function() {
24879 if (this.peekToken().text !== ']') {
24881 if (this.peek(']')) {
24882 // Support trailing commas per ES5.1.
24885 elements.push(this.expression());
24886 } while (this.expect(','));
24890 return { type: AST.ArrayExpression, elements: elements };
24893 object: function() {
24894 var properties = [], property;
24895 if (this.peekToken().text !== '}') {
24897 if (this.peek('}')) {
24898 // Support trailing commas per ES5.1.
24901 property = {type: AST.Property, kind: 'init'};
24902 if (this.peek().constant) {
24903 property.key = this.constant();
24904 property.computed = false;
24906 property.value = this.expression();
24907 } else if (this.peek().identifier) {
24908 property.key = this.identifier();
24909 property.computed = false;
24910 if (this.peek(':')) {
24912 property.value = this.expression();
24914 property.value = property.key;
24916 } else if (this.peek('[')) {
24918 property.key = this.expression();
24920 property.computed = true;
24922 property.value = this.expression();
24924 this.throwError('invalid key', this.peek());
24926 properties.push(property);
24927 } while (this.expect(','));
24931 return {type: AST.ObjectExpression, properties: properties };
24934 throwError: function(msg, token) {
24935 throw $parseMinErr('syntax',
24936 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
24937 token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
24940 consume: function(e1) {
24941 if (this.tokens.length === 0) {
24942 throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
24945 var token = this.expect(e1);
24947 this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
24952 peekToken: function() {
24953 if (this.tokens.length === 0) {
24954 throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
24956 return this.tokens[0];
24959 peek: function(e1, e2, e3, e4) {
24960 return this.peekAhead(0, e1, e2, e3, e4);
24963 peekAhead: function(i, e1, e2, e3, e4) {
24964 if (this.tokens.length > i) {
24965 var token = this.tokens[i];
24966 var t = token.text;
24967 if (t === e1 || t === e2 || t === e3 || t === e4 ||
24968 (!e1 && !e2 && !e3 && !e4)) {
24975 expect: function(e1, e2, e3, e4) {
24976 var token = this.peek(e1, e2, e3, e4);
24978 this.tokens.shift();
24985 'this': {type: AST.ThisExpression },
24986 '$locals': {type: AST.LocalsExpression }
24990 function ifDefined(v, d) {
24991 return typeof v !== 'undefined' ? v : d;
24994 function plusFn(l, r) {
24995 if (typeof l === 'undefined') return r;
24996 if (typeof r === 'undefined') return l;
25000 function isStateless($filter, filterName) {
25001 var fn = $filter(filterName);
25002 return !fn.$stateful;
25005 function findConstantAndWatchExpressions(ast, $filter) {
25008 var isStatelessFilter;
25009 switch (ast.type) {
25011 allConstants = true;
25012 forEach(ast.body, function(expr) {
25013 findConstantAndWatchExpressions(expr.expression, $filter);
25014 allConstants = allConstants && expr.expression.constant;
25016 ast.constant = allConstants;
25019 ast.constant = true;
25022 case AST.UnaryExpression:
25023 findConstantAndWatchExpressions(ast.argument, $filter);
25024 ast.constant = ast.argument.constant;
25025 ast.toWatch = ast.argument.toWatch;
25027 case AST.BinaryExpression:
25028 findConstantAndWatchExpressions(ast.left, $filter);
25029 findConstantAndWatchExpressions(ast.right, $filter);
25030 ast.constant = ast.left.constant && ast.right.constant;
25031 ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
25033 case AST.LogicalExpression:
25034 findConstantAndWatchExpressions(ast.left, $filter);
25035 findConstantAndWatchExpressions(ast.right, $filter);
25036 ast.constant = ast.left.constant && ast.right.constant;
25037 ast.toWatch = ast.constant ? [] : [ast];
25039 case AST.ConditionalExpression:
25040 findConstantAndWatchExpressions(ast.test, $filter);
25041 findConstantAndWatchExpressions(ast.alternate, $filter);
25042 findConstantAndWatchExpressions(ast.consequent, $filter);
25043 ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
25044 ast.toWatch = ast.constant ? [] : [ast];
25046 case AST.Identifier:
25047 ast.constant = false;
25048 ast.toWatch = [ast];
25050 case AST.MemberExpression:
25051 findConstantAndWatchExpressions(ast.object, $filter);
25052 if (ast.computed) {
25053 findConstantAndWatchExpressions(ast.property, $filter);
25055 ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
25056 ast.toWatch = [ast];
25058 case AST.CallExpression:
25059 isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;
25060 allConstants = isStatelessFilter;
25062 forEach(ast.arguments, function(expr) {
25063 findConstantAndWatchExpressions(expr, $filter);
25064 allConstants = allConstants && expr.constant;
25065 if (!expr.constant) {
25066 argsToWatch.push.apply(argsToWatch, expr.toWatch);
25069 ast.constant = allConstants;
25070 ast.toWatch = isStatelessFilter ? argsToWatch : [ast];
25072 case AST.AssignmentExpression:
25073 findConstantAndWatchExpressions(ast.left, $filter);
25074 findConstantAndWatchExpressions(ast.right, $filter);
25075 ast.constant = ast.left.constant && ast.right.constant;
25076 ast.toWatch = [ast];
25078 case AST.ArrayExpression:
25079 allConstants = true;
25081 forEach(ast.elements, function(expr) {
25082 findConstantAndWatchExpressions(expr, $filter);
25083 allConstants = allConstants && expr.constant;
25084 if (!expr.constant) {
25085 argsToWatch.push.apply(argsToWatch, expr.toWatch);
25088 ast.constant = allConstants;
25089 ast.toWatch = argsToWatch;
25091 case AST.ObjectExpression:
25092 allConstants = true;
25094 forEach(ast.properties, function(property) {
25095 findConstantAndWatchExpressions(property.value, $filter);
25096 allConstants = allConstants && property.value.constant && !property.computed;
25097 if (!property.value.constant) {
25098 argsToWatch.push.apply(argsToWatch, property.value.toWatch);
25101 ast.constant = allConstants;
25102 ast.toWatch = argsToWatch;
25104 case AST.ThisExpression:
25105 ast.constant = false;
25108 case AST.LocalsExpression:
25109 ast.constant = false;
25115 function getInputs(body) {
25116 if (body.length !== 1) return;
25117 var lastExpression = body[0].expression;
25118 var candidate = lastExpression.toWatch;
25119 if (candidate.length !== 1) return candidate;
25120 return candidate[0] !== lastExpression ? candidate : undefined;
25123 function isAssignable(ast) {
25124 return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
25127 function assignableAST(ast) {
25128 if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
25129 return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
25133 function isLiteral(ast) {
25134 return ast.body.length === 0 ||
25135 ast.body.length === 1 && (
25136 ast.body[0].expression.type === AST.Literal ||
25137 ast.body[0].expression.type === AST.ArrayExpression ||
25138 ast.body[0].expression.type === AST.ObjectExpression);
25141 function isConstant(ast) {
25142 return ast.constant;
25145 function ASTCompiler(astBuilder, $filter) {
25146 this.astBuilder = astBuilder;
25147 this.$filter = $filter;
25150 ASTCompiler.prototype = {
25151 compile: function(expression, expensiveChecks) {
25153 var ast = this.astBuilder.ast(expression);
25157 expensiveChecks: expensiveChecks,
25158 fn: {vars: [], body: [], own: {}},
25159 assign: {vars: [], body: [], own: {}},
25162 findConstantAndWatchExpressions(ast, self.$filter);
25165 this.stage = 'assign';
25166 if ((assignable = assignableAST(ast))) {
25167 this.state.computing = 'assign';
25168 var result = this.nextId();
25169 this.recurse(assignable, result);
25170 this.return_(result);
25171 extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
25173 var toWatch = getInputs(ast.body);
25174 self.stage = 'inputs';
25175 forEach(toWatch, function(watch, key) {
25176 var fnKey = 'fn' + key;
25177 self.state[fnKey] = {vars: [], body: [], own: {}};
25178 self.state.computing = fnKey;
25179 var intoId = self.nextId();
25180 self.recurse(watch, intoId);
25181 self.return_(intoId);
25182 self.state.inputs.push(fnKey);
25183 watch.watchId = key;
25185 this.state.computing = 'fn';
25186 this.stage = 'main';
25189 // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
25190 // This is a workaround for this until we do a better job at only removing the prefix only when we should.
25191 '"' + this.USE + ' ' + this.STRICT + '";\n' +
25192 this.filterPrefix() +
25193 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
25198 // eslint-disable-next-line no-new-func
25199 var fn = (new Function('$filter',
25200 'ensureSafeMemberName',
25201 'ensureSafeObject',
25202 'ensureSafeFunction',
25204 'ensureSafeAssignContext',
25210 ensureSafeMemberName,
25212 ensureSafeFunction,
25214 ensureSafeAssignContext,
25218 this.state = this.stage = undefined;
25219 fn.literal = isLiteral(ast);
25220 fn.constant = isConstant(ast);
25228 watchFns: function() {
25230 var fns = this.state.inputs;
25232 forEach(fns, function(name) {
25233 result.push('var ' + name + '=' + self.generateFunction(name, 's'));
25236 result.push('fn.inputs=[' + fns.join(',') + '];');
25238 return result.join('');
25241 generateFunction: function(name, params) {
25242 return 'function(' + params + '){' +
25243 this.varsPrefix(name) +
25248 filterPrefix: function() {
25251 forEach(this.state.filters, function(id, filter) {
25252 parts.push(id + '=$filter(' + self.escape(filter) + ')');
25254 if (parts.length) return 'var ' + parts.join(',') + ';';
25258 varsPrefix: function(section) {
25259 return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
25262 body: function(section) {
25263 return this.state[section].body.join('');
25266 recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
25267 var left, right, self = this, args, expression, computed;
25268 recursionFn = recursionFn || noop;
25269 if (!skipWatchIdCheck && isDefined(ast.watchId)) {
25270 intoId = intoId || this.nextId();
25272 this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
25273 this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
25277 switch (ast.type) {
25279 forEach(ast.body, function(expression, pos) {
25280 self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
25281 if (pos !== ast.body.length - 1) {
25282 self.current().body.push(right, ';');
25284 self.return_(right);
25289 expression = this.escape(ast.value);
25290 this.assign(intoId, expression);
25291 recursionFn(expression);
25293 case AST.UnaryExpression:
25294 this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
25295 expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
25296 this.assign(intoId, expression);
25297 recursionFn(expression);
25299 case AST.BinaryExpression:
25300 this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
25301 this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
25302 if (ast.operator === '+') {
25303 expression = this.plus(left, right);
25304 } else if (ast.operator === '-') {
25305 expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
25307 expression = '(' + left + ')' + ast.operator + '(' + right + ')';
25309 this.assign(intoId, expression);
25310 recursionFn(expression);
25312 case AST.LogicalExpression:
25313 intoId = intoId || this.nextId();
25314 self.recurse(ast.left, intoId);
25315 self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
25316 recursionFn(intoId);
25318 case AST.ConditionalExpression:
25319 intoId = intoId || this.nextId();
25320 self.recurse(ast.test, intoId);
25321 self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
25322 recursionFn(intoId);
25324 case AST.Identifier:
25325 intoId = intoId || this.nextId();
25327 nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
25328 nameId.computed = false;
25329 nameId.name = ast.name;
25331 ensureSafeMemberName(ast.name);
25332 self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
25334 self.if_(self.stage === 'inputs' || 's', function() {
25335 if (create && create !== 1) {
25337 self.not(self.nonComputedMember('s', ast.name)),
25338 self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
25340 self.assign(intoId, self.nonComputedMember('s', ast.name));
25342 }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
25344 if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
25345 self.addEnsureSafeObject(intoId);
25347 recursionFn(intoId);
25349 case AST.MemberExpression:
25350 left = nameId && (nameId.context = this.nextId()) || this.nextId();
25351 intoId = intoId || this.nextId();
25352 self.recurse(ast.object, left, undefined, function() {
25353 self.if_(self.notNull(left), function() {
25354 if (create && create !== 1) {
25355 self.addEnsureSafeAssignContext(left);
25357 if (ast.computed) {
25358 right = self.nextId();
25359 self.recurse(ast.property, right);
25360 self.getStringValue(right);
25361 self.addEnsureSafeMemberName(right);
25362 if (create && create !== 1) {
25363 self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
25365 expression = self.ensureSafeObject(self.computedMember(left, right));
25366 self.assign(intoId, expression);
25368 nameId.computed = true;
25369 nameId.name = right;
25372 ensureSafeMemberName(ast.property.name);
25373 if (create && create !== 1) {
25374 self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
25376 expression = self.nonComputedMember(left, ast.property.name);
25377 if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
25378 expression = self.ensureSafeObject(expression);
25380 self.assign(intoId, expression);
25382 nameId.computed = false;
25383 nameId.name = ast.property.name;
25387 self.assign(intoId, 'undefined');
25389 recursionFn(intoId);
25392 case AST.CallExpression:
25393 intoId = intoId || this.nextId();
25395 right = self.filter(ast.callee.name);
25397 forEach(ast.arguments, function(expr) {
25398 var argument = self.nextId();
25399 self.recurse(expr, argument);
25400 args.push(argument);
25402 expression = right + '(' + args.join(',') + ')';
25403 self.assign(intoId, expression);
25404 recursionFn(intoId);
25406 right = self.nextId();
25409 self.recurse(ast.callee, right, left, function() {
25410 self.if_(self.notNull(right), function() {
25411 self.addEnsureSafeFunction(right);
25412 forEach(ast.arguments, function(expr) {
25413 self.recurse(expr, self.nextId(), undefined, function(argument) {
25414 args.push(self.ensureSafeObject(argument));
25418 if (!self.state.expensiveChecks) {
25419 self.addEnsureSafeObject(left.context);
25421 expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
25423 expression = right + '(' + args.join(',') + ')';
25425 expression = self.ensureSafeObject(expression);
25426 self.assign(intoId, expression);
25428 self.assign(intoId, 'undefined');
25430 recursionFn(intoId);
25434 case AST.AssignmentExpression:
25435 right = this.nextId();
25437 this.recurse(ast.left, undefined, left, function() {
25438 self.if_(self.notNull(left.context), function() {
25439 self.recurse(ast.right, right);
25440 self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
25441 self.addEnsureSafeAssignContext(left.context);
25442 expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
25443 self.assign(intoId, expression);
25444 recursionFn(intoId || expression);
25448 case AST.ArrayExpression:
25450 forEach(ast.elements, function(expr) {
25451 self.recurse(expr, self.nextId(), undefined, function(argument) {
25452 args.push(argument);
25455 expression = '[' + args.join(',') + ']';
25456 this.assign(intoId, expression);
25457 recursionFn(expression);
25459 case AST.ObjectExpression:
25462 forEach(ast.properties, function(property) {
25463 if (property.computed) {
25468 intoId = intoId || this.nextId();
25469 this.assign(intoId, '{}');
25470 forEach(ast.properties, function(property) {
25471 if (property.computed) {
25472 left = self.nextId();
25473 self.recurse(property.key, left);
25475 left = property.key.type === AST.Identifier ?
25476 property.key.name :
25477 ('' + property.key.value);
25479 right = self.nextId();
25480 self.recurse(property.value, right);
25481 self.assign(self.member(intoId, left, property.computed), right);
25484 forEach(ast.properties, function(property) {
25485 self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
25486 args.push(self.escape(
25487 property.key.type === AST.Identifier ? property.key.name :
25488 ('' + property.key.value)) +
25492 expression = '{' + args.join(',') + '}';
25493 this.assign(intoId, expression);
25495 recursionFn(intoId || expression);
25497 case AST.ThisExpression:
25498 this.assign(intoId, 's');
25501 case AST.LocalsExpression:
25502 this.assign(intoId, 'l');
25505 case AST.NGValueParameter:
25506 this.assign(intoId, 'v');
25512 getHasOwnProperty: function(element, property) {
25513 var key = element + '.' + property;
25514 var own = this.current().own;
25515 if (!own.hasOwnProperty(key)) {
25516 own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
25521 assign: function(id, value) {
25523 this.current().body.push(id, '=', value, ';');
25527 filter: function(filterName) {
25528 if (!this.state.filters.hasOwnProperty(filterName)) {
25529 this.state.filters[filterName] = this.nextId(true);
25531 return this.state.filters[filterName];
25534 ifDefined: function(id, defaultValue) {
25535 return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
25538 plus: function(left, right) {
25539 return 'plus(' + left + ',' + right + ')';
25542 return_: function(id) {
25543 this.current().body.push('return ', id, ';');
25546 if_: function(test, alternate, consequent) {
25547 if (test === true) {
25550 var body = this.current().body;
25551 body.push('if(', test, '){');
25555 body.push('else{');
25562 not: function(expression) {
25563 return '!(' + expression + ')';
25566 notNull: function(expression) {
25567 return expression + '!=null';
25570 nonComputedMember: function(left, right) {
25571 var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;
25572 var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
25573 if (SAFE_IDENTIFIER.test(right)) {
25574 return left + '.' + right;
25576 return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
25580 computedMember: function(left, right) {
25581 return left + '[' + right + ']';
25584 member: function(left, right, computed) {
25585 if (computed) return this.computedMember(left, right);
25586 return this.nonComputedMember(left, right);
25589 addEnsureSafeObject: function(item) {
25590 this.current().body.push(this.ensureSafeObject(item), ';');
25593 addEnsureSafeMemberName: function(item) {
25594 this.current().body.push(this.ensureSafeMemberName(item), ';');
25597 addEnsureSafeFunction: function(item) {
25598 this.current().body.push(this.ensureSafeFunction(item), ';');
25601 addEnsureSafeAssignContext: function(item) {
25602 this.current().body.push(this.ensureSafeAssignContext(item), ';');
25605 ensureSafeObject: function(item) {
25606 return 'ensureSafeObject(' + item + ',text)';
25609 ensureSafeMemberName: function(item) {
25610 return 'ensureSafeMemberName(' + item + ',text)';
25613 ensureSafeFunction: function(item) {
25614 return 'ensureSafeFunction(' + item + ',text)';
25617 getStringValue: function(item) {
25618 this.assign(item, 'getStringValue(' + item + ')');
25621 ensureSafeAssignContext: function(item) {
25622 return 'ensureSafeAssignContext(' + item + ',text)';
25625 lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
25627 return function() {
25628 self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
25632 lazyAssign: function(id, value) {
25634 return function() {
25635 self.assign(id, value);
25639 stringEscapeRegex: /[^ a-zA-Z0-9]/g,
25641 stringEscapeFn: function(c) {
25642 return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
25645 escape: function(value) {
25646 if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\'';
25647 if (isNumber(value)) return value.toString();
25648 if (value === true) return 'true';
25649 if (value === false) return 'false';
25650 if (value === null) return 'null';
25651 if (typeof value === 'undefined') return 'undefined';
25653 throw $parseMinErr('esc', 'IMPOSSIBLE');
25656 nextId: function(skip, init) {
25657 var id = 'v' + (this.state.nextId++);
25659 this.current().vars.push(id + (init ? '=' + init : ''));
25664 current: function() {
25665 return this.state[this.state.computing];
25670 function ASTInterpreter(astBuilder, $filter) {
25671 this.astBuilder = astBuilder;
25672 this.$filter = $filter;
25675 ASTInterpreter.prototype = {
25676 compile: function(expression, expensiveChecks) {
25678 var ast = this.astBuilder.ast(expression);
25679 this.expression = expression;
25680 this.expensiveChecks = expensiveChecks;
25681 findConstantAndWatchExpressions(ast, self.$filter);
25684 if ((assignable = assignableAST(ast))) {
25685 assign = this.recurse(assignable);
25687 var toWatch = getInputs(ast.body);
25691 forEach(toWatch, function(watch, key) {
25692 var input = self.recurse(watch);
25693 watch.input = input;
25694 inputs.push(input);
25695 watch.watchId = key;
25698 var expressions = [];
25699 forEach(ast.body, function(expression) {
25700 expressions.push(self.recurse(expression.expression));
25702 var fn = ast.body.length === 0 ? noop :
25703 ast.body.length === 1 ? expressions[0] :
25704 function(scope, locals) {
25706 forEach(expressions, function(exp) {
25707 lastValue = exp(scope, locals);
25712 fn.assign = function(scope, value, locals) {
25713 return assign(scope, locals, value);
25717 fn.inputs = inputs;
25719 fn.literal = isLiteral(ast);
25720 fn.constant = isConstant(ast);
25724 recurse: function(ast, context, create) {
25725 var left, right, self = this, args;
25727 return this.inputs(ast.input, ast.watchId);
25729 switch (ast.type) {
25731 return this.value(ast.value, context);
25732 case AST.UnaryExpression:
25733 right = this.recurse(ast.argument);
25734 return this['unary' + ast.operator](right, context);
25735 case AST.BinaryExpression:
25736 left = this.recurse(ast.left);
25737 right = this.recurse(ast.right);
25738 return this['binary' + ast.operator](left, right, context);
25739 case AST.LogicalExpression:
25740 left = this.recurse(ast.left);
25741 right = this.recurse(ast.right);
25742 return this['binary' + ast.operator](left, right, context);
25743 case AST.ConditionalExpression:
25744 return this['ternary?:'](
25745 this.recurse(ast.test),
25746 this.recurse(ast.alternate),
25747 this.recurse(ast.consequent),
25750 case AST.Identifier:
25751 ensureSafeMemberName(ast.name, self.expression);
25752 return self.identifier(ast.name,
25753 self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
25754 context, create, self.expression);
25755 case AST.MemberExpression:
25756 left = this.recurse(ast.object, false, !!create);
25757 if (!ast.computed) {
25758 ensureSafeMemberName(ast.property.name, self.expression);
25759 right = ast.property.name;
25761 if (ast.computed) right = this.recurse(ast.property);
25762 return ast.computed ?
25763 this.computedMember(left, right, context, create, self.expression) :
25764 this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
25765 case AST.CallExpression:
25767 forEach(ast.arguments, function(expr) {
25768 args.push(self.recurse(expr));
25770 if (ast.filter) right = this.$filter(ast.callee.name);
25771 if (!ast.filter) right = this.recurse(ast.callee, true);
25772 return ast.filter ?
25773 function(scope, locals, assign, inputs) {
25775 for (var i = 0; i < args.length; ++i) {
25776 values.push(args[i](scope, locals, assign, inputs));
25778 var value = right.apply(undefined, values, inputs);
25779 return context ? {context: undefined, name: undefined, value: value} : value;
25781 function(scope, locals, assign, inputs) {
25782 var rhs = right(scope, locals, assign, inputs);
25784 if (rhs.value != null) {
25785 ensureSafeObject(rhs.context, self.expression);
25786 ensureSafeFunction(rhs.value, self.expression);
25788 for (var i = 0; i < args.length; ++i) {
25789 values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
25791 value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
25793 return context ? {value: value} : value;
25795 case AST.AssignmentExpression:
25796 left = this.recurse(ast.left, true, 1);
25797 right = this.recurse(ast.right);
25798 return function(scope, locals, assign, inputs) {
25799 var lhs = left(scope, locals, assign, inputs);
25800 var rhs = right(scope, locals, assign, inputs);
25801 ensureSafeObject(lhs.value, self.expression);
25802 ensureSafeAssignContext(lhs.context);
25803 lhs.context[lhs.name] = rhs;
25804 return context ? {value: rhs} : rhs;
25806 case AST.ArrayExpression:
25808 forEach(ast.elements, function(expr) {
25809 args.push(self.recurse(expr));
25811 return function(scope, locals, assign, inputs) {
25813 for (var i = 0; i < args.length; ++i) {
25814 value.push(args[i](scope, locals, assign, inputs));
25816 return context ? {value: value} : value;
25818 case AST.ObjectExpression:
25820 forEach(ast.properties, function(property) {
25821 if (property.computed) {
25822 args.push({key: self.recurse(property.key),
25824 value: self.recurse(property.value)
25827 args.push({key: property.key.type === AST.Identifier ?
25828 property.key.name :
25829 ('' + property.key.value),
25831 value: self.recurse(property.value)
25835 return function(scope, locals, assign, inputs) {
25837 for (var i = 0; i < args.length; ++i) {
25838 if (args[i].computed) {
25839 value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
25841 value[args[i].key] = args[i].value(scope, locals, assign, inputs);
25844 return context ? {value: value} : value;
25846 case AST.ThisExpression:
25847 return function(scope) {
25848 return context ? {value: scope} : scope;
25850 case AST.LocalsExpression:
25851 return function(scope, locals) {
25852 return context ? {value: locals} : locals;
25854 case AST.NGValueParameter:
25855 return function(scope, locals, assign) {
25856 return context ? {value: assign} : assign;
25861 'unary+': function(argument, context) {
25862 return function(scope, locals, assign, inputs) {
25863 var arg = argument(scope, locals, assign, inputs);
25864 if (isDefined(arg)) {
25869 return context ? {value: arg} : arg;
25872 'unary-': function(argument, context) {
25873 return function(scope, locals, assign, inputs) {
25874 var arg = argument(scope, locals, assign, inputs);
25875 if (isDefined(arg)) {
25880 return context ? {value: arg} : arg;
25883 'unary!': function(argument, context) {
25884 return function(scope, locals, assign, inputs) {
25885 var arg = !argument(scope, locals, assign, inputs);
25886 return context ? {value: arg} : arg;
25889 'binary+': function(left, right, context) {
25890 return function(scope, locals, assign, inputs) {
25891 var lhs = left(scope, locals, assign, inputs);
25892 var rhs = right(scope, locals, assign, inputs);
25893 var arg = plusFn(lhs, rhs);
25894 return context ? {value: arg} : arg;
25897 'binary-': function(left, right, context) {
25898 return function(scope, locals, assign, inputs) {
25899 var lhs = left(scope, locals, assign, inputs);
25900 var rhs = right(scope, locals, assign, inputs);
25901 var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
25902 return context ? {value: arg} : arg;
25905 'binary*': function(left, right, context) {
25906 return function(scope, locals, assign, inputs) {
25907 var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
25908 return context ? {value: arg} : arg;
25911 'binary/': function(left, right, context) {
25912 return function(scope, locals, assign, inputs) {
25913 var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
25914 return context ? {value: arg} : arg;
25917 'binary%': function(left, right, context) {
25918 return function(scope, locals, assign, inputs) {
25919 var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
25920 return context ? {value: arg} : arg;
25923 'binary===': function(left, right, context) {
25924 return function(scope, locals, assign, inputs) {
25925 var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
25926 return context ? {value: arg} : arg;
25929 'binary!==': function(left, right, context) {
25930 return function(scope, locals, assign, inputs) {
25931 var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
25932 return context ? {value: arg} : arg;
25935 'binary==': function(left, right, context) {
25936 return function(scope, locals, assign, inputs) {
25937 // eslint-disable-next-line eqeqeq
25938 var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
25939 return context ? {value: arg} : arg;
25942 'binary!=': function(left, right, context) {
25943 return function(scope, locals, assign, inputs) {
25944 // eslint-disable-next-line eqeqeq
25945 var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
25946 return context ? {value: arg} : arg;
25949 'binary<': function(left, right, context) {
25950 return function(scope, locals, assign, inputs) {
25951 var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
25952 return context ? {value: arg} : arg;
25955 'binary>': function(left, right, context) {
25956 return function(scope, locals, assign, inputs) {
25957 var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
25958 return context ? {value: arg} : arg;
25961 'binary<=': function(left, right, context) {
25962 return function(scope, locals, assign, inputs) {
25963 var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
25964 return context ? {value: arg} : arg;
25967 'binary>=': function(left, right, context) {
25968 return function(scope, locals, assign, inputs) {
25969 var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
25970 return context ? {value: arg} : arg;
25973 'binary&&': function(left, right, context) {
25974 return function(scope, locals, assign, inputs) {
25975 var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
25976 return context ? {value: arg} : arg;
25979 'binary||': function(left, right, context) {
25980 return function(scope, locals, assign, inputs) {
25981 var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
25982 return context ? {value: arg} : arg;
25985 'ternary?:': function(test, alternate, consequent, context) {
25986 return function(scope, locals, assign, inputs) {
25987 var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
25988 return context ? {value: arg} : arg;
25991 value: function(value, context) {
25992 return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
25994 identifier: function(name, expensiveChecks, context, create, expression) {
25995 return function(scope, locals, assign, inputs) {
25996 var base = locals && (name in locals) ? locals : scope;
25997 if (create && create !== 1 && base && !(base[name])) {
26000 var value = base ? base[name] : undefined;
26001 if (expensiveChecks) {
26002 ensureSafeObject(value, expression);
26005 return {context: base, name: name, value: value};
26011 computedMember: function(left, right, context, create, expression) {
26012 return function(scope, locals, assign, inputs) {
26013 var lhs = left(scope, locals, assign, inputs);
26017 rhs = right(scope, locals, assign, inputs);
26018 rhs = getStringValue(rhs);
26019 ensureSafeMemberName(rhs, expression);
26020 if (create && create !== 1) {
26021 ensureSafeAssignContext(lhs);
26022 if (lhs && !(lhs[rhs])) {
26027 ensureSafeObject(value, expression);
26030 return {context: lhs, name: rhs, value: value};
26036 nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
26037 return function(scope, locals, assign, inputs) {
26038 var lhs = left(scope, locals, assign, inputs);
26039 if (create && create !== 1) {
26040 ensureSafeAssignContext(lhs);
26041 if (lhs && !(lhs[right])) {
26045 var value = lhs != null ? lhs[right] : undefined;
26046 if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
26047 ensureSafeObject(value, expression);
26050 return {context: lhs, name: right, value: value};
26056 inputs: function(input, watchId) {
26057 return function(scope, value, locals, inputs) {
26058 if (inputs) return inputs[watchId];
26059 return input(scope, value, locals);
26067 var Parser = function Parser(lexer, $filter, options) {
26068 this.lexer = lexer;
26069 this.$filter = $filter;
26070 this.options = options;
26071 this.ast = new AST(lexer, options);
26072 this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
26073 new ASTCompiler(this.ast, $filter);
26076 Parser.prototype = {
26077 constructor: Parser,
26079 parse: function(text) {
26080 return this.astCompiler.compile(text, this.options.expensiveChecks);
26084 function isPossiblyDangerousMemberName(name) {
26085 return name === 'constructor';
26088 function getValueOf(value) {
26089 return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
26092 ///////////////////////////////////
26101 * Converts Angular {@link guide/expression expression} into a function.
26104 * var getter = $parse('user.name');
26105 * var setter = getter.assign;
26106 * var context = {user:{name:'angular'}};
26107 * var locals = {user:{name:'local'}};
26109 * expect(getter(context)).toEqual('angular');
26110 * setter(context, 'newValue');
26111 * expect(context.user.name).toEqual('newValue');
26112 * expect(getter(context, locals)).toEqual('local');
26116 * @param {string} expression String expression to compile.
26117 * @returns {function(context, locals)} a function which represents the compiled expression:
26119 * * `context` – `{object}` – an object against which any expressions embedded in the strings
26120 * are evaluated against (typically a scope object).
26121 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
26124 * The returned function also has the following properties:
26125 * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
26127 * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
26128 * constant literals.
26129 * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
26130 * set to a function to change its value on the given context.
26137 * @name $parseProvider
26141 * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
26144 function $ParseProvider() {
26145 var cacheDefault = createMap();
26146 var cacheExpensive = createMap();
26151 'undefined': undefined
26153 var identStart, identContinue;
26157 * @name $parseProvider#addLiteral
26160 * Configure $parse service to add literal values that will be present as literal at expressions.
26162 * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
26163 * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
26166 this.addLiteral = function(literalName, literalValue) {
26167 literals[literalName] = literalValue;
26172 * @name $parseProvider#setIdentifierFns
26176 * Allows defining the set of characters that are allowed in Angular expressions. The function
26177 * `identifierStart` will get called to know if a given character is a valid character to be the
26178 * first character for an identifier. The function `identifierContinue` will get called to know if
26179 * a given character is a valid character to be a follow-up identifier character. The functions
26180 * `identifierStart` and `identifierContinue` will receive as arguments the single character to be
26181 * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
26182 * mind that the `string` parameter can be two characters long depending on the character
26183 * representation. It is expected for the function to return `true` or `false`, whether that
26184 * character is allowed or not.
26186 * Since this function will be called extensively, keep the implementation of these functions fast,
26187 * as the performance of these functions have a direct impact on the expressions parsing speed.
26189 * @param {function=} identifierStart The function that will decide whether the given character is
26190 * a valid identifier start character.
26191 * @param {function=} identifierContinue The function that will decide whether the given character is
26192 * a valid identifier continue character.
26194 this.setIdentifierFns = function(identifierStart, identifierContinue) {
26195 identStart = identifierStart;
26196 identContinue = identifierContinue;
26200 this.$get = ['$filter', function($filter) {
26201 var noUnsafeEval = csp().noUnsafeEval;
26202 var $parseOptions = {
26204 expensiveChecks: false,
26205 literals: copy(literals),
26206 isIdentifierStart: isFunction(identStart) && identStart,
26207 isIdentifierContinue: isFunction(identContinue) && identContinue
26209 $parseOptionsExpensive = {
26211 expensiveChecks: true,
26212 literals: copy(literals),
26213 isIdentifierStart: isFunction(identStart) && identStart,
26214 isIdentifierContinue: isFunction(identContinue) && identContinue
26216 var runningChecksEnabled = false;
26218 $parse.$$runningExpensiveChecks = function() {
26219 return runningChecksEnabled;
26224 function $parse(exp, interceptorFn, expensiveChecks) {
26225 var parsedExpression, oneTime, cacheKey;
26227 expensiveChecks = expensiveChecks || runningChecksEnabled;
26229 switch (typeof exp) {
26234 var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
26235 parsedExpression = cache[cacheKey];
26237 if (!parsedExpression) {
26238 if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
26240 exp = exp.substring(2);
26242 var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
26243 var lexer = new Lexer(parseOptions);
26244 var parser = new Parser(lexer, $filter, parseOptions);
26245 parsedExpression = parser.parse(exp);
26246 if (parsedExpression.constant) {
26247 parsedExpression.$$watchDelegate = constantWatchDelegate;
26248 } else if (oneTime) {
26249 parsedExpression.$$watchDelegate = parsedExpression.literal ?
26250 oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
26251 } else if (parsedExpression.inputs) {
26252 parsedExpression.$$watchDelegate = inputsWatchDelegate;
26254 if (expensiveChecks) {
26255 parsedExpression = expensiveChecksInterceptor(parsedExpression);
26257 cache[cacheKey] = parsedExpression;
26259 return addInterceptor(parsedExpression, interceptorFn);
26262 return addInterceptor(exp, interceptorFn);
26265 return addInterceptor(noop, interceptorFn);
26269 function expensiveChecksInterceptor(fn) {
26270 if (!fn) return fn;
26271 expensiveCheckFn.$$watchDelegate = fn.$$watchDelegate;
26272 expensiveCheckFn.assign = expensiveChecksInterceptor(fn.assign);
26273 expensiveCheckFn.constant = fn.constant;
26274 expensiveCheckFn.literal = fn.literal;
26275 for (var i = 0; fn.inputs && i < fn.inputs.length; ++i) {
26276 fn.inputs[i] = expensiveChecksInterceptor(fn.inputs[i]);
26278 expensiveCheckFn.inputs = fn.inputs;
26280 return expensiveCheckFn;
26282 function expensiveCheckFn(scope, locals, assign, inputs) {
26283 var expensiveCheckOldValue = runningChecksEnabled;
26284 runningChecksEnabled = true;
26286 return fn(scope, locals, assign, inputs);
26288 runningChecksEnabled = expensiveCheckOldValue;
26293 function expressionInputDirtyCheck(newValue, oldValueOfValue) {
26295 if (newValue == null || oldValueOfValue == null) { // null/undefined
26296 return newValue === oldValueOfValue;
26299 if (typeof newValue === 'object') {
26301 // attempt to convert the value to a primitive type
26302 // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
26303 // be cheaply dirty-checked
26304 newValue = getValueOf(newValue);
26306 if (typeof newValue === 'object') {
26307 // objects/arrays are not supported - deep-watching them would be too expensive
26311 // fall-through to the primitive equality check
26315 // eslint-disable-next-line no-self-compare
26316 return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
26319 function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
26320 var inputExpressions = parsedExpression.inputs;
26323 if (inputExpressions.length === 1) {
26324 var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
26325 inputExpressions = inputExpressions[0];
26326 return scope.$watch(function expressionInputWatch(scope) {
26327 var newInputValue = inputExpressions(scope);
26328 if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
26329 lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
26330 oldInputValueOf = newInputValue && getValueOf(newInputValue);
26333 }, listener, objectEquality, prettyPrintExpression);
26336 var oldInputValueOfValues = [];
26337 var oldInputValues = [];
26338 for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
26339 oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
26340 oldInputValues[i] = null;
26343 return scope.$watch(function expressionInputsWatch(scope) {
26344 var changed = false;
26346 for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
26347 var newInputValue = inputExpressions[i](scope);
26348 if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
26349 oldInputValues[i] = newInputValue;
26350 oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
26355 lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
26359 }, listener, objectEquality, prettyPrintExpression);
26362 function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
26363 var unwatch, lastValue;
26364 unwatch = scope.$watch(function oneTimeWatch(scope) {
26365 return parsedExpression(scope);
26366 }, /** @this */ function oneTimeListener(value, old, scope) {
26368 if (isFunction(listener)) {
26369 listener.apply(this, arguments);
26371 if (isDefined(value)) {
26372 scope.$$postDigest(function() {
26373 if (isDefined(lastValue)) {
26378 }, objectEquality);
26382 function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
26383 var unwatch, lastValue;
26384 unwatch = scope.$watch(function oneTimeWatch(scope) {
26385 return parsedExpression(scope);
26386 }, /** @this */ function oneTimeListener(value, old, scope) {
26388 if (isFunction(listener)) {
26389 listener.call(this, value, old, scope);
26391 if (isAllDefined(value)) {
26392 scope.$$postDigest(function() {
26393 if (isAllDefined(lastValue)) unwatch();
26396 }, objectEquality);
26400 function isAllDefined(value) {
26401 var allDefined = true;
26402 forEach(value, function(val) {
26403 if (!isDefined(val)) allDefined = false;
26409 function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
26410 var unwatch = scope.$watch(function constantWatch(scope) {
26412 return parsedExpression(scope);
26413 }, listener, objectEquality);
26417 function addInterceptor(parsedExpression, interceptorFn) {
26418 if (!interceptorFn) return parsedExpression;
26419 var watchDelegate = parsedExpression.$$watchDelegate;
26420 var useInputs = false;
26423 watchDelegate !== oneTimeLiteralWatchDelegate &&
26424 watchDelegate !== oneTimeWatchDelegate;
26426 var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
26427 var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
26428 return interceptorFn(value, scope, locals);
26429 } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
26430 var value = parsedExpression(scope, locals, assign, inputs);
26431 var result = interceptorFn(value, scope, locals);
26432 // we only return the interceptor's result if the
26433 // initial value is defined (for bind-once)
26434 return isDefined(value) ? result : value;
26437 // Propagate $$watchDelegates other then inputsWatchDelegate
26438 if (parsedExpression.$$watchDelegate &&
26439 parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
26440 fn.$$watchDelegate = parsedExpression.$$watchDelegate;
26441 } else if (!interceptorFn.$stateful) {
26442 // If there is an interceptor, but no watchDelegate then treat the interceptor like
26443 // we treat filters - it is assumed to be a pure function unless flagged with $stateful
26444 fn.$$watchDelegate = inputsWatchDelegate;
26445 useInputs = !parsedExpression.inputs;
26446 fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
26457 * @requires $rootScope
26461 * A service that helps you run functions asynchronously, and use their return values (or exceptions)
26462 * when they are done processing.
26464 * This is an implementation of promises/deferred objects inspired by
26465 * [Kris Kowal's Q](https://github.com/kriskowal/q).
26467 * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
26468 * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
26472 * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
26473 * function as the first argument. This is similar to the native Promise implementation from ES6,
26474 * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
26476 * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
26479 * It can be used like so:
26482 * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
26483 * // are available in the current lexical scope (they could have been injected or passed in).
26485 * function asyncGreet(name) {
26486 * // perform some asynchronous operation, resolve or reject the promise when appropriate.
26487 * return $q(function(resolve, reject) {
26488 * setTimeout(function() {
26489 * if (okToGreet(name)) {
26490 * resolve('Hello, ' + name + '!');
26492 * reject('Greeting ' + name + ' is not allowed.');
26498 * var promise = asyncGreet('Robin Hood');
26499 * promise.then(function(greeting) {
26500 * alert('Success: ' + greeting);
26501 * }, function(reason) {
26502 * alert('Failed: ' + reason);
26506 * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
26508 * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
26510 * However, the more traditional CommonJS-style usage is still available, and documented below.
26512 * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
26513 * interface for interacting with an object that represents the result of an action that is
26514 * performed asynchronously, and may or may not be finished at any given point in time.
26516 * From the perspective of dealing with error handling, deferred and promise APIs are to
26517 * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
26520 * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
26521 * // are available in the current lexical scope (they could have been injected or passed in).
26523 * function asyncGreet(name) {
26524 * var deferred = $q.defer();
26526 * setTimeout(function() {
26527 * deferred.notify('About to greet ' + name + '.');
26529 * if (okToGreet(name)) {
26530 * deferred.resolve('Hello, ' + name + '!');
26532 * deferred.reject('Greeting ' + name + ' is not allowed.');
26536 * return deferred.promise;
26539 * var promise = asyncGreet('Robin Hood');
26540 * promise.then(function(greeting) {
26541 * alert('Success: ' + greeting);
26542 * }, function(reason) {
26543 * alert('Failed: ' + reason);
26544 * }, function(update) {
26545 * alert('Got notification: ' + update);
26549 * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
26550 * comes in the way of guarantees that promise and deferred APIs make, see
26551 * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
26553 * Additionally the promise api allows for composition that is very hard to do with the
26554 * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
26555 * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
26556 * section on serial or parallel joining of promises.
26558 * # The Deferred API
26560 * A new instance of deferred is constructed by calling `$q.defer()`.
26562 * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
26563 * that can be used for signaling the successful or unsuccessful completion, as well as the status
26568 * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
26569 * constructed via `$q.reject`, the promise will be rejected instead.
26570 * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
26571 * resolving it with a rejection constructed via `$q.reject`.
26572 * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
26573 * multiple times before the promise is either resolved or rejected.
26577 * - promise – `{Promise}` – promise object associated with this deferred.
26580 * # The Promise API
26582 * A new promise instance is created when a deferred instance is created and can be retrieved by
26583 * calling `deferred.promise`.
26585 * The purpose of the promise object is to allow for interested parties to get access to the result
26586 * of the deferred task when it completes.
26590 * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or
26591 * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
26592 * as soon as the result is available. The callbacks are called with a single argument: the result
26593 * or rejection reason. Additionally, the notify callback may be called zero or more times to
26594 * provide a progress indication, before the promise is resolved or rejected.
26596 * This method *returns a new promise* which is resolved or rejected via the return value of the
26597 * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
26598 * with the value which is resolved in that promise using
26599 * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
26600 * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
26601 * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback
26602 * arguments are optional.
26604 * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
26606 * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
26607 * but to do so without modifying the final value. This is useful to release resources or do some
26608 * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
26609 * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
26610 * more information.
26612 * # Chaining promises
26614 * Because calling the `then` method of a promise returns a new derived promise, it is easily
26615 * possible to create a chain of promises:
26618 * promiseB = promiseA.then(function(result) {
26619 * return result + 1;
26622 * // promiseB will be resolved immediately after promiseA is resolved and its value
26623 * // will be the result of promiseA incremented by 1
26626 * It is possible to create chains of any length and since a promise can be resolved with another
26627 * promise (which will defer its resolution further), it is possible to pause/defer resolution of
26628 * the promises at any point in the chain. This makes it possible to implement powerful APIs like
26629 * $http's response interceptors.
26632 * # Differences between Kris Kowal's Q and $q
26634 * There are two main differences:
26636 * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
26637 * mechanism in angular, which means faster propagation of resolution or rejection into your
26638 * models and avoiding unnecessary browser repaints, which would result in flickering UI.
26639 * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
26640 * all the important functionality needed for common async tasks.
26645 * it('should simulate promise', inject(function($q, $rootScope) {
26646 * var deferred = $q.defer();
26647 * var promise = deferred.promise;
26648 * var resolvedValue;
26650 * promise.then(function(value) { resolvedValue = value; });
26651 * expect(resolvedValue).toBeUndefined();
26653 * // Simulate resolving of promise
26654 * deferred.resolve(123);
26655 * // Note that the 'then' function does not get called synchronously.
26656 * // This is because we want the promise API to always be async, whether or not
26657 * // it got called synchronously or asynchronously.
26658 * expect(resolvedValue).toBeUndefined();
26660 * // Propagate promise resolution to 'then' functions using $apply().
26661 * $rootScope.$apply();
26662 * expect(resolvedValue).toEqual(123);
26666 * @param {function(function, function)} resolver Function which is responsible for resolving or
26667 * rejecting the newly created promise. The first parameter is a function which resolves the
26668 * promise, the second parameter is a function which rejects the promise.
26670 * @returns {Promise} The newly created promise.
26672 function $QProvider() {
26674 this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
26675 return qFactory(function(callback) {
26676 $rootScope.$evalAsync(callback);
26677 }, $exceptionHandler);
26682 function $$QProvider() {
26683 this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
26684 return qFactory(function(callback) {
26685 $browser.defer(callback);
26686 }, $exceptionHandler);
26691 * Constructs a promise manager.
26693 * @param {function(function)} nextTick Function for executing functions in the next turn.
26694 * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
26695 * debugging purposes.
26696 * @returns {object} Promise manager.
26698 function qFactory(nextTick, exceptionHandler) {
26699 var $qMinErr = minErr('$q', TypeError);
26703 * @name ng.$q#defer
26707 * Creates a `Deferred` object which represents a task which will finish in the future.
26709 * @returns {Deferred} Returns a new instance of deferred.
26712 var d = new Deferred();
26713 //Necessary to support unbound execution :/
26714 d.resolve = simpleBind(d, d.resolve);
26715 d.reject = simpleBind(d, d.reject);
26716 d.notify = simpleBind(d, d.notify);
26720 function Promise() {
26721 this.$$state = { status: 0 };
26724 extend(Promise.prototype, {
26725 then: function(onFulfilled, onRejected, progressBack) {
26726 if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
26729 var result = new Deferred();
26731 this.$$state.pending = this.$$state.pending || [];
26732 this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
26733 if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
26735 return result.promise;
26738 'catch': function(callback) {
26739 return this.then(null, callback);
26742 'finally': function(callback, progressBack) {
26743 return this.then(function(value) {
26744 return handleCallback(value, resolve, callback);
26745 }, function(error) {
26746 return handleCallback(error, reject, callback);
26751 //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
26752 function simpleBind(context, fn) {
26753 return function(value) {
26754 fn.call(context, value);
26758 function processQueue(state) {
26759 var fn, deferred, pending;
26761 pending = state.pending;
26762 state.processScheduled = false;
26763 state.pending = undefined;
26764 for (var i = 0, ii = pending.length; i < ii; ++i) {
26765 deferred = pending[i][0];
26766 fn = pending[i][state.status];
26768 if (isFunction(fn)) {
26769 deferred.resolve(fn(state.value));
26770 } else if (state.status === 1) {
26771 deferred.resolve(state.value);
26773 deferred.reject(state.value);
26776 deferred.reject(e);
26777 exceptionHandler(e);
26782 function scheduleProcessQueue(state) {
26783 if (state.processScheduled || !state.pending) return;
26784 state.processScheduled = true;
26785 nextTick(function() { processQueue(state); });
26788 function Deferred() {
26789 this.promise = new Promise();
26792 extend(Deferred.prototype, {
26793 resolve: function(val) {
26794 if (this.promise.$$state.status) return;
26795 if (val === this.promise) {
26796 this.$$reject($qMinErr(
26798 'Expected promise to be resolved with value other than itself \'{0}\'',
26801 this.$$resolve(val);
26806 $$resolve: function(val) {
26811 if ((isObject(val) || isFunction(val))) then = val && val.then;
26812 if (isFunction(then)) {
26813 this.promise.$$state.status = -1;
26814 then.call(val, resolvePromise, rejectPromise, simpleBind(this, this.notify));
26816 this.promise.$$state.value = val;
26817 this.promise.$$state.status = 1;
26818 scheduleProcessQueue(this.promise.$$state);
26822 exceptionHandler(e);
26825 function resolvePromise(val) {
26828 that.$$resolve(val);
26830 function rejectPromise(val) {
26833 that.$$reject(val);
26837 reject: function(reason) {
26838 if (this.promise.$$state.status) return;
26839 this.$$reject(reason);
26842 $$reject: function(reason) {
26843 this.promise.$$state.value = reason;
26844 this.promise.$$state.status = 2;
26845 scheduleProcessQueue(this.promise.$$state);
26848 notify: function(progress) {
26849 var callbacks = this.promise.$$state.pending;
26851 if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
26852 nextTick(function() {
26853 var callback, result;
26854 for (var i = 0, ii = callbacks.length; i < ii; i++) {
26855 result = callbacks[i][0];
26856 callback = callbacks[i][3];
26858 result.notify(isFunction(callback) ? callback(progress) : progress);
26860 exceptionHandler(e);
26874 * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
26875 * used to forward rejection in a chain of promises. If you are dealing with the last promise in
26876 * a promise chain, you don't need to worry about it.
26878 * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
26879 * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
26880 * a promise error callback and you want to forward the error to the promise derived from the
26881 * current promise, you have to "rethrow" the error by returning a rejection constructed via
26885 * promiseB = promiseA.then(function(result) {
26886 * // success: do something and resolve promiseB
26887 * // with the old or a new result
26889 * }, function(reason) {
26890 * // error: handle the error if possible and
26891 * // resolve promiseB with newPromiseOrValue,
26892 * // otherwise forward the rejection to promiseB
26893 * if (canHandle(reason)) {
26894 * // handle the error and recover
26895 * return newPromiseOrValue;
26897 * return $q.reject(reason);
26901 * @param {*} reason Constant, message, exception or an object representing the rejection reason.
26902 * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
26904 function reject(reason) {
26905 var result = new Deferred();
26906 result.reject(reason);
26907 return result.promise;
26910 function handleCallback(value, resolver, callback) {
26911 var callbackOutput = null;
26913 if (isFunction(callback)) callbackOutput = callback();
26917 if (isPromiseLike(callbackOutput)) {
26918 return callbackOutput.then(function() {
26919 return resolver(value);
26922 return resolver(value);
26932 * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
26933 * This is useful when you are dealing with an object that might or might not be a promise, or if
26934 * the promise comes from a source that can't be trusted.
26936 * @param {*} value Value or a promise
26937 * @param {Function=} successCallback
26938 * @param {Function=} errorCallback
26939 * @param {Function=} progressCallback
26940 * @returns {Promise} Returns a promise of the passed value or promise
26944 function when(value, callback, errback, progressBack) {
26945 var result = new Deferred();
26946 result.resolve(value);
26947 return result.promise.then(callback, errback, progressBack);
26956 * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
26958 * @param {*} value Value or a promise
26959 * @param {Function=} successCallback
26960 * @param {Function=} errorCallback
26961 * @param {Function=} progressCallback
26962 * @returns {Promise} Returns a promise of the passed value or promise
26964 var resolve = when;
26972 * Combines multiple promises into a single promise that is resolved when all of the input
26973 * promises are resolved.
26975 * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
26976 * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
26977 * each value corresponding to the promise at the same index/key in the `promises` array/hash.
26978 * If any of the promises is resolved with a rejection, this resulting promise will be rejected
26979 * with the same rejection value.
26982 function all(promises) {
26983 var deferred = new Deferred(),
26985 results = isArray(promises) ? [] : {};
26987 forEach(promises, function(promise, key) {
26989 when(promise).then(function(value) {
26990 results[key] = value;
26991 if (!(--counter)) deferred.resolve(results);
26992 }, function(reason) {
26993 deferred.reject(reason);
26997 if (counter === 0) {
26998 deferred.resolve(results);
27001 return deferred.promise;
27010 * Returns a promise that resolves or rejects as soon as one of those promises
27011 * resolves or rejects, with the value or reason from that promise.
27013 * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
27014 * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`
27015 * resolves or rejects, with the value or reason from that promise.
27018 function race(promises) {
27019 var deferred = defer();
27021 forEach(promises, function(promise) {
27022 when(promise).then(deferred.resolve, deferred.reject);
27025 return deferred.promise;
27028 function $Q(resolver) {
27029 if (!isFunction(resolver)) {
27030 throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver);
27033 var deferred = new Deferred();
27035 function resolveFn(value) {
27036 deferred.resolve(value);
27039 function rejectFn(reason) {
27040 deferred.reject(reason);
27043 resolver(resolveFn, rejectFn);
27045 return deferred.promise;
27048 // Let's make the instanceof operator work for promises, so that
27049 // `new $q(fn) instanceof $q` would evaluate to true.
27050 $Q.prototype = Promise.prototype;
27053 $Q.reject = reject;
27055 $Q.resolve = resolve;
27063 function $$RAFProvider() { //rAF
27064 this.$get = ['$window', '$timeout', function($window, $timeout) {
27065 var requestAnimationFrame = $window.requestAnimationFrame ||
27066 $window.webkitRequestAnimationFrame;
27068 var cancelAnimationFrame = $window.cancelAnimationFrame ||
27069 $window.webkitCancelAnimationFrame ||
27070 $window.webkitCancelRequestAnimationFrame;
27072 var rafSupported = !!requestAnimationFrame;
27073 var raf = rafSupported
27075 var id = requestAnimationFrame(fn);
27076 return function() {
27077 cancelAnimationFrame(id);
27081 var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
27082 return function() {
27083 $timeout.cancel(timer);
27087 raf.supported = rafSupported;
27096 * The design decisions behind the scope are heavily favored for speed and memory consumption.
27098 * The typical use of scope is to watch the expressions, which most of the time return the same
27099 * value as last time so we optimize the operation.
27101 * Closures construction is expensive in terms of speed as well as memory:
27102 * - No closures, instead use prototypical inheritance for API
27103 * - Internal state needs to be stored on scope directly, which means that private state is
27104 * exposed as $$____ properties
27106 * Loop operations are optimized by using while(count--) { ... }
27107 * - This means that in order to keep the same order of execution as addition we have to add
27108 * items to the array at the beginning (unshift) instead of at the end (push)
27110 * Child scopes are created and removed often
27111 * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
27113 * There are fewer watches than observers. This is why you don't want the observer to be implemented
27114 * in the same way as watch. Watch requires return of the initialization function which is expensive
27121 * @name $rootScopeProvider
27124 * Provider for the $rootScope service.
27129 * @name $rootScopeProvider#digestTtl
27132 * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
27133 * assuming that the model is unstable.
27135 * The current default is 10 iterations.
27137 * In complex applications it's possible that the dependencies between `$watch`s will result in
27138 * several digest iterations. However if an application needs more than the default 10 digest
27139 * iterations for its model to stabilize then you should investigate what is causing the model to
27140 * continuously change during the digest.
27142 * Increasing the TTL could have performance implications, so you should not change it without
27143 * proper justification.
27145 * @param {number} limit The number of digest iterations.
27156 * Every application has a single root {@link ng.$rootScope.Scope scope}.
27157 * All other scopes are descendant scopes of the root scope. Scopes provide separation
27158 * between the model and the view, via a mechanism for watching the model for changes.
27159 * They also provide event emission/broadcast and subscription facility. See the
27160 * {@link guide/scope developer guide on scopes}.
27162 function $RootScopeProvider() {
27164 var $rootScopeMinErr = minErr('$rootScope');
27165 var lastDirtyWatch = null;
27166 var applyAsyncId = null;
27168 this.digestTtl = function(value) {
27169 if (arguments.length) {
27175 function createChildScopeClass(parent) {
27176 function ChildScope() {
27177 this.$$watchers = this.$$nextSibling =
27178 this.$$childHead = this.$$childTail = null;
27179 this.$$listeners = {};
27180 this.$$listenerCount = {};
27181 this.$$watchersCount = 0;
27182 this.$id = nextUid();
27183 this.$$ChildScope = null;
27185 ChildScope.prototype = parent;
27189 this.$get = ['$exceptionHandler', '$parse', '$browser',
27190 function($exceptionHandler, $parse, $browser) {
27192 function destroyChildScope($event) {
27193 $event.currentScope.$$destroyed = true;
27196 function cleanUpScope($scope) {
27199 // There is a memory leak in IE9 if all child scopes are not disconnected
27200 // completely when a scope is destroyed. So this code will recurse up through
27201 // all this scopes children
27203 // See issue https://github.com/angular/angular.js/issues/10706
27204 if ($scope.$$childHead) {
27205 cleanUpScope($scope.$$childHead);
27207 if ($scope.$$nextSibling) {
27208 cleanUpScope($scope.$$nextSibling);
27212 // The code below works around IE9 and V8's memory leaks
27215 // - https://code.google.com/p/v8/issues/detail?id=2073#c26
27216 // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
27217 // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
27219 $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
27220 $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
27225 * @name $rootScope.Scope
27228 * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
27229 * {@link auto.$injector $injector}. Child scopes are created using the
27230 * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
27231 * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
27232 * an in-depth introduction and usage examples.
27236 * A scope can inherit from a parent scope, as in this example:
27238 var parent = $rootScope;
27239 var child = parent.$new();
27241 parent.salutation = "Hello";
27242 expect(child.salutation).toEqual('Hello');
27244 child.salutation = "Welcome";
27245 expect(child.salutation).toEqual('Welcome');
27246 expect(parent.salutation).toEqual('Hello');
27249 * When interacting with `Scope` in tests, additional helper methods are available on the
27250 * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
27254 * @param {Object.<string, function()>=} providers Map of service factory which need to be
27255 * provided for the current scope. Defaults to {@link ng}.
27256 * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
27257 * append/override services provided by `providers`. This is handy
27258 * when unit-testing and having the need to override a default
27260 * @returns {Object} Newly created scope.
27264 this.$id = nextUid();
27265 this.$$phase = this.$parent = this.$$watchers =
27266 this.$$nextSibling = this.$$prevSibling =
27267 this.$$childHead = this.$$childTail = null;
27269 this.$$destroyed = false;
27270 this.$$listeners = {};
27271 this.$$listenerCount = {};
27272 this.$$watchersCount = 0;
27273 this.$$isolateBindings = null;
27278 * @name $rootScope.Scope#$id
27281 * Unique scope ID (monotonically increasing) useful for debugging.
27286 * @name $rootScope.Scope#$parent
27289 * Reference to the parent scope.
27294 * @name $rootScope.Scope#$root
27297 * Reference to the root scope.
27300 Scope.prototype = {
27301 constructor: Scope,
27304 * @name $rootScope.Scope#$new
27308 * Creates a new child {@link ng.$rootScope.Scope scope}.
27310 * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
27311 * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
27313 * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
27314 * desired for the scope and its child scopes to be permanently detached from the parent and
27315 * thus stop participating in model change detection and listener notification by invoking.
27317 * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
27318 * parent scope. The scope is isolated, as it can not see parent scope properties.
27319 * When creating widgets, it is useful for the widget to not accidentally read parent
27322 * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
27323 * of the newly created scope. Defaults to `this` scope if not provided.
27324 * This is used when creating a transclude scope to correctly place it
27325 * in the scope hierarchy while maintaining the correct prototypical
27328 * @returns {Object} The newly created child scope.
27331 $new: function(isolate, parent) {
27334 parent = parent || this;
27337 child = new Scope();
27338 child.$root = this.$root;
27340 // Only create a child scope class if somebody asks for one,
27341 // but cache it to allow the VM to optimize lookups.
27342 if (!this.$$ChildScope) {
27343 this.$$ChildScope = createChildScopeClass(this);
27345 child = new this.$$ChildScope();
27347 child.$parent = parent;
27348 child.$$prevSibling = parent.$$childTail;
27349 if (parent.$$childHead) {
27350 parent.$$childTail.$$nextSibling = child;
27351 parent.$$childTail = child;
27353 parent.$$childHead = parent.$$childTail = child;
27356 // When the new scope is not isolated or we inherit from `this`, and
27357 // the parent scope is destroyed, the property `$$destroyed` is inherited
27358 // prototypically. In all other cases, this property needs to be set
27359 // when the parent scope is destroyed.
27360 // The listener needs to be added after the parent is set
27361 if (isolate || parent !== this) child.$on('$destroy', destroyChildScope);
27368 * @name $rootScope.Scope#$watch
27372 * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
27374 * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
27375 * $digest()} and should return the value that will be watched. (`watchExpression` should not change
27376 * its value when executed multiple times with the same input because it may be executed multiple
27377 * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
27378 * [idempotent](http://en.wikipedia.org/wiki/Idempotence).)
27379 * - The `listener` is called only when the value from the current `watchExpression` and the
27380 * previous call to `watchExpression` are not equal (with the exception of the initial run,
27381 * see below). Inequality is determined according to reference inequality,
27382 * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
27383 * via the `!==` Javascript operator, unless `objectEquality == true`
27385 * - When `objectEquality == true`, inequality of the `watchExpression` is determined
27386 * according to the {@link angular.equals} function. To save the value of the object for
27387 * later comparison, the {@link angular.copy} function is used. This therefore means that
27388 * watching complex objects will have adverse memory and performance implications.
27389 * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
27390 * This is achieved by rerunning the watchers until no changes are detected. The rerun
27391 * iteration limit is 10 to prevent an infinite loop deadlock.
27394 * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
27395 * you can register a `watchExpression` function with no `listener`. (Be prepared for
27396 * multiple calls to your `watchExpression` because it will execute multiple times in a
27397 * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
27399 * After a watcher is registered with the scope, the `listener` fn is called asynchronously
27400 * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
27401 * watcher. In rare cases, this is undesirable because the listener is called when the result
27402 * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
27403 * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
27404 * listener was called due to initialization.
27410 // let's assume that scope was dependency injected as the $rootScope
27411 var scope = $rootScope;
27412 scope.name = 'misko';
27415 expect(scope.counter).toEqual(0);
27416 scope.$watch('name', function(newValue, oldValue) {
27417 scope.counter = scope.counter + 1;
27419 expect(scope.counter).toEqual(0);
27422 // the listener is always called during the first $digest loop after it was registered
27423 expect(scope.counter).toEqual(1);
27426 // but now it will not be called unless the value changes
27427 expect(scope.counter).toEqual(1);
27429 scope.name = 'adam';
27431 expect(scope.counter).toEqual(2);
27435 // Using a function as a watchExpression
27437 scope.foodCounter = 0;
27438 expect(scope.foodCounter).toEqual(0);
27440 // This function returns the value being watched. It is called for each turn of the $digest loop
27441 function() { return food; },
27442 // This is the change listener, called when the value returned from the above function changes
27443 function(newValue, oldValue) {
27444 if ( newValue !== oldValue ) {
27445 // Only increment the counter if the value changed
27446 scope.foodCounter = scope.foodCounter + 1;
27450 // No digest has been run so the counter will be zero
27451 expect(scope.foodCounter).toEqual(0);
27453 // Run the digest but since food has not changed count will still be zero
27455 expect(scope.foodCounter).toEqual(0);
27457 // Update food and run digest. Now the counter will increment
27458 food = 'cheeseburger';
27460 expect(scope.foodCounter).toEqual(1);
27466 * @param {(function()|string)} watchExpression Expression that is evaluated on each
27467 * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
27468 * a call to the `listener`.
27470 * - `string`: Evaluated as {@link guide/expression expression}
27471 * - `function(scope)`: called with current `scope` as a parameter.
27472 * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
27473 * of `watchExpression` changes.
27475 * - `newVal` contains the current value of the `watchExpression`
27476 * - `oldVal` contains the previous value of the `watchExpression`
27477 * - `scope` refers to the current scope
27478 * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
27479 * comparing for reference equality.
27480 * @returns {function()} Returns a deregistration function for this listener.
27482 $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
27483 var get = $parse(watchExp);
27485 if (get.$$watchDelegate) {
27486 return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
27489 array = scope.$$watchers,
27492 last: initWatchVal,
27494 exp: prettyPrintExpression || watchExp,
27495 eq: !!objectEquality
27498 lastDirtyWatch = null;
27500 if (!isFunction(listener)) {
27505 array = scope.$$watchers = [];
27506 array.$$digestWatchIndex = -1;
27508 // we use unshift since we use a while loop in $digest for speed.
27509 // the while loop reads in reverse order.
27510 array.unshift(watcher);
27511 array.$$digestWatchIndex++;
27512 incrementWatchersCount(this, 1);
27514 return function deregisterWatch() {
27515 var index = arrayRemove(array, watcher);
27517 incrementWatchersCount(scope, -1);
27518 if (index < array.$$digestWatchIndex) {
27519 array.$$digestWatchIndex--;
27522 lastDirtyWatch = null;
27528 * @name $rootScope.Scope#$watchGroup
27532 * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
27533 * If any one expression in the collection changes the `listener` is executed.
27535 * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return
27536 * values are examined for changes on every call to `$digest`.
27537 * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
27539 * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
27540 * watched using {@link ng.$rootScope.Scope#$watch $watch()}
27542 * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
27543 * expression in `watchExpressions` changes
27544 * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
27545 * those of `watchExpression`
27546 * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
27547 * those of `watchExpression`
27548 * The `scope` refers to the current scope.
27549 * @returns {function()} Returns a de-registration function for all listeners.
27551 $watchGroup: function(watchExpressions, listener) {
27552 var oldValues = new Array(watchExpressions.length);
27553 var newValues = new Array(watchExpressions.length);
27554 var deregisterFns = [];
27556 var changeReactionScheduled = false;
27557 var firstRun = true;
27559 if (!watchExpressions.length) {
27560 // No expressions means we call the listener ASAP
27561 var shouldCall = true;
27562 self.$evalAsync(function() {
27563 if (shouldCall) listener(newValues, newValues, self);
27565 return function deregisterWatchGroup() {
27566 shouldCall = false;
27570 if (watchExpressions.length === 1) {
27571 // Special case size of one
27572 return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
27573 newValues[0] = value;
27574 oldValues[0] = oldValue;
27575 listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
27579 forEach(watchExpressions, function(expr, i) {
27580 var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
27581 newValues[i] = value;
27582 oldValues[i] = oldValue;
27583 if (!changeReactionScheduled) {
27584 changeReactionScheduled = true;
27585 self.$evalAsync(watchGroupAction);
27588 deregisterFns.push(unwatchFn);
27591 function watchGroupAction() {
27592 changeReactionScheduled = false;
27596 listener(newValues, newValues, self);
27598 listener(newValues, oldValues, self);
27602 return function deregisterWatchGroup() {
27603 while (deregisterFns.length) {
27604 deregisterFns.shift()();
27612 * @name $rootScope.Scope#$watchCollection
27616 * Shallow watches the properties of an object and fires whenever any of the properties change
27617 * (for arrays, this implies watching the array items; for object maps, this implies watching
27618 * the properties). If a change is detected, the `listener` callback is fired.
27620 * - The `obj` collection is observed via standard $watch operation and is examined on every
27621 * call to $digest() to see if any items have been added, removed, or moved.
27622 * - The `listener` is called whenever anything within the `obj` has changed. Examples include
27623 * adding, removing, and moving items belonging to an object or array.
27628 $scope.names = ['igor', 'matias', 'misko', 'james'];
27629 $scope.dataCount = 4;
27631 $scope.$watchCollection('names', function(newNames, oldNames) {
27632 $scope.dataCount = newNames.length;
27635 expect($scope.dataCount).toEqual(4);
27638 //still at 4 ... no changes
27639 expect($scope.dataCount).toEqual(4);
27641 $scope.names.pop();
27644 //now there's been a change
27645 expect($scope.dataCount).toEqual(3);
27649 * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
27650 * expression value should evaluate to an object or an array which is observed on each
27651 * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
27652 * collection will trigger a call to the `listener`.
27654 * @param {function(newCollection, oldCollection, scope)} listener a callback function called
27655 * when a change is detected.
27656 * - The `newCollection` object is the newly modified data obtained from the `obj` expression
27657 * - The `oldCollection` object is a copy of the former collection data.
27658 * Due to performance considerations, the`oldCollection` value is computed only if the
27659 * `listener` function declares two or more arguments.
27660 * - The `scope` argument refers to the current scope.
27662 * @returns {function()} Returns a de-registration function for this listener. When the
27663 * de-registration function is executed, the internal watch operation is terminated.
27665 $watchCollection: function(obj, listener) {
27666 $watchCollectionInterceptor.$stateful = true;
27669 // the current value, updated on each dirty-check run
27671 // a shallow copy of the newValue from the last dirty-check run,
27672 // updated to match newValue during dirty-check run
27674 // a shallow copy of the newValue from when the last change happened
27676 // only track veryOldValue if the listener is asking for it
27677 var trackVeryOldValue = (listener.length > 1);
27678 var changeDetected = 0;
27679 var changeDetector = $parse(obj, $watchCollectionInterceptor);
27680 var internalArray = [];
27681 var internalObject = {};
27682 var initRun = true;
27685 function $watchCollectionInterceptor(_value) {
27687 var newLength, key, bothNaN, newItem, oldItem;
27689 // If the new value is undefined, then return undefined as the watch may be a one-time watch
27690 if (isUndefined(newValue)) return;
27692 if (!isObject(newValue)) { // if primitive
27693 if (oldValue !== newValue) {
27694 oldValue = newValue;
27697 } else if (isArrayLike(newValue)) {
27698 if (oldValue !== internalArray) {
27699 // we are transitioning from something which was not an array into array.
27700 oldValue = internalArray;
27701 oldLength = oldValue.length = 0;
27705 newLength = newValue.length;
27707 if (oldLength !== newLength) {
27708 // if lengths do not match we need to trigger change notification
27710 oldValue.length = oldLength = newLength;
27712 // copy the items to oldValue and look for changes.
27713 for (var i = 0; i < newLength; i++) {
27714 oldItem = oldValue[i];
27715 newItem = newValue[i];
27717 // eslint-disable-next-line no-self-compare
27718 bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
27719 if (!bothNaN && (oldItem !== newItem)) {
27721 oldValue[i] = newItem;
27725 if (oldValue !== internalObject) {
27726 // we are transitioning from something which was not an object into object.
27727 oldValue = internalObject = {};
27731 // copy the items to oldValue and look for changes.
27733 for (key in newValue) {
27734 if (hasOwnProperty.call(newValue, key)) {
27736 newItem = newValue[key];
27737 oldItem = oldValue[key];
27739 if (key in oldValue) {
27740 // eslint-disable-next-line no-self-compare
27741 bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
27742 if (!bothNaN && (oldItem !== newItem)) {
27744 oldValue[key] = newItem;
27748 oldValue[key] = newItem;
27753 if (oldLength > newLength) {
27754 // we used to have more keys, need to find them and destroy them.
27756 for (key in oldValue) {
27757 if (!hasOwnProperty.call(newValue, key)) {
27759 delete oldValue[key];
27764 return changeDetected;
27767 function $watchCollectionAction() {
27770 listener(newValue, newValue, self);
27772 listener(newValue, veryOldValue, self);
27775 // make a copy for the next time a collection is changed
27776 if (trackVeryOldValue) {
27777 if (!isObject(newValue)) {
27779 veryOldValue = newValue;
27780 } else if (isArrayLike(newValue)) {
27781 veryOldValue = new Array(newValue.length);
27782 for (var i = 0; i < newValue.length; i++) {
27783 veryOldValue[i] = newValue[i];
27785 } else { // if object
27787 for (var key in newValue) {
27788 if (hasOwnProperty.call(newValue, key)) {
27789 veryOldValue[key] = newValue[key];
27796 return this.$watch(changeDetector, $watchCollectionAction);
27801 * @name $rootScope.Scope#$digest
27805 * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
27806 * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
27807 * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
27808 * until no more listeners are firing. This means that it is possible to get into an infinite
27809 * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
27810 * iterations exceeds 10.
27812 * Usually, you don't call `$digest()` directly in
27813 * {@link ng.directive:ngController controllers} or in
27814 * {@link ng.$compileProvider#directive directives}.
27815 * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
27816 * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
27818 * If you want to be notified whenever `$digest()` is called,
27819 * you can register a `watchExpression` function with
27820 * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
27822 * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
27827 scope.name = 'misko';
27830 expect(scope.counter).toEqual(0);
27831 scope.$watch('name', function(newValue, oldValue) {
27832 scope.counter = scope.counter + 1;
27834 expect(scope.counter).toEqual(0);
27837 // the listener is always called during the first $digest loop after it was registered
27838 expect(scope.counter).toEqual(1);
27841 // but now it will not be called unless the value changes
27842 expect(scope.counter).toEqual(1);
27844 scope.name = 'adam';
27846 expect(scope.counter).toEqual(2);
27850 $digest: function() {
27851 var watch, value, last, fn, get,
27854 next, current, target = this,
27858 beginPhase('$digest');
27859 // Check for changes to browser url that happened in sync before the call to $digest
27860 $browser.$$checkUrlChange();
27862 if (this === $rootScope && applyAsyncId !== null) {
27863 // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
27864 // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
27865 $browser.defer.cancel(applyAsyncId);
27869 lastDirtyWatch = null;
27871 do { // "while dirty" loop
27875 // It's safe for asyncQueuePosition to be a local variable here because this loop can't
27876 // be reentered recursively. Calling $digest from a function passed to $applyAsync would
27877 // lead to a '$digest already in progress' error.
27878 for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {
27880 asyncTask = asyncQueue[asyncQueuePosition];
27881 asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
27883 $exceptionHandler(e);
27885 lastDirtyWatch = null;
27887 asyncQueue.length = 0;
27889 traverseScopesLoop:
27890 do { // "traverse the scopes" loop
27891 if ((watchers = current.$$watchers)) {
27892 // process our watches
27893 watchers.$$digestWatchIndex = watchers.length;
27894 while (watchers.$$digestWatchIndex--) {
27896 watch = watchers[watchers.$$digestWatchIndex];
27897 // Most common watches are on primitives, in which case we can short
27898 // circuit it with === operator, only when === fails do we use .equals
27901 if ((value = get(current)) !== (last = watch.last) &&
27903 ? equals(value, last)
27904 : (isNumberNaN(value) && isNumberNaN(last)))) {
27906 lastDirtyWatch = watch;
27907 watch.last = watch.eq ? copy(value, null) : value;
27909 fn(value, ((last === initWatchVal) ? value : last), current);
27912 if (!watchLog[logIdx]) watchLog[logIdx] = [];
27913 watchLog[logIdx].push({
27914 msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
27919 } else if (watch === lastDirtyWatch) {
27920 // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
27921 // have already been tested.
27923 break traverseScopesLoop;
27927 $exceptionHandler(e);
27932 // Insanity Warning: scope depth-first traversal
27933 // yes, this code is a bit crazy, but it works and we have tests to prove it!
27934 // this piece should be kept in sync with the traversal in $broadcast
27935 if (!(next = ((current.$$watchersCount && current.$$childHead) ||
27936 (current !== target && current.$$nextSibling)))) {
27937 while (current !== target && !(next = current.$$nextSibling)) {
27938 current = current.$parent;
27941 } while ((current = next));
27943 // `break traverseScopesLoop;` takes us to here
27945 if ((dirty || asyncQueue.length) && !(ttl--)) {
27947 throw $rootScopeMinErr('infdig',
27948 '{0} $digest() iterations reached. Aborting!\n' +
27949 'Watchers fired in the last 5 iterations: {1}',
27953 } while (dirty || asyncQueue.length);
27957 // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
27958 while (postDigestQueuePosition < postDigestQueue.length) {
27960 postDigestQueue[postDigestQueuePosition++]();
27962 $exceptionHandler(e);
27965 postDigestQueue.length = postDigestQueuePosition = 0;
27971 * @name $rootScope.Scope#$destroy
27972 * @eventType broadcast on scope being destroyed
27975 * Broadcasted when a scope and its children are being destroyed.
27977 * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
27978 * clean up DOM bindings before an element is removed from the DOM.
27983 * @name $rootScope.Scope#$destroy
27987 * Removes the current scope (and all of its children) from the parent scope. Removal implies
27988 * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
27989 * propagate to the current scope and its children. Removal also implies that the current
27990 * scope is eligible for garbage collection.
27992 * The `$destroy()` is usually used by directives such as
27993 * {@link ng.directive:ngRepeat ngRepeat} for managing the
27994 * unrolling of the loop.
27996 * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
27997 * Application code can register a `$destroy` event handler that will give it a chance to
27998 * perform any necessary cleanup.
28000 * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
28001 * clean up DOM bindings before an element is removed from the DOM.
28003 $destroy: function() {
28004 // We can't destroy a scope that has been already destroyed.
28005 if (this.$$destroyed) return;
28006 var parent = this.$parent;
28008 this.$broadcast('$destroy');
28009 this.$$destroyed = true;
28011 if (this === $rootScope) {
28012 //Remove handlers attached to window when $rootScope is removed
28013 $browser.$$applicationDestroyed();
28016 incrementWatchersCount(this, -this.$$watchersCount);
28017 for (var eventName in this.$$listenerCount) {
28018 decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
28021 // sever all the references to parent scopes (after this cleanup, the current scope should
28022 // not be retained by any of our references and should be eligible for garbage collection)
28023 if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling;
28024 if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling;
28025 if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
28026 if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
28028 // Disable listeners, watchers and apply/digest methods
28029 this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
28030 this.$on = this.$watch = this.$watchGroup = function() { return noop; };
28031 this.$$listeners = {};
28033 // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
28034 this.$$nextSibling = null;
28035 cleanUpScope(this);
28040 * @name $rootScope.Scope#$eval
28044 * Executes the `expression` on the current scope and returns the result. Any exceptions in
28045 * the expression are propagated (uncaught). This is useful when evaluating Angular
28050 var scope = ng.$rootScope.Scope();
28054 expect(scope.$eval('a+b')).toEqual(3);
28055 expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
28058 * @param {(string|function())=} expression An angular expression to be executed.
28060 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
28061 * - `function(scope)`: execute the function with the current `scope` parameter.
28063 * @param {(object)=} locals Local variables object, useful for overriding values in scope.
28064 * @returns {*} The result of evaluating the expression.
28066 $eval: function(expr, locals) {
28067 return $parse(expr)(this, locals);
28072 * @name $rootScope.Scope#$evalAsync
28076 * Executes the expression on the current scope at a later point in time.
28078 * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
28081 * - it will execute after the function that scheduled the evaluation (preferably before DOM
28083 * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
28084 * `expression` execution.
28086 * Any exceptions from the execution of the expression are forwarded to the
28087 * {@link ng.$exceptionHandler $exceptionHandler} service.
28089 * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
28090 * will be scheduled. However, it is encouraged to always call code that changes the model
28091 * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
28093 * @param {(string|function())=} expression An angular expression to be executed.
28095 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
28096 * - `function(scope)`: execute the function with the current `scope` parameter.
28098 * @param {(object)=} locals Local variables object, useful for overriding values in scope.
28100 $evalAsync: function(expr, locals) {
28101 // if we are outside of an $digest loop and this is the first time we are scheduling async
28102 // task also schedule async auto-flush
28103 if (!$rootScope.$$phase && !asyncQueue.length) {
28104 $browser.defer(function() {
28105 if (asyncQueue.length) {
28106 $rootScope.$digest();
28111 asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});
28114 $$postDigest: function(fn) {
28115 postDigestQueue.push(fn);
28120 * @name $rootScope.Scope#$apply
28124 * `$apply()` is used to execute an expression in angular from outside of the angular
28125 * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
28126 * Because we are calling into the angular framework we need to perform proper scope life
28127 * cycle of {@link ng.$exceptionHandler exception handling},
28128 * {@link ng.$rootScope.Scope#$digest executing watches}.
28132 * # Pseudo-Code of `$apply()`
28134 function $apply(expr) {
28136 return $eval(expr);
28138 $exceptionHandler(e);
28146 * Scope's `$apply()` method transitions through the following stages:
28148 * 1. The {@link guide/expression expression} is executed using the
28149 * {@link ng.$rootScope.Scope#$eval $eval()} method.
28150 * 2. Any exceptions from the execution of the expression are forwarded to the
28151 * {@link ng.$exceptionHandler $exceptionHandler} service.
28152 * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
28153 * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
28156 * @param {(string|function())=} exp An angular expression to be executed.
28158 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
28159 * - `function(scope)`: execute the function with current `scope` parameter.
28161 * @returns {*} The result of evaluating the expression.
28163 $apply: function(expr) {
28165 beginPhase('$apply');
28167 return this.$eval(expr);
28172 $exceptionHandler(e);
28175 $rootScope.$digest();
28177 $exceptionHandler(e);
28178 // eslint-disable-next-line no-unsafe-finally
28186 * @name $rootScope.Scope#$applyAsync
28190 * Schedule the invocation of $apply to occur at a later time. The actual time difference
28191 * varies across browsers, but is typically around ~10 milliseconds.
28193 * This can be used to queue up multiple expressions which need to be evaluated in the same
28196 * @param {(string|function())=} exp An angular expression to be executed.
28198 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
28199 * - `function(scope)`: execute the function with current `scope` parameter.
28201 $applyAsync: function(expr) {
28204 applyAsyncQueue.push($applyAsyncExpression);
28206 expr = $parse(expr);
28207 scheduleApplyAsync();
28209 function $applyAsyncExpression() {
28216 * @name $rootScope.Scope#$on
28220 * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
28221 * discussion of event life cycle.
28223 * The event listener function format is: `function(event, args...)`. The `event` object
28224 * passed into the listener has the following attributes:
28226 * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
28228 * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
28229 * event propagates through the scope hierarchy, this property is set to null.
28230 * - `name` - `{string}`: name of the event.
28231 * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
28232 * further event propagation (available only for events that were `$emit`-ed).
28233 * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
28235 * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
28237 * @param {string} name Event name to listen on.
28238 * @param {function(event, ...args)} listener Function to call when the event is emitted.
28239 * @returns {function()} Returns a deregistration function for this listener.
28241 $on: function(name, listener) {
28242 var namedListeners = this.$$listeners[name];
28243 if (!namedListeners) {
28244 this.$$listeners[name] = namedListeners = [];
28246 namedListeners.push(listener);
28248 var current = this;
28250 if (!current.$$listenerCount[name]) {
28251 current.$$listenerCount[name] = 0;
28253 current.$$listenerCount[name]++;
28254 } while ((current = current.$parent));
28257 return function() {
28258 var indexOfListener = namedListeners.indexOf(listener);
28259 if (indexOfListener !== -1) {
28260 namedListeners[indexOfListener] = null;
28261 decrementListenerCount(self, 1, name);
28269 * @name $rootScope.Scope#$emit
28273 * Dispatches an event `name` upwards through the scope hierarchy notifying the
28274 * registered {@link ng.$rootScope.Scope#$on} listeners.
28276 * The event life cycle starts at the scope on which `$emit` was called. All
28277 * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
28278 * notified. Afterwards, the event traverses upwards toward the root scope and calls all
28279 * registered listeners along the way. The event will stop propagating if one of the listeners
28282 * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
28283 * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
28285 * @param {string} name Event name to emit.
28286 * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
28287 * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
28289 $emit: function(name, args) {
28293 stopPropagation = false,
28296 targetScope: scope,
28297 stopPropagation: function() {stopPropagation = true;},
28298 preventDefault: function() {
28299 event.defaultPrevented = true;
28301 defaultPrevented: false
28303 listenerArgs = concat([event], arguments, 1),
28307 namedListeners = scope.$$listeners[name] || empty;
28308 event.currentScope = scope;
28309 for (i = 0, length = namedListeners.length; i < length; i++) {
28311 // if listeners were deregistered, defragment the array
28312 if (!namedListeners[i]) {
28313 namedListeners.splice(i, 1);
28319 //allow all listeners attached to the current scope to run
28320 namedListeners[i].apply(null, listenerArgs);
28322 $exceptionHandler(e);
28325 //if any listener on the current scope stops propagation, prevent bubbling
28326 if (stopPropagation) {
28327 event.currentScope = null;
28331 scope = scope.$parent;
28334 event.currentScope = null;
28342 * @name $rootScope.Scope#$broadcast
28346 * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
28347 * registered {@link ng.$rootScope.Scope#$on} listeners.
28349 * The event life cycle starts at the scope on which `$broadcast` was called. All
28350 * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
28351 * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
28352 * scope and calls all registered listeners along the way. The event cannot be canceled.
28354 * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
28355 * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
28357 * @param {string} name Event name to broadcast.
28358 * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
28359 * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
28361 $broadcast: function(name, args) {
28367 targetScope: target,
28368 preventDefault: function() {
28369 event.defaultPrevented = true;
28371 defaultPrevented: false
28374 if (!target.$$listenerCount[name]) return event;
28376 var listenerArgs = concat([event], arguments, 1),
28377 listeners, i, length;
28379 //down while you can, then up and next sibling or up and next sibling until back at root
28380 while ((current = next)) {
28381 event.currentScope = current;
28382 listeners = current.$$listeners[name] || [];
28383 for (i = 0, length = listeners.length; i < length; i++) {
28384 // if listeners were deregistered, defragment the array
28385 if (!listeners[i]) {
28386 listeners.splice(i, 1);
28393 listeners[i].apply(null, listenerArgs);
28395 $exceptionHandler(e);
28399 // Insanity Warning: scope depth-first traversal
28400 // yes, this code is a bit crazy, but it works and we have tests to prove it!
28401 // this piece should be kept in sync with the traversal in $digest
28402 // (though it differs due to having the extra check for $$listenerCount)
28403 if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
28404 (current !== target && current.$$nextSibling)))) {
28405 while (current !== target && !(next = current.$$nextSibling)) {
28406 current = current.$parent;
28411 event.currentScope = null;
28416 var $rootScope = new Scope();
28418 //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
28419 var asyncQueue = $rootScope.$$asyncQueue = [];
28420 var postDigestQueue = $rootScope.$$postDigestQueue = [];
28421 var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
28423 var postDigestQueuePosition = 0;
28428 function beginPhase(phase) {
28429 if ($rootScope.$$phase) {
28430 throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
28433 $rootScope.$$phase = phase;
28436 function clearPhase() {
28437 $rootScope.$$phase = null;
28440 function incrementWatchersCount(current, count) {
28442 current.$$watchersCount += count;
28443 } while ((current = current.$parent));
28446 function decrementListenerCount(current, count, name) {
28448 current.$$listenerCount[name] -= count;
28450 if (current.$$listenerCount[name] === 0) {
28451 delete current.$$listenerCount[name];
28453 } while ((current = current.$parent));
28457 * function used as an initial value for watchers.
28458 * because it's unique we can easily tell it apart from other values
28460 function initWatchVal() {}
28462 function flushApplyAsync() {
28463 while (applyAsyncQueue.length) {
28465 applyAsyncQueue.shift()();
28467 $exceptionHandler(e);
28470 applyAsyncId = null;
28473 function scheduleApplyAsync() {
28474 if (applyAsyncId === null) {
28475 applyAsyncId = $browser.defer(function() {
28476 $rootScope.$apply(flushApplyAsync);
28485 * @name $rootElement
28488 * The root element of Angular application. This is either the element where {@link
28489 * ng.directive:ngApp ngApp} was declared or the element passed into
28490 * {@link angular.bootstrap}. The element represents the root element of application. It is also the
28491 * location where the application's {@link auto.$injector $injector} service gets
28492 * published, and can be retrieved using `$rootElement.injector()`.
28496 // the implementation is in angular.bootstrap
28501 * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
28503 function $$SanitizeUriProvider() {
28504 var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
28505 imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
28509 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
28510 * urls during a[href] sanitization.
28512 * The sanitization is a security measure aimed at prevent XSS attacks via html links.
28514 * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
28515 * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
28516 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
28517 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
28519 * @param {RegExp=} regexp New regexp to whitelist urls with.
28520 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
28521 * chaining otherwise.
28523 this.aHrefSanitizationWhitelist = function(regexp) {
28524 if (isDefined(regexp)) {
28525 aHrefSanitizationWhitelist = regexp;
28528 return aHrefSanitizationWhitelist;
28534 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
28535 * urls during img[src] sanitization.
28537 * The sanitization is a security measure aimed at prevent XSS attacks via html links.
28539 * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
28540 * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
28541 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
28542 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
28544 * @param {RegExp=} regexp New regexp to whitelist urls with.
28545 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
28546 * chaining otherwise.
28548 this.imgSrcSanitizationWhitelist = function(regexp) {
28549 if (isDefined(regexp)) {
28550 imgSrcSanitizationWhitelist = regexp;
28553 return imgSrcSanitizationWhitelist;
28556 this.$get = function() {
28557 return function sanitizeUri(uri, isImage) {
28558 var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
28560 normalizedVal = urlResolve(uri).href;
28561 if (normalizedVal !== '' && !normalizedVal.match(regex)) {
28562 return 'unsafe:' + normalizedVal;
28569 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
28570 * Any commits to this file should be reviewed with security in mind. *
28571 * Changes to this file can potentially create security vulnerabilities. *
28572 * An approval from 2 Core members with history of modifying *
28573 * this file is required. *
28575 * Does the change somehow allow for arbitrary javascript to be executed? *
28576 * Or allows for someone to change the prototype of built-in objects? *
28577 * Or gives undesired access to variables likes document or window? *
28578 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
28580 /* exported $SceProvider, $SceDelegateProvider */
28582 var $sceMinErr = minErr('$sce');
28584 var SCE_CONTEXTS = {
28588 // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
28589 // url. (e.g. ng-include, script src, templateUrl)
28590 RESOURCE_URL: 'resourceUrl',
28594 // Helper functions follow.
28596 function adjustMatcher(matcher) {
28597 if (matcher === 'self') {
28599 } else if (isString(matcher)) {
28600 // Strings match exactly except for 2 wildcards - '*' and '**'.
28601 // '*' matches any character except those from the set ':/.?&'.
28602 // '**' matches any character (like .* in a RegExp).
28603 // More than 2 *'s raises an error as it's ill defined.
28604 if (matcher.indexOf('***') > -1) {
28605 throw $sceMinErr('iwcard',
28606 'Illegal sequence *** in string matcher. String: {0}', matcher);
28608 matcher = escapeForRegexp(matcher).
28609 replace(/\\\*\\\*/g, '.*').
28610 replace(/\\\*/g, '[^:/.?&;]*');
28611 return new RegExp('^' + matcher + '$');
28612 } else if (isRegExp(matcher)) {
28613 // The only other type of matcher allowed is a Regexp.
28614 // Match entire URL / disallow partial matches.
28615 // Flags are reset (i.e. no global, ignoreCase or multiline)
28616 return new RegExp('^' + matcher.source + '$');
28618 throw $sceMinErr('imatcher',
28619 'Matchers may only be "self", string patterns or RegExp objects');
28624 function adjustMatchers(matchers) {
28625 var adjustedMatchers = [];
28626 if (isDefined(matchers)) {
28627 forEach(matchers, function(matcher) {
28628 adjustedMatchers.push(adjustMatcher(matcher));
28631 return adjustedMatchers;
28637 * @name $sceDelegate
28642 * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
28643 * Contextual Escaping (SCE)} services to AngularJS.
28645 * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
28646 * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
28647 * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
28648 * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
28649 * work because `$sce` delegates to `$sceDelegate` for these operations.
28651 * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
28653 * The default instance of `$sceDelegate` should work out of the box with little pain. While you
28654 * can override it completely to change the behavior of `$sce`, the common case would
28655 * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
28656 * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
28657 * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
28658 * $sceDelegateProvider.resourceUrlWhitelist} and {@link
28659 * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
28664 * @name $sceDelegateProvider
28669 * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
28670 * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
28671 * that the URLs used for sourcing Angular templates are safe. Refer {@link
28672 * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
28673 * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
28675 * For the general details about this service in Angular, read the main page for {@link ng.$sce
28676 * Strict Contextual Escaping (SCE)}.
28678 * **Example**: Consider the following case. <a name="example"></a>
28680 * - your app is hosted at url `http://myapp.example.com/`
28681 * - but some of your templates are hosted on other domains you control such as
28682 * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
28683 * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
28685 * Here is what a secure configuration for this scenario might look like:
28688 * angular.module('myApp', []).config(function($sceDelegateProvider) {
28689 * $sceDelegateProvider.resourceUrlWhitelist([
28690 * // Allow same origin resource loads.
28692 * // Allow loading from our assets domain. Notice the difference between * and **.
28693 * 'http://srv*.assets.example.com/**'
28696 * // The blacklist overrides the whitelist so the open redirect here is blocked.
28697 * $sceDelegateProvider.resourceUrlBlacklist([
28698 * 'http://myapp.example.com/clickThru**'
28704 function $SceDelegateProvider() {
28705 this.SCE_CONTEXTS = SCE_CONTEXTS;
28707 // Resource URLs can also be trusted by policy.
28708 var resourceUrlWhitelist = ['self'],
28709 resourceUrlBlacklist = [];
28713 * @name $sceDelegateProvider#resourceUrlWhitelist
28716 * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
28717 * provided. This must be an array or null. A snapshot of this array is used so further
28718 * changes to the array are ignored.
28720 * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
28721 * allowed in this array.
28723 * <div class="alert alert-warning">
28724 * **Note:** an empty whitelist array will block all URLs!
28727 * @return {Array} the currently set whitelist array.
28729 * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
28730 * same origin resource requests.
28733 * Sets/Gets the whitelist of trusted resource URLs.
28735 this.resourceUrlWhitelist = function(value) {
28736 if (arguments.length) {
28737 resourceUrlWhitelist = adjustMatchers(value);
28739 return resourceUrlWhitelist;
28744 * @name $sceDelegateProvider#resourceUrlBlacklist
28747 * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
28748 * provided. This must be an array or null. A snapshot of this array is used so further
28749 * changes to the array are ignored.
28751 * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
28752 * allowed in this array.
28754 * The typical usage for the blacklist is to **block
28755 * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
28756 * these would otherwise be trusted but actually return content from the redirected domain.
28758 * Finally, **the blacklist overrides the whitelist** and has the final say.
28760 * @return {Array} the currently set blacklist array.
28762 * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
28763 * is no blacklist.)
28766 * Sets/Gets the blacklist of trusted resource URLs.
28769 this.resourceUrlBlacklist = function(value) {
28770 if (arguments.length) {
28771 resourceUrlBlacklist = adjustMatchers(value);
28773 return resourceUrlBlacklist;
28776 this.$get = ['$injector', function($injector) {
28778 var htmlSanitizer = function htmlSanitizer(html) {
28779 throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
28782 if ($injector.has('$sanitize')) {
28783 htmlSanitizer = $injector.get('$sanitize');
28787 function matchUrl(matcher, parsedUrl) {
28788 if (matcher === 'self') {
28789 return urlIsSameOrigin(parsedUrl);
28791 // definitely a regex. See adjustMatchers()
28792 return !!matcher.exec(parsedUrl.href);
28796 function isResourceUrlAllowedByPolicy(url) {
28797 var parsedUrl = urlResolve(url.toString());
28798 var i, n, allowed = false;
28799 // Ensure that at least one item from the whitelist allows this url.
28800 for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
28801 if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
28807 // Ensure that no item from the blacklist blocked this url.
28808 for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
28809 if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
28818 function generateHolderType(Base) {
28819 var holderType = function TrustedValueHolderType(trustedValue) {
28820 this.$$unwrapTrustedValue = function() {
28821 return trustedValue;
28825 holderType.prototype = new Base();
28827 holderType.prototype.valueOf = function sceValueOf() {
28828 return this.$$unwrapTrustedValue();
28830 holderType.prototype.toString = function sceToString() {
28831 return this.$$unwrapTrustedValue().toString();
28836 var trustedValueHolderBase = generateHolderType(),
28839 byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
28840 byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
28841 byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
28842 byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
28843 byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
28847 * @name $sceDelegate#trustAs
28850 * Returns an object that is trusted by angular for use in specified strict
28851 * contextual escaping contexts (such as ng-bind-html, ng-include, any src
28852 * attribute interpolation, any dom event binding attribute interpolation
28853 * such as for onclick, etc.) that uses the provided value.
28854 * See {@link ng.$sce $sce} for enabling strict contextual escaping.
28856 * @param {string} type The kind of context in which this value is safe for use. e.g. url,
28857 * resourceUrl, html, js and css.
28858 * @param {*} value The value that that should be considered trusted/safe.
28859 * @returns {*} A value that can be used to stand in for the provided `value` in places
28860 * where Angular expects a $sce.trustAs() return value.
28862 function trustAs(type, trustedValue) {
28863 var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
28864 if (!Constructor) {
28865 throw $sceMinErr('icontext',
28866 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
28867 type, trustedValue);
28869 if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
28870 return trustedValue;
28872 // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
28873 // mutable objects, we ensure here that the value passed in is actually a string.
28874 if (typeof trustedValue !== 'string') {
28875 throw $sceMinErr('itype',
28876 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
28879 return new Constructor(trustedValue);
28884 * @name $sceDelegate#valueOf
28887 * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
28888 * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
28889 * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
28891 * If the passed parameter is not a value that had been returned by {@link
28892 * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
28894 * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
28895 * call or anything else.
28896 * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
28897 * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
28898 * `value` unchanged.
28900 function valueOf(maybeTrusted) {
28901 if (maybeTrusted instanceof trustedValueHolderBase) {
28902 return maybeTrusted.$$unwrapTrustedValue();
28904 return maybeTrusted;
28910 * @name $sceDelegate#getTrusted
28913 * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
28914 * returns the originally supplied value if the queried context type is a supertype of the
28915 * created type. If this condition isn't satisfied, throws an exception.
28917 * <div class="alert alert-danger">
28918 * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
28919 * (XSS) vulnerability in your application.
28922 * @param {string} type The kind of context in which this value is to be used.
28923 * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
28924 * `$sceDelegate.trustAs`} call.
28925 * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
28926 * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
28928 function getTrusted(type, maybeTrusted) {
28929 if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
28930 return maybeTrusted;
28932 var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
28933 if (constructor && maybeTrusted instanceof constructor) {
28934 return maybeTrusted.$$unwrapTrustedValue();
28936 // If we get here, then we may only take one of two actions.
28937 // 1. sanitize the value for the requested type, or
28938 // 2. throw an exception.
28939 if (type === SCE_CONTEXTS.RESOURCE_URL) {
28940 if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
28941 return maybeTrusted;
28943 throw $sceMinErr('insecurl',
28944 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
28945 maybeTrusted.toString());
28947 } else if (type === SCE_CONTEXTS.HTML) {
28948 return htmlSanitizer(maybeTrusted);
28950 throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
28953 return { trustAs: trustAs,
28954 getTrusted: getTrusted,
28955 valueOf: valueOf };
28962 * @name $sceProvider
28967 * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
28968 * - enable/disable Strict Contextual Escaping (SCE) in a module
28969 * - override the default implementation with a custom delegate
28971 * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
28981 * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
28983 * # Strict Contextual Escaping
28985 * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
28986 * contexts to result in a value that is marked as safe to use for that context. One example of
28987 * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
28988 * to these contexts as privileged or SCE contexts.
28990 * As of version 1.2, Angular ships with SCE enabled by default.
28992 * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
28993 * one to execute arbitrary javascript by the use of the expression() syntax. Refer
28994 * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
28995 * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
28996 * to the top of your HTML document.
28998 * SCE assists in writing code in a way that (a) is secure by default and (b) makes auditing for
28999 * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
29001 * Here's an example of a binding in a privileged context:
29004 * <input ng-model="userHtml" aria-label="User input">
29005 * <div ng-bind-html="userHtml"></div>
29008 * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
29009 * disabled, this application allows the user to render arbitrary HTML into the DIV.
29010 * In a more realistic example, one may be rendering user comments, blog articles, etc. via
29011 * bindings. (HTML is just one example of a context where rendering user controlled input creates
29012 * security vulnerabilities.)
29014 * For the case of HTML, you might use a library, either on the client side, or on the server side,
29015 * to sanitize unsafe HTML before binding to the value and rendering it in the document.
29017 * How would you ensure that every place that used these types of bindings was bound to a value that
29018 * was sanitized by your library (or returned as safe for rendering by your server?) How can you
29019 * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
29020 * properties/fields and forgot to update the binding to the sanitized value?
29022 * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
29023 * determine that something explicitly says it's safe to use a value for binding in that
29024 * context. You can then audit your code (a simple grep would do) to ensure that this is only done
29025 * for those values that you can easily tell are safe - because they were received from your server,
29026 * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
29027 * allowing only the files in a specific directory to do this. Ensuring that the internal API
29028 * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
29030 * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
29031 * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
29032 * obtain values that will be accepted by SCE / privileged contexts.
29035 * ## How does it work?
29037 * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
29038 * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
29039 * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
29040 * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
29042 * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
29043 * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
29047 * var ngBindHtmlDirective = ['$sce', function($sce) {
29048 * return function(scope, element, attr) {
29049 * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
29050 * element.html(value || '');
29056 * ## Impact on loading templates
29058 * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
29059 * `templateUrl`'s specified by {@link guide/directive directives}.
29061 * By default, Angular only loads templates from the same domain and protocol as the application
29062 * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
29063 * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
29064 * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
29065 * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
29069 * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
29070 * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
29071 * policy apply in addition to this and may further restrict whether the template is successfully
29072 * loaded. This means that without the right CORS policy, loading templates from a different domain
29073 * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
29076 * ## This feels like too much overhead
29078 * It's important to remember that SCE only applies to interpolation expressions.
29080 * If your expressions are constant literals, they're automatically trusted and you don't need to
29081 * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
29082 * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
29084 * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
29085 * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
29087 * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
29088 * templates in `ng-include` from your application's domain without having to even know about SCE.
29089 * It blocks loading templates from other domains or loading templates over http from an https
29090 * served document. You can change these by setting your own custom {@link
29091 * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
29092 * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
29094 * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
29095 * application that's secure and can be audited to verify that with much more ease than bolting
29096 * security onto an application later.
29098 * <a name="contexts"></a>
29099 * ## What trusted context types are supported?
29101 * | Context | Notes |
29102 * |---------------------|----------------|
29103 * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
29104 * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
29105 * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
29106 * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG`, `VIDEO`, `AUDIO`, `SOURCE`, and `TRACK` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
29107 * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
29109 * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
29111 * Each element in these arrays must be one of the following:
29114 * - The special **string**, `'self'`, can be used to match against all URLs of the **same
29115 * domain** as the application document using the **same protocol**.
29116 * - **String** (except the special value `'self'`)
29117 * - The string is matched against the full *normalized / absolute URL* of the resource
29118 * being tested (substring matches are not good enough.)
29119 * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
29120 * match themselves.
29121 * - `*`: matches zero or more occurrences of any character other than one of the following 6
29122 * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
29124 * - `**`: matches zero or more occurrences of *any* character. As such, it's not
29125 * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
29126 * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
29127 * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
29128 * http://foo.example.com/templates/**).
29129 * - **RegExp** (*see caveat below*)
29130 * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
29131 * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
29132 * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
29133 * have good test coverage). For instance, the use of `.` in the regex is correct only in a
29134 * small number of cases. A `.` character in the regex used when matching the scheme or a
29135 * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
29136 * is highly recommended to use the string patterns and only fall back to regular expressions
29137 * as a last resort.
29138 * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
29139 * matched against the **entire** *normalized / absolute URL* of the resource being tested
29140 * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
29141 * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
29142 * - If you are generating your JavaScript from some other templating engine (not
29143 * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
29144 * remember to escape your regular expression (and be aware that you might need more than
29145 * one level of escaping depending on your templating engine and the way you interpolated
29146 * the value.) Do make use of your platform's escaping mechanism as it might be good
29147 * enough before coding your own. E.g. Ruby has
29148 * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
29149 * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
29150 * Javascript lacks a similar built in function for escaping. Take a look at Google
29151 * Closure library's [goog.string.regExpEscape(s)](
29152 * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
29154 * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
29156 * ## Show me an example using SCE.
29158 * <example module="mySceApp" deps="angular-sanitize.js" name="sce-service">
29159 * <file name="index.html">
29160 * <div ng-controller="AppController as myCtrl">
29161 * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
29162 * <b>User comments</b><br>
29163 * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
29164 * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
29166 * <div class="well">
29167 * <div ng-repeat="userComment in myCtrl.userComments">
29168 * <b>{{userComment.name}}</b>:
29169 * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
29176 * <file name="script.js">
29177 * angular.module('mySceApp', ['ngSanitize'])
29178 * .controller('AppController', ['$http', '$templateCache', '$sce',
29179 * function AppController($http, $templateCache, $sce) {
29181 * $http.get('test_data.json', {cache: $templateCache}).success(function(userComments) {
29182 * self.userComments = userComments;
29184 * self.explicitlyTrustedHtml = $sce.trustAsHtml(
29185 * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
29186 * 'sanitization."">Hover over this text.</span>');
29190 * <file name="test_data.json">
29192 * { "name": "Alice",
29194 * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
29197 * "htmlComment": "<i>Yes!</i> Am I the only other one?"
29202 * <file name="protractor.js" type="protractor">
29203 * describe('SCE doc demo', function() {
29204 * it('should sanitize untrusted values', function() {
29205 * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML'))
29206 * .toBe('<span>Is <i>anyone</i> reading this?</span>');
29209 * it('should NOT sanitize explicitly trusted values', function() {
29210 * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(
29211 * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
29212 * 'sanitization."">Hover over this text.</span>');
29220 * ## Can I disable SCE completely?
29222 * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
29223 * for little coding overhead. It will be much harder to take an SCE disabled application and
29224 * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
29225 * for cases where you have a lot of existing code that was written before SCE was introduced and
29226 * you're migrating them a module at a time.
29228 * That said, here's how you can completely disable SCE:
29231 * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
29232 * // Completely disable SCE. For demonstration purposes only!
29233 * // Do not use in new projects.
29234 * $sceProvider.enabled(false);
29240 function $SceProvider() {
29241 var enabled = true;
29245 * @name $sceProvider#enabled
29248 * @param {boolean=} value If provided, then enables/disables SCE.
29249 * @return {boolean} true if SCE is enabled, false otherwise.
29252 * Enables/disables SCE and returns the current value.
29254 this.enabled = function(value) {
29255 if (arguments.length) {
29262 /* Design notes on the default implementation for SCE.
29264 * The API contract for the SCE delegate
29265 * -------------------------------------
29266 * The SCE delegate object must provide the following 3 methods:
29268 * - trustAs(contextEnum, value)
29269 * This method is used to tell the SCE service that the provided value is OK to use in the
29270 * contexts specified by contextEnum. It must return an object that will be accepted by
29271 * getTrusted() for a compatible contextEnum and return this value.
29274 * For values that were not produced by trustAs(), return them as is. For values that were
29275 * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
29276 * trustAs is wrapping the given values into some type, this operation unwraps it when given
29279 * - getTrusted(contextEnum, value)
29280 * This function should return the a value that is safe to use in the context specified by
29281 * contextEnum or throw and exception otherwise.
29283 * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
29284 * opaque or wrapped in some holder object. That happens to be an implementation detail. For
29285 * instance, an implementation could maintain a registry of all trusted objects by context. In
29286 * such a case, trustAs() would return the same object that was passed in. getTrusted() would
29287 * return the same object passed in if it was found in the registry under a compatible context or
29288 * throw an exception otherwise. An implementation might only wrap values some of the time based
29289 * on some criteria. getTrusted() might return a value and not throw an exception for special
29290 * constants or objects even if not wrapped. All such implementations fulfill this contract.
29293 * A note on the inheritance model for SCE contexts
29294 * ------------------------------------------------
29295 * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
29296 * is purely an implementation details.
29298 * The contract is simply this:
29300 * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
29301 * will also succeed.
29303 * Inheritance happens to capture this in a natural way. In some future, we
29304 * may not use inheritance anymore. That is OK because no code outside of
29305 * sce.js and sceSpecs.js would need to be aware of this detail.
29308 this.$get = ['$parse', '$sceDelegate', function(
29309 $parse, $sceDelegate) {
29310 // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
29311 // the "expression(javascript expression)" syntax which is insecure.
29312 if (enabled && msie < 8) {
29313 throw $sceMinErr('iequirks',
29314 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
29315 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
29316 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
29319 var sce = shallowCopy(SCE_CONTEXTS);
29323 * @name $sce#isEnabled
29326 * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
29327 * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
29330 * Returns a boolean indicating if SCE is enabled.
29332 sce.isEnabled = function() {
29335 sce.trustAs = $sceDelegate.trustAs;
29336 sce.getTrusted = $sceDelegate.getTrusted;
29337 sce.valueOf = $sceDelegate.valueOf;
29340 sce.trustAs = sce.getTrusted = function(type, value) { return value; };
29341 sce.valueOf = identity;
29346 * @name $sce#parseAs
29349 * Converts Angular {@link guide/expression expression} into a function. This is like {@link
29350 * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
29351 * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
29354 * @param {string} type The kind of SCE context in which this result will be used.
29355 * @param {string} expression String expression to compile.
29356 * @returns {function(context, locals)} a function which represents the compiled expression:
29358 * * `context` – `{object}` – an object against which any expressions embedded in the strings
29359 * are evaluated against (typically a scope object).
29360 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
29363 sce.parseAs = function sceParseAs(type, expr) {
29364 var parsed = $parse(expr);
29365 if (parsed.literal && parsed.constant) {
29368 return $parse(expr, function(value) {
29369 return sce.getTrusted(type, value);
29376 * @name $sce#trustAs
29379 * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
29380 * returns an object that is trusted by angular for use in specified strict contextual
29381 * escaping contexts (such as ng-bind-html, ng-include, any src attribute
29382 * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
29383 * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
29386 * @param {string} type The kind of context in which this value is safe for use. e.g. url,
29387 * resourceUrl, html, js and css.
29388 * @param {*} value The value that that should be considered trusted/safe.
29389 * @returns {*} A value that can be used to stand in for the provided `value` in places
29390 * where Angular expects a $sce.trustAs() return value.
29395 * @name $sce#trustAsHtml
29398 * Shorthand method. `$sce.trustAsHtml(value)` →
29399 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
29401 * @param {*} value The value to trustAs.
29402 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
29403 * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
29404 * only accept expressions that are either literal constants or are the
29405 * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
29410 * @name $sce#trustAsUrl
29413 * Shorthand method. `$sce.trustAsUrl(value)` →
29414 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
29416 * @param {*} value The value to trustAs.
29417 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
29418 * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
29419 * only accept expressions that are either literal constants or are the
29420 * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
29425 * @name $sce#trustAsResourceUrl
29428 * Shorthand method. `$sce.trustAsResourceUrl(value)` →
29429 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
29431 * @param {*} value The value to trustAs.
29432 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
29433 * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
29434 * only accept expressions that are either literal constants or are the return
29435 * value of {@link ng.$sce#trustAs $sce.trustAs}.)
29440 * @name $sce#trustAsJs
29443 * Shorthand method. `$sce.trustAsJs(value)` →
29444 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
29446 * @param {*} value The value to trustAs.
29447 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
29448 * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
29449 * only accept expressions that are either literal constants or are the
29450 * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
29455 * @name $sce#getTrusted
29458 * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
29459 * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
29460 * originally supplied value if the queried context type is a supertype of the created type.
29461 * If this condition isn't satisfied, throws an exception.
29463 * @param {string} type The kind of context in which this value is to be used.
29464 * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
29466 * @returns {*} The value the was originally provided to
29467 * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
29468 * Otherwise, throws an exception.
29473 * @name $sce#getTrustedHtml
29476 * Shorthand method. `$sce.getTrustedHtml(value)` →
29477 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
29479 * @param {*} value The value to pass to `$sce.getTrusted`.
29480 * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
29485 * @name $sce#getTrustedCss
29488 * Shorthand method. `$sce.getTrustedCss(value)` →
29489 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
29491 * @param {*} value The value to pass to `$sce.getTrusted`.
29492 * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
29497 * @name $sce#getTrustedUrl
29500 * Shorthand method. `$sce.getTrustedUrl(value)` →
29501 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
29503 * @param {*} value The value to pass to `$sce.getTrusted`.
29504 * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
29509 * @name $sce#getTrustedResourceUrl
29512 * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
29513 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
29515 * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
29516 * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
29521 * @name $sce#getTrustedJs
29524 * Shorthand method. `$sce.getTrustedJs(value)` →
29525 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
29527 * @param {*} value The value to pass to `$sce.getTrusted`.
29528 * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
29533 * @name $sce#parseAsHtml
29536 * Shorthand method. `$sce.parseAsHtml(expression string)` →
29537 * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
29539 * @param {string} expression String expression to compile.
29540 * @returns {function(context, locals)} a function which represents the compiled expression:
29542 * * `context` – `{object}` – an object against which any expressions embedded in the strings
29543 * are evaluated against (typically a scope object).
29544 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
29550 * @name $sce#parseAsCss
29553 * Shorthand method. `$sce.parseAsCss(value)` →
29554 * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
29556 * @param {string} expression String expression to compile.
29557 * @returns {function(context, locals)} a function which represents the compiled expression:
29559 * * `context` – `{object}` – an object against which any expressions embedded in the strings
29560 * are evaluated against (typically a scope object).
29561 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
29567 * @name $sce#parseAsUrl
29570 * Shorthand method. `$sce.parseAsUrl(value)` →
29571 * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
29573 * @param {string} expression String expression to compile.
29574 * @returns {function(context, locals)} a function which represents the compiled expression:
29576 * * `context` – `{object}` – an object against which any expressions embedded in the strings
29577 * are evaluated against (typically a scope object).
29578 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
29584 * @name $sce#parseAsResourceUrl
29587 * Shorthand method. `$sce.parseAsResourceUrl(value)` →
29588 * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
29590 * @param {string} expression String expression to compile.
29591 * @returns {function(context, locals)} a function which represents the compiled expression:
29593 * * `context` – `{object}` – an object against which any expressions embedded in the strings
29594 * are evaluated against (typically a scope object).
29595 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
29601 * @name $sce#parseAsJs
29604 * Shorthand method. `$sce.parseAsJs(value)` →
29605 * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
29607 * @param {string} expression String expression to compile.
29608 * @returns {function(context, locals)} a function which represents the compiled expression:
29610 * * `context` – `{object}` – an object against which any expressions embedded in the strings
29611 * are evaluated against (typically a scope object).
29612 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
29616 // Shorthand delegations.
29617 var parse = sce.parseAs,
29618 getTrusted = sce.getTrusted,
29619 trustAs = sce.trustAs;
29621 forEach(SCE_CONTEXTS, function(enumValue, name) {
29622 var lName = lowercase(name);
29623 sce[camelCase('parse_as_' + lName)] = function(expr) {
29624 return parse(enumValue, expr);
29626 sce[camelCase('get_trusted_' + lName)] = function(value) {
29627 return getTrusted(enumValue, value);
29629 sce[camelCase('trust_as_' + lName)] = function(value) {
29630 return trustAs(enumValue, value);
29638 /* exported $SnifferProvider */
29641 * !!! This is an undocumented "private" service !!!
29644 * @requires $window
29645 * @requires $document
29648 * @property {boolean} history Does the browser support html5 history api ?
29649 * @property {boolean} transitions Does the browser support CSS transition events ?
29650 * @property {boolean} animations Does the browser support CSS animation events ?
29653 * This is very simple implementation of testing browser's features.
29655 function $SnifferProvider() {
29656 this.$get = ['$window', '$document', function($window, $document) {
29657 var eventSupport = {},
29658 // Chrome Packaged Apps are not allowed to access `history.pushState`.
29659 // If not sandboxed, they can be detected by the presence of `chrome.app.runtime`
29660 // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by
29661 // the presence of an extension runtime ID and the absence of other Chrome runtime APIs
29662 // (see https://developer.chrome.com/apps/manifest/sandbox).
29663 isChromePackagedApp =
29665 ($window.chrome.app && $window.chrome.app.runtime ||
29666 !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id),
29667 hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
29669 toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
29670 boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
29671 document = $document[0] || {},
29673 vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
29674 bodyStyle = document.body && document.body.style,
29675 transitions = false,
29676 animations = false,
29680 for (var prop in bodyStyle) {
29681 if ((match = vendorRegex.exec(prop))) {
29682 vendorPrefix = match[0];
29683 vendorPrefix = vendorPrefix[0].toUpperCase() + vendorPrefix.substr(1);
29688 if (!vendorPrefix) {
29689 vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
29692 transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
29693 animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
29695 if (android && (!transitions || !animations)) {
29696 transitions = isString(bodyStyle.webkitTransition);
29697 animations = isString(bodyStyle.webkitAnimation);
29703 // Android has history.pushState, but it does not update location correctly
29704 // so let's not use the history API at all.
29705 // http://code.google.com/p/android/issues/detail?id=17471
29706 // https://github.com/angular/angular.js/issues/904
29708 // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
29709 // so let's not use the history API also
29710 // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
29711 history: !!(hasHistoryPushState && !(android < 4) && !boxee),
29712 hasEvent: function(event) {
29713 // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
29714 // it. In particular the event is not fired when backspace or delete key are pressed or
29715 // when cut operation is performed.
29716 // IE10+ implements 'input' event but it erroneously fires under various situations,
29717 // e.g. when placeholder changes, or a form is focused.
29718 if (event === 'input' && msie <= 11) return false;
29720 if (isUndefined(eventSupport[event])) {
29721 var divElm = document.createElement('div');
29722 eventSupport[event] = 'on' + event in divElm;
29725 return eventSupport[event];
29728 vendorPrefix: vendorPrefix,
29729 transitions: transitions,
29730 animations: animations,
29736 var $templateRequestMinErr = minErr('$compile');
29740 * @name $templateRequestProvider
29744 * Used to configure the options passed to the {@link $http} service when making a template request.
29746 * For example, it can be used for specifying the "Accept" header that is sent to the server, when
29747 * requesting a template.
29749 function $TemplateRequestProvider() {
29755 * @name $templateRequestProvider#httpOptions
29757 * The options to be passed to the {@link $http} service when making the request.
29758 * You can use this to override options such as the "Accept" header for template requests.
29760 * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
29761 * options if not overridden here.
29763 * @param {string=} value new value for the {@link $http} options.
29764 * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
29766 this.httpOptions = function(val) {
29771 return httpOptions;
29776 * @name $templateRequest
29779 * The `$templateRequest` service runs security checks then downloads the provided template using
29780 * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
29781 * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
29782 * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
29783 * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
29784 * when `tpl` is of type string and `$templateCache` has the matching entry.
29786 * If you want to pass custom options to the `$http` service, such as setting the Accept header you
29787 * can configure this via {@link $templateRequestProvider#httpOptions}.
29789 * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
29790 * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
29792 * @return {Promise} a promise for the HTTP response data of the given URL.
29794 * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
29796 this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
29798 function handleRequestFn(tpl, ignoreRequestError) {
29799 handleRequestFn.totalPendingRequests++;
29801 // We consider the template cache holds only trusted templates, so
29802 // there's no need to go through whitelisting again for keys that already
29803 // are included in there. This also makes Angular accept any script
29804 // directive, no matter its name. However, we still need to unwrap trusted
29806 if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
29807 tpl = $sce.getTrustedResourceUrl(tpl);
29810 var transformResponse = $http.defaults && $http.defaults.transformResponse;
29812 if (isArray(transformResponse)) {
29813 transformResponse = transformResponse.filter(function(transformer) {
29814 return transformer !== defaultHttpResponseTransform;
29816 } else if (transformResponse === defaultHttpResponseTransform) {
29817 transformResponse = null;
29820 return $http.get(tpl, extend({
29821 cache: $templateCache,
29822 transformResponse: transformResponse
29824 )['finally'](function() {
29825 handleRequestFn.totalPendingRequests--;
29827 .then(function(response) {
29828 $templateCache.put(tpl, response.data);
29829 return response.data;
29832 function handleError(resp) {
29833 if (!ignoreRequestError) {
29834 throw $templateRequestMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
29835 tpl, resp.status, resp.statusText);
29837 return $q.reject(resp);
29841 handleRequestFn.totalPendingRequests = 0;
29843 return handleRequestFn;
29848 function $$TestabilityProvider() {
29849 this.$get = ['$rootScope', '$browser', '$location',
29850 function($rootScope, $browser, $location) {
29853 * @name $testability
29856 * The private $$testability service provides a collection of methods for use when debugging
29857 * or by automated test and debugging tools.
29859 var testability = {};
29862 * @name $$testability#findBindings
29865 * Returns an array of elements that are bound (via ng-bind or {{}})
29866 * to expressions matching the input.
29868 * @param {Element} element The element root to search from.
29869 * @param {string} expression The binding expression to match.
29870 * @param {boolean} opt_exactMatch If true, only returns exact matches
29871 * for the expression. Filters and whitespace are ignored.
29873 testability.findBindings = function(element, expression, opt_exactMatch) {
29874 var bindings = element.getElementsByClassName('ng-binding');
29876 forEach(bindings, function(binding) {
29877 var dataBinding = angular.element(binding).data('$binding');
29879 forEach(dataBinding, function(bindingName) {
29880 if (opt_exactMatch) {
29881 var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
29882 if (matcher.test(bindingName)) {
29883 matches.push(binding);
29886 if (bindingName.indexOf(expression) !== -1) {
29887 matches.push(binding);
29897 * @name $$testability#findModels
29900 * Returns an array of elements that are two-way found via ng-model to
29901 * expressions matching the input.
29903 * @param {Element} element The element root to search from.
29904 * @param {string} expression The model expression to match.
29905 * @param {boolean} opt_exactMatch If true, only returns exact matches
29906 * for the expression.
29908 testability.findModels = function(element, expression, opt_exactMatch) {
29909 var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
29910 for (var p = 0; p < prefixes.length; ++p) {
29911 var attributeEquals = opt_exactMatch ? '=' : '*=';
29912 var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
29913 var elements = element.querySelectorAll(selector);
29914 if (elements.length) {
29921 * @name $$testability#getLocation
29924 * Shortcut for getting the location in a browser agnostic way. Returns
29925 * the path, search, and hash. (e.g. /path?a=b#hash)
29927 testability.getLocation = function() {
29928 return $location.url();
29932 * @name $$testability#setLocation
29935 * Shortcut for navigating to a location without doing a full page reload.
29937 * @param {string} url The location url (path, search and hash,
29938 * e.g. /path?a=b#hash) to go to.
29940 testability.setLocation = function(url) {
29941 if (url !== $location.url()) {
29942 $location.url(url);
29943 $rootScope.$digest();
29948 * @name $$testability#whenStable
29951 * Calls the callback when $timeout and $http requests are completed.
29953 * @param {function} callback
29955 testability.whenStable = function(callback) {
29956 $browser.notifyWhenNoOutstandingRequests(callback);
29959 return testability;
29964 function $TimeoutProvider() {
29965 this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
29966 function($rootScope, $browser, $q, $$q, $exceptionHandler) {
29968 var deferreds = {};
29976 * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
29977 * block and delegates any exceptions to
29978 * {@link ng.$exceptionHandler $exceptionHandler} service.
29980 * The return value of calling `$timeout` is a promise, which will be resolved when
29981 * the delay has passed and the timeout function, if provided, is executed.
29983 * To cancel a timeout request, call `$timeout.cancel(promise)`.
29985 * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
29986 * synchronously flush the queue of deferred functions.
29988 * If you only want a promise that will be resolved after some specified delay
29989 * then you can call `$timeout` without the `fn` function.
29991 * @param {function()=} fn A function, whose execution should be delayed.
29992 * @param {number=} [delay=0] Delay in milliseconds.
29993 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
29994 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
29995 * @param {...*=} Pass additional parameters to the executed function.
29996 * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
29997 * will be resolved with the return value of the `fn` function.
30000 function timeout(fn, delay, invokeApply) {
30001 if (!isFunction(fn)) {
30002 invokeApply = delay;
30007 var args = sliceArgs(arguments, 3),
30008 skipApply = (isDefined(invokeApply) && !invokeApply),
30009 deferred = (skipApply ? $$q : $q).defer(),
30010 promise = deferred.promise,
30013 timeoutId = $browser.defer(function() {
30015 deferred.resolve(fn.apply(null, args));
30017 deferred.reject(e);
30018 $exceptionHandler(e);
30020 delete deferreds[promise.$$timeoutId];
30023 if (!skipApply) $rootScope.$apply();
30026 promise.$$timeoutId = timeoutId;
30027 deferreds[timeoutId] = deferred;
30035 * @name $timeout#cancel
30038 * Cancels a task associated with the `promise`. As a result of this, the promise will be
30039 * resolved with a rejection.
30041 * @param {Promise=} promise Promise returned by the `$timeout` function.
30042 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
30045 timeout.cancel = function(promise) {
30046 if (promise && promise.$$timeoutId in deferreds) {
30047 deferreds[promise.$$timeoutId].reject('canceled');
30048 delete deferreds[promise.$$timeoutId];
30049 return $browser.defer.cancel(promise.$$timeoutId);
30058 // NOTE: The usage of window and document instead of $window and $document here is
30059 // deliberate. This service depends on the specific behavior of anchor nodes created by the
30060 // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
30061 // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
30062 // doesn't know about mocked locations and resolves URLs to the real document - which is
30063 // exactly the behavior needed here. There is little value is mocking these out for this
30065 var urlParsingNode = window.document.createElement('a');
30066 var originUrl = urlResolve(window.location.href);
30071 * Implementation Notes for non-IE browsers
30072 * ----------------------------------------
30073 * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
30074 * results both in the normalizing and parsing of the URL. Normalizing means that a relative
30075 * URL will be resolved into an absolute URL in the context of the application document.
30076 * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
30077 * properties are all populated to reflect the normalized URL. This approach has wide
30078 * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
30079 * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
30081 * Implementation Notes for IE
30082 * ---------------------------
30083 * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
30084 * browsers. However, the parsed components will not be set if the URL assigned did not specify
30085 * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
30086 * work around that by performing the parsing in a 2nd step by taking a previously normalized
30087 * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
30088 * properties such as protocol, hostname, port, etc.
30091 * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
30092 * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
30093 * http://url.spec.whatwg.org/#urlutils
30094 * https://github.com/angular/angular.js/pull/2902
30095 * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
30098 * @param {string} url The URL to be parsed.
30099 * @description Normalizes and parses a URL.
30100 * @returns {object} Returns the normalized URL as a dictionary.
30102 * | member name | Description |
30103 * |---------------|----------------|
30104 * | href | A normalized version of the provided URL if it was not an absolute URL |
30105 * | protocol | The protocol including the trailing colon |
30106 * | host | The host and port (if the port is non-default) of the normalizedUrl |
30107 * | search | The search params, minus the question mark |
30108 * | hash | The hash string, minus the hash symbol
30109 * | hostname | The hostname
30110 * | port | The port, without ":"
30111 * | pathname | The pathname, beginning with "/"
30114 function urlResolve(url) {
30118 // Normalize before parse. Refer Implementation Notes on why this is
30119 // done in two steps on IE.
30120 urlParsingNode.setAttribute('href', href);
30121 href = urlParsingNode.href;
30124 urlParsingNode.setAttribute('href', href);
30126 // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
30128 href: urlParsingNode.href,
30129 protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
30130 host: urlParsingNode.host,
30131 search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
30132 hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
30133 hostname: urlParsingNode.hostname,
30134 port: urlParsingNode.port,
30135 pathname: (urlParsingNode.pathname.charAt(0) === '/')
30136 ? urlParsingNode.pathname
30137 : '/' + urlParsingNode.pathname
30142 * Parse a request URL and determine whether this is a same-origin request as the application document.
30144 * @param {string|object} requestUrl The url of the request as a string that will be resolved
30145 * or a parsed URL object.
30146 * @returns {boolean} Whether the request is for the same origin as the application document.
30148 function urlIsSameOrigin(requestUrl) {
30149 var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
30150 return (parsed.protocol === originUrl.protocol &&
30151 parsed.host === originUrl.host);
30160 * A reference to the browser's `window` object. While `window`
30161 * is globally available in JavaScript, it causes testability problems, because
30162 * it is a global variable. In angular we always refer to it through the
30163 * `$window` service, so it may be overridden, removed or mocked for testing.
30165 * Expressions, like the one defined for the `ngClick` directive in the example
30166 * below, are evaluated with respect to the current scope. Therefore, there is
30167 * no risk of inadvertently coding in a dependency on a global value in such an
30171 <example module="windowExample" name="window-service">
30172 <file name="index.html">
30174 angular.module('windowExample', [])
30175 .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
30176 $scope.greeting = 'Hello, World!';
30177 $scope.doGreeting = function(greeting) {
30178 $window.alert(greeting);
30182 <div ng-controller="ExampleController">
30183 <input type="text" ng-model="greeting" aria-label="greeting" />
30184 <button ng-click="doGreeting(greeting)">ALERT</button>
30187 <file name="protractor.js" type="protractor">
30188 it('should display the greeting in the input box', function() {
30189 element(by.model('greeting')).sendKeys('Hello, E2E Tests');
30190 // If we click the button it will block the test runner
30191 // element(':button').click();
30196 function $WindowProvider() {
30197 this.$get = valueFn(window);
30201 * @name $$cookieReader
30202 * @requires $document
30205 * This is a private service for reading cookies used by $http and ngCookies
30207 * @return {Object} a key/value map of the current cookies
30209 function $$CookieReader($document) {
30210 var rawDocument = $document[0] || {};
30211 var lastCookies = {};
30212 var lastCookieString = '';
30214 function safeGetCookie(rawDocument) {
30216 return rawDocument.cookie || '';
30222 function safeDecodeURIComponent(str) {
30224 return decodeURIComponent(str);
30230 return function() {
30231 var cookieArray, cookie, i, index, name;
30232 var currentCookieString = safeGetCookie(rawDocument);
30234 if (currentCookieString !== lastCookieString) {
30235 lastCookieString = currentCookieString;
30236 cookieArray = lastCookieString.split('; ');
30239 for (i = 0; i < cookieArray.length; i++) {
30240 cookie = cookieArray[i];
30241 index = cookie.indexOf('=');
30242 if (index > 0) { //ignore nameless cookies
30243 name = safeDecodeURIComponent(cookie.substring(0, index));
30244 // the first value that is seen for a cookie is the most
30245 // specific one. values for the same cookie name that
30246 // follow are for less specific paths.
30247 if (isUndefined(lastCookies[name])) {
30248 lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
30253 return lastCookies;
30257 $$CookieReader.$inject = ['$document'];
30260 function $$CookieReaderProvider() {
30261 this.$get = $$CookieReader;
30264 /* global currencyFilter: true,
30266 filterFilter: true,
30268 limitToFilter: true,
30269 lowercaseFilter: true,
30270 numberFilter: true,
30271 orderByFilter: true,
30272 uppercaseFilter: true,
30277 * @name $filterProvider
30280 * Filters are just functions which transform input to an output. However filters need to be
30281 * Dependency Injected. To achieve this a filter definition consists of a factory function which is
30282 * annotated with dependencies and is responsible for creating a filter function.
30284 * <div class="alert alert-warning">
30285 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
30286 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
30287 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
30288 * (`myapp_subsection_filterx`).
30292 * // Filter registration
30293 * function MyModule($provide, $filterProvider) {
30294 * // create a service to demonstrate injection (not always needed)
30295 * $provide.value('greet', function(name){
30296 * return 'Hello ' + name + '!';
30299 * // register a filter factory which uses the
30300 * // greet service to demonstrate DI.
30301 * $filterProvider.register('greet', function(greet){
30302 * // return the filter function which uses the greet service
30303 * // to generate salutation
30304 * return function(text) {
30305 * // filters need to be forgiving so check input validity
30306 * return text && greet(text) || text;
30312 * The filter function is registered with the `$injector` under the filter name suffix with
30316 * it('should be the same instance', inject(
30317 * function($filterProvider) {
30318 * $filterProvider.register('reverse', function(){
30322 * function($filter, reverseFilter) {
30323 * expect($filter('reverse')).toBe(reverseFilter);
30328 * For more information about how angular filters work, and how to create your own filters, see
30329 * {@link guide/filter Filters} in the Angular Developer Guide.
30337 * Filters are used for formatting data displayed to the user.
30339 * They can be used in view templates, controllers or services.Angular comes
30340 * with a collection of [built-in filters](api/ng/filter), but it is easy to
30341 * define your own as well.
30343 * The general syntax in templates is as follows:
30346 * {{ expression [| filter_name[:parameter_value] ... ] }}
30349 * @param {String} name Name of the filter function to retrieve
30350 * @return {Function} the filter function
30352 <example name="$filter" module="filterExample">
30353 <file name="index.html">
30354 <div ng-controller="MainCtrl">
30355 <h3>{{ originalText }}</h3>
30356 <h3>{{ filteredText }}</h3>
30360 <file name="script.js">
30361 angular.module('filterExample', [])
30362 .controller('MainCtrl', function($scope, $filter) {
30363 $scope.originalText = 'hello';
30364 $scope.filteredText = $filter('uppercase')($scope.originalText);
30369 $FilterProvider.$inject = ['$provide'];
30371 function $FilterProvider($provide) {
30372 var suffix = 'Filter';
30376 * @name $filterProvider#register
30377 * @param {string|Object} name Name of the filter function, or an object map of filters where
30378 * the keys are the filter names and the values are the filter factories.
30380 * <div class="alert alert-warning">
30381 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
30382 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
30383 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
30384 * (`myapp_subsection_filterx`).
30386 * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
30387 * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
30388 * of the registered filter instances.
30390 function register(name, factory) {
30391 if (isObject(name)) {
30393 forEach(name, function(filter, key) {
30394 filters[key] = register(key, filter);
30398 return $provide.factory(name + suffix, factory);
30401 this.register = register;
30403 this.$get = ['$injector', function($injector) {
30404 return function(name) {
30405 return $injector.get(name + suffix);
30409 ////////////////////////////////////////
30412 currencyFilter: false,
30414 filterFilter: false,
30416 limitToFilter: false,
30417 lowercaseFilter: false,
30418 numberFilter: false,
30419 orderByFilter: false,
30420 uppercaseFilter: false
30423 register('currency', currencyFilter);
30424 register('date', dateFilter);
30425 register('filter', filterFilter);
30426 register('json', jsonFilter);
30427 register('limitTo', limitToFilter);
30428 register('lowercase', lowercaseFilter);
30429 register('number', numberFilter);
30430 register('orderBy', orderByFilter);
30431 register('uppercase', uppercaseFilter);
30440 * Selects a subset of items from `array` and returns it as a new array.
30442 * @param {Array} array The source array.
30443 * @param {string|Object|function()} expression The predicate to be used for selecting items from
30448 * - `string`: The string is used for matching against the contents of the `array`. All strings or
30449 * objects with string properties in `array` that match this string will be returned. This also
30450 * applies to nested object properties.
30451 * The predicate can be negated by prefixing the string with `!`.
30453 * - `Object`: A pattern object can be used to filter specific properties on objects contained
30454 * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
30455 * which have property `name` containing "M" and property `phone` containing "1". A special
30456 * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match
30457 * against any property of the object or its nested object properties. That's equivalent to the
30458 * simple substring match with a `string` as described above. The special property name can be
30459 * overwritten, using the `anyPropertyKey` parameter.
30460 * The predicate can be negated by prefixing the string with `!`.
30461 * For example `{name: "!M"}` predicate will return an array of items which have property `name`
30462 * not containing "M".
30464 * Note that a named property will match properties on the same level only, while the special
30465 * `$` property will match properties on the same level or deeper. E.g. an array item like
30466 * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
30467 * **will** be matched by `{$: 'John'}`.
30469 * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
30470 * The function is called for each element of the array, with the element, its index, and
30471 * the entire array itself as arguments.
30473 * The final result is an array of those elements that the predicate returned true for.
30475 * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in
30476 * determining if the expected value (from the filter expression) and actual value (from
30477 * the object in the array) should be considered a match.
30481 * - `function(actual, expected)`:
30482 * The function will be given the object value and the predicate value to compare and
30483 * should return true if both values should be considered equal.
30485 * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
30486 * This is essentially strict comparison of expected and actual.
30488 * - `false`: A short hand for a function which will look for a substring match in a case
30489 * insensitive way. Primitive values are converted to strings. Objects are not compared against
30490 * primitives, unless they have a custom `toString` method (e.g. `Date` objects).
30493 * Defaults to `false`.
30495 * @param {string} [anyPropertyKey] The special property name that matches against any property.
30499 <example name="filter-filter">
30500 <file name="index.html">
30501 <div ng-init="friends = [{name:'John', phone:'555-1276'},
30502 {name:'Mary', phone:'800-BIG-MARY'},
30503 {name:'Mike', phone:'555-4321'},
30504 {name:'Adam', phone:'555-5678'},
30505 {name:'Julie', phone:'555-8765'},
30506 {name:'Juliette', phone:'555-5678'}]"></div>
30508 <label>Search: <input ng-model="searchText"></label>
30509 <table id="searchTextResults">
30510 <tr><th>Name</th><th>Phone</th></tr>
30511 <tr ng-repeat="friend in friends | filter:searchText">
30512 <td>{{friend.name}}</td>
30513 <td>{{friend.phone}}</td>
30517 <label>Any: <input ng-model="search.$"></label> <br>
30518 <label>Name only <input ng-model="search.name"></label><br>
30519 <label>Phone only <input ng-model="search.phone"></label><br>
30520 <label>Equality <input type="checkbox" ng-model="strict"></label><br>
30521 <table id="searchObjResults">
30522 <tr><th>Name</th><th>Phone</th></tr>
30523 <tr ng-repeat="friendObj in friends | filter:search:strict">
30524 <td>{{friendObj.name}}</td>
30525 <td>{{friendObj.phone}}</td>
30529 <file name="protractor.js" type="protractor">
30530 var expectFriendNames = function(expectedNames, key) {
30531 element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
30532 arr.forEach(function(wd, i) {
30533 expect(wd.getText()).toMatch(expectedNames[i]);
30538 it('should search across all fields when filtering with a string', function() {
30539 var searchText = element(by.model('searchText'));
30540 searchText.clear();
30541 searchText.sendKeys('m');
30542 expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
30544 searchText.clear();
30545 searchText.sendKeys('76');
30546 expectFriendNames(['John', 'Julie'], 'friend');
30549 it('should search in specific fields when filtering with a predicate object', function() {
30550 var searchAny = element(by.model('search.$'));
30552 searchAny.sendKeys('i');
30553 expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
30555 it('should use a equal comparison when comparator is true', function() {
30556 var searchName = element(by.model('search.name'));
30557 var strict = element(by.model('strict'));
30558 searchName.clear();
30559 searchName.sendKeys('Julie');
30561 expectFriendNames(['Julie'], 'friendObj');
30567 function filterFilter() {
30568 return function(array, expression, comparator, anyPropertyKey) {
30569 if (!isArrayLike(array)) {
30570 if (array == null) {
30573 throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
30577 anyPropertyKey = anyPropertyKey || '$';
30578 var expressionType = getTypeForFilter(expression);
30580 var matchAgainstAnyProp;
30582 switch (expressionType) {
30584 predicateFn = expression;
30590 matchAgainstAnyProp = true;
30593 predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);
30599 return Array.prototype.filter.call(array, predicateFn);
30603 // Helper functions for `filterFilter`
30604 function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {
30605 var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);
30608 if (comparator === true) {
30609 comparator = equals;
30610 } else if (!isFunction(comparator)) {
30611 comparator = function(actual, expected) {
30612 if (isUndefined(actual)) {
30613 // No substring matching against `undefined`
30616 if ((actual === null) || (expected === null)) {
30617 // No substring matching against `null`; only match against `null`
30618 return actual === expected;
30620 if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
30621 // Should not compare primitives against objects, unless they have custom `toString` method
30625 actual = lowercase('' + actual);
30626 expected = lowercase('' + expected);
30627 return actual.indexOf(expected) !== -1;
30631 predicateFn = function(item) {
30632 if (shouldMatchPrimitives && !isObject(item)) {
30633 return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);
30635 return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);
30638 return predicateFn;
30641 function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {
30642 var actualType = getTypeForFilter(actual);
30643 var expectedType = getTypeForFilter(expected);
30645 if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
30646 return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);
30647 } else if (isArray(actual)) {
30648 // In case `actual` is an array, consider it a match
30649 // if ANY of it's items matches `expected`
30650 return actual.some(function(item) {
30651 return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);
30655 switch (actualType) {
30658 if (matchAgainstAnyProp) {
30659 for (key in actual) {
30660 if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {
30664 return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);
30665 } else if (expectedType === 'object') {
30666 for (key in expected) {
30667 var expectedVal = expected[key];
30668 if (isFunction(expectedVal) || isUndefined(expectedVal)) {
30672 var matchAnyProperty = key === anyPropertyKey;
30673 var actualVal = matchAnyProperty ? actual : actual[key];
30674 if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {
30680 return comparator(actual, expected);
30685 return comparator(actual, expected);
30689 // Used for easily differentiating between `null` and actual `object`
30690 function getTypeForFilter(val) {
30691 return (val === null) ? 'null' : typeof val;
30694 var MAX_DIGITS = 22;
30695 var DECIMAL_SEP = '.';
30696 var ZERO_CHAR = '0';
30704 * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
30705 * symbol for current locale is used.
30707 * @param {number} amount Input to filter.
30708 * @param {string=} symbol Currency symbol or identifier to be displayed.
30709 * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
30710 * @returns {string} Formatted number.
30714 <example module="currencyExample" name="currency-filter">
30715 <file name="index.html">
30717 angular.module('currencyExample', [])
30718 .controller('ExampleController', ['$scope', function($scope) {
30719 $scope.amount = 1234.56;
30722 <div ng-controller="ExampleController">
30723 <input type="number" ng-model="amount" aria-label="amount"> <br>
30724 default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
30725 custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
30726 no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
30729 <file name="protractor.js" type="protractor">
30730 it('should init with 1234.56', function() {
30731 expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
30732 expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
30733 expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
30735 it('should update', function() {
30736 if (browser.params.browser === 'safari') {
30737 // Safari does not understand the minus key. See
30738 // https://github.com/angular/protractor/issues/481
30741 element(by.model('amount')).clear();
30742 element(by.model('amount')).sendKeys('-1234');
30743 expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
30744 expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
30745 expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
30750 currencyFilter.$inject = ['$locale'];
30751 function currencyFilter($locale) {
30752 var formats = $locale.NUMBER_FORMATS;
30753 return function(amount, currencySymbol, fractionSize) {
30754 if (isUndefined(currencySymbol)) {
30755 currencySymbol = formats.CURRENCY_SYM;
30758 if (isUndefined(fractionSize)) {
30759 fractionSize = formats.PATTERNS[1].maxFrac;
30762 // if null or undefined pass it through
30763 return (amount == null)
30765 : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
30766 replace(/\u00A4/g, currencySymbol);
30776 * Formats a number as text.
30778 * If the input is null or undefined, it will just be returned.
30779 * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
30780 * If the input is not a number an empty string is returned.
30783 * @param {number|string} number Number to format.
30784 * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
30785 * If this is not provided then the fraction size is computed from the current locale's number
30786 * formatting pattern. In the case of the default locale, it will be 3.
30787 * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current
30788 * locale (e.g., in the en_US locale it will have "." as the decimal separator and
30789 * include "," group separators after each third digit).
30792 <example module="numberFilterExample" name="number-filter">
30793 <file name="index.html">
30795 angular.module('numberFilterExample', [])
30796 .controller('ExampleController', ['$scope', function($scope) {
30797 $scope.val = 1234.56789;
30800 <div ng-controller="ExampleController">
30801 <label>Enter number: <input ng-model='val'></label><br>
30802 Default formatting: <span id='number-default'>{{val | number}}</span><br>
30803 No fractions: <span>{{val | number:0}}</span><br>
30804 Negative number: <span>{{-val | number:4}}</span>
30807 <file name="protractor.js" type="protractor">
30808 it('should format numbers', function() {
30809 expect(element(by.id('number-default')).getText()).toBe('1,234.568');
30810 expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
30811 expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
30814 it('should update', function() {
30815 element(by.model('val')).clear();
30816 element(by.model('val')).sendKeys('3374.333');
30817 expect(element(by.id('number-default')).getText()).toBe('3,374.333');
30818 expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
30819 expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
30824 numberFilter.$inject = ['$locale'];
30825 function numberFilter($locale) {
30826 var formats = $locale.NUMBER_FORMATS;
30827 return function(number, fractionSize) {
30829 // if null or undefined pass it through
30830 return (number == null)
30832 : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
30838 * Parse a number (as a string) into three components that can be used
30839 * for formatting the number.
30841 * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
30843 * @param {string} numStr The number to parse
30844 * @return {object} An object describing this number, containing the following keys:
30845 * - d : an array of digits containing leading zeros as necessary
30846 * - i : the number of the digits in `d` that are to the left of the decimal point
30847 * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
30850 function parse(numStr) {
30851 var exponent = 0, digits, numberOfIntegerDigits;
30855 if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
30856 numStr = numStr.replace(DECIMAL_SEP, '');
30859 // Exponential form?
30860 if ((i = numStr.search(/e/i)) > 0) {
30861 // Work out the exponent.
30862 if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
30863 numberOfIntegerDigits += +numStr.slice(i + 1);
30864 numStr = numStr.substring(0, i);
30865 } else if (numberOfIntegerDigits < 0) {
30866 // There was no decimal point or exponent so it is an integer.
30867 numberOfIntegerDigits = numStr.length;
30870 // Count the number of leading zeros.
30871 for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }
30873 if (i === (zeros = numStr.length)) {
30874 // The digits are all zero.
30876 numberOfIntegerDigits = 1;
30878 // Count the number of trailing zeros
30880 while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;
30882 // Trailing zeros are insignificant so ignore them
30883 numberOfIntegerDigits -= i;
30885 // Convert string to array of digits without leading/trailing zeros.
30886 for (j = 0; i <= zeros; i++, j++) {
30887 digits[j] = +numStr.charAt(i);
30891 // If the number overflows the maximum allowed digits then use an exponent.
30892 if (numberOfIntegerDigits > MAX_DIGITS) {
30893 digits = digits.splice(0, MAX_DIGITS - 1);
30894 exponent = numberOfIntegerDigits - 1;
30895 numberOfIntegerDigits = 1;
30898 return { d: digits, e: exponent, i: numberOfIntegerDigits };
30902 * Round the parsed number to the specified number of decimal places
30903 * This function changed the parsedNumber in-place
30905 function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
30906 var digits = parsedNumber.d;
30907 var fractionLen = digits.length - parsedNumber.i;
30909 // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
30910 fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
30912 // The index of the digit to where rounding is to occur
30913 var roundAt = fractionSize + parsedNumber.i;
30914 var digit = digits[roundAt];
30917 // Drop fractional digits beyond `roundAt`
30918 digits.splice(Math.max(parsedNumber.i, roundAt));
30920 // Set non-fractional digits beyond `roundAt` to 0
30921 for (var j = roundAt; j < digits.length; j++) {
30925 // We rounded to zero so reset the parsedNumber
30926 fractionLen = Math.max(0, fractionLen);
30927 parsedNumber.i = 1;
30928 digits.length = Math.max(1, roundAt = fractionSize + 1);
30930 for (var i = 1; i < roundAt; i++) digits[i] = 0;
30934 if (roundAt - 1 < 0) {
30935 for (var k = 0; k > roundAt; k--) {
30942 digits[roundAt - 1]++;
30946 // Pad out with zeros to get the required fraction length
30947 for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
30950 // Do any carrying, e.g. a digit was rounded up to 10
30951 var carry = digits.reduceRight(function(carry, d, i, digits) {
30953 digits[i] = d % 10;
30954 return Math.floor(d / 10);
30957 digits.unshift(carry);
30963 * Format a number into a string
30964 * @param {number} number The number to format
30966 * minFrac, // the minimum number of digits required in the fraction part of the number
30967 * maxFrac, // the maximum number of digits required in the fraction part of the number
30968 * gSize, // number of digits in each group of separated digits
30969 * lgSize, // number of digits in the last group of digits before the decimal separator
30970 * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
30971 * posPre, // the string to go in front of a positive number
30972 * negSuf, // the string to go after a negative number (e.g. `)`)
30973 * posSuf // the string to go after a positive number
30975 * @param {string} groupSep The string to separate groups of number (e.g. `,`)
30976 * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
30977 * @param {[type]} fractionSize The size of the fractional part of the number
30978 * @return {string} The number formatted as a string
30980 function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
30982 if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
30984 var isInfinity = !isFinite(number);
30985 var isZero = false;
30986 var numStr = Math.abs(number) + '',
30987 formattedText = '',
30991 formattedText = '\u221e';
30993 parsedNumber = parse(numStr);
30995 roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
30997 var digits = parsedNumber.d;
30998 var integerLen = parsedNumber.i;
30999 var exponent = parsedNumber.e;
31001 isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
31003 // pad zeros for small numbers
31004 while (integerLen < 0) {
31009 // extract decimals digits
31010 if (integerLen > 0) {
31011 decimals = digits.splice(integerLen, digits.length);
31017 // format the integer digits with grouping separators
31019 if (digits.length >= pattern.lgSize) {
31020 groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
31022 while (digits.length > pattern.gSize) {
31023 groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
31025 if (digits.length) {
31026 groups.unshift(digits.join(''));
31028 formattedText = groups.join(groupSep);
31030 // append the decimal digits
31031 if (decimals.length) {
31032 formattedText += decimalSep + decimals.join('');
31036 formattedText += 'e+' + exponent;
31039 if (number < 0 && !isZero) {
31040 return pattern.negPre + formattedText + pattern.negSuf;
31042 return pattern.posPre + formattedText + pattern.posSuf;
31046 function padNumber(num, digits, trim, negWrap) {
31048 if (num < 0 || (negWrap && num <= 0)) {
31057 while (num.length < digits) num = ZERO_CHAR + num;
31059 num = num.substr(num.length - digits);
31065 function dateGetter(name, size, offset, trim, negWrap) {
31066 offset = offset || 0;
31067 return function(date) {
31068 var value = date['get' + name]();
31069 if (offset > 0 || value > -offset) {
31072 if (value === 0 && offset === -12) value = 12;
31073 return padNumber(value, size, trim, negWrap);
31077 function dateStrGetter(name, shortForm, standAlone) {
31078 return function(date, formats) {
31079 var value = date['get' + name]();
31080 var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
31081 var get = uppercase(propPrefix + name);
31083 return formats[get][value];
31087 function timeZoneGetter(date, formats, offset) {
31088 var zone = -1 * offset;
31089 var paddedZone = (zone >= 0) ? '+' : '';
31091 paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
31092 padNumber(Math.abs(zone % 60), 2);
31097 function getFirstThursdayOfYear(year) {
31098 // 0 = index of January
31099 var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
31100 // 4 = index of Thursday (+1 to account for 1st = 5)
31101 // 11 = index of *next* Thursday (+1 account for 1st = 12)
31102 return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
31105 function getThursdayThisWeek(datetime) {
31106 return new Date(datetime.getFullYear(), datetime.getMonth(),
31107 // 4 = index of Thursday
31108 datetime.getDate() + (4 - datetime.getDay()));
31111 function weekGetter(size) {
31112 return function(date) {
31113 var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
31114 thisThurs = getThursdayThisWeek(date);
31116 var diff = +thisThurs - +firstThurs,
31117 result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
31119 return padNumber(result, size);
31123 function ampmGetter(date, formats) {
31124 return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
31127 function eraGetter(date, formats) {
31128 return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
31131 function longEraGetter(date, formats) {
31132 return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
31135 var DATE_FORMATS = {
31136 yyyy: dateGetter('FullYear', 4, 0, false, true),
31137 yy: dateGetter('FullYear', 2, 0, true, true),
31138 y: dateGetter('FullYear', 1, 0, false, true),
31139 MMMM: dateStrGetter('Month'),
31140 MMM: dateStrGetter('Month', true),
31141 MM: dateGetter('Month', 2, 1),
31142 M: dateGetter('Month', 1, 1),
31143 LLLL: dateStrGetter('Month', false, true),
31144 dd: dateGetter('Date', 2),
31145 d: dateGetter('Date', 1),
31146 HH: dateGetter('Hours', 2),
31147 H: dateGetter('Hours', 1),
31148 hh: dateGetter('Hours', 2, -12),
31149 h: dateGetter('Hours', 1, -12),
31150 mm: dateGetter('Minutes', 2),
31151 m: dateGetter('Minutes', 1),
31152 ss: dateGetter('Seconds', 2),
31153 s: dateGetter('Seconds', 1),
31154 // while ISO 8601 requires fractions to be prefixed with `.` or `,`
31155 // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
31156 sss: dateGetter('Milliseconds', 3),
31157 EEEE: dateStrGetter('Day'),
31158 EEE: dateStrGetter('Day', true),
31166 GGGG: longEraGetter
31169 var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
31170 NUMBER_STRING = /^-?\d+$/;
31178 * Formats `date` to a string based on the requested `format`.
31180 * `format` string can be composed of the following elements:
31182 * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
31183 * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
31184 * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
31185 * * `'MMMM'`: Month in year (January-December)
31186 * * `'MMM'`: Month in year (Jan-Dec)
31187 * * `'MM'`: Month in year, padded (01-12)
31188 * * `'M'`: Month in year (1-12)
31189 * * `'LLLL'`: Stand-alone month in year (January-December)
31190 * * `'dd'`: Day in month, padded (01-31)
31191 * * `'d'`: Day in month (1-31)
31192 * * `'EEEE'`: Day in Week,(Sunday-Saturday)
31193 * * `'EEE'`: Day in Week, (Sun-Sat)
31194 * * `'HH'`: Hour in day, padded (00-23)
31195 * * `'H'`: Hour in day (0-23)
31196 * * `'hh'`: Hour in AM/PM, padded (01-12)
31197 * * `'h'`: Hour in AM/PM, (1-12)
31198 * * `'mm'`: Minute in hour, padded (00-59)
31199 * * `'m'`: Minute in hour (0-59)
31200 * * `'ss'`: Second in minute, padded (00-59)
31201 * * `'s'`: Second in minute (0-59)
31202 * * `'sss'`: Millisecond in second, padded (000-999)
31203 * * `'a'`: AM/PM marker
31204 * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
31205 * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
31206 * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
31207 * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
31208 * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
31210 * `format` string can also be one of the following predefined
31211 * {@link guide/i18n localizable formats}:
31213 * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
31214 * (e.g. Sep 3, 2010 12:05:08 PM)
31215 * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
31216 * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
31217 * (e.g. Friday, September 3, 2010)
31218 * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
31219 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
31220 * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
31221 * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
31222 * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
31224 * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
31225 * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
31226 * (e.g. `"h 'o''clock'"`).
31228 * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
31229 * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
31230 * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
31231 * specified in the string input, the time is considered to be in the local timezone.
31232 * @param {string=} format Formatting rules (see Description). If not specified,
31233 * `mediumDate` is used.
31234 * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
31235 * continental US time zone abbreviations, but for general use, use a time zone offset, for
31236 * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
31237 * If not specified, the timezone of the browser will be used.
31238 * @returns {string} Formatted string or the input if input is not recognized as date/millis.
31241 <example name="filter-date">
31242 <file name="index.html">
31243 <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
31244 <span>{{1288323623006 | date:'medium'}}</span><br>
31245 <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
31246 <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
31247 <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
31248 <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
31249 <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
31250 <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
31252 <file name="protractor.js" type="protractor">
31253 it('should format date', function() {
31254 expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
31255 toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
31256 expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
31257 toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/);
31258 expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
31259 toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
31260 expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
31261 toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
31266 dateFilter.$inject = ['$locale'];
31267 function dateFilter($locale) {
31270 var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
31271 // 1 2 3 4 5 6 7 8 9 10 11
31272 function jsonStringToDate(string) {
31274 if ((match = string.match(R_ISO8601_STR))) {
31275 var date = new Date(0),
31278 dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
31279 timeSetter = match[8] ? date.setUTCHours : date.setHours;
31282 tzHour = toInt(match[9] + match[10]);
31283 tzMin = toInt(match[9] + match[11]);
31285 dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
31286 var h = toInt(match[4] || 0) - tzHour;
31287 var m = toInt(match[5] || 0) - tzMin;
31288 var s = toInt(match[6] || 0);
31289 var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
31290 timeSetter.call(date, h, m, s, ms);
31297 return function(date, format, timezone) {
31302 format = format || 'mediumDate';
31303 format = $locale.DATETIME_FORMATS[format] || format;
31304 if (isString(date)) {
31305 date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
31308 if (isNumber(date)) {
31309 date = new Date(date);
31312 if (!isDate(date) || !isFinite(date.getTime())) {
31317 match = DATE_FORMATS_SPLIT.exec(format);
31319 parts = concat(parts, match, 1);
31320 format = parts.pop();
31322 parts.push(format);
31327 var dateTimezoneOffset = date.getTimezoneOffset();
31329 dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
31330 date = convertTimezoneToLocal(date, timezone, true);
31332 forEach(parts, function(value) {
31333 fn = DATE_FORMATS[value];
31334 text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
31335 : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
31349 * Allows you to convert a JavaScript object into JSON string.
31351 * This filter is mostly useful for debugging. When using the double curly {{value}} notation
31352 * the binding is automatically converted to JSON.
31354 * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
31355 * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
31356 * @returns {string} JSON string.
31360 <example name="filter-json">
31361 <file name="index.html">
31362 <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
31363 <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
31365 <file name="protractor.js" type="protractor">
31366 it('should jsonify filtered objects', function() {
31367 expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/);
31368 expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/);
31374 function jsonFilter() {
31375 return function(object, spacing) {
31376 if (isUndefined(spacing)) {
31379 return toJson(object, spacing);
31389 * Converts string to lowercase.
31390 * @see angular.lowercase
31392 var lowercaseFilter = valueFn(lowercase);
31400 * Converts string to uppercase.
31401 * @see angular.uppercase
31403 var uppercaseFilter = valueFn(uppercase);
31411 * Creates a new array or string containing only a specified number of elements. The elements are
31412 * taken from either the beginning or the end of the source array, string or number, as specified by
31413 * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
31414 * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
31415 * it is converted to a string.
31417 * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
31418 * @param {string|number} limit - The length of the returned array or string. If the `limit` number
31419 * is positive, `limit` number of items from the beginning of the source array/string are copied.
31420 * If the number is negative, `limit` number of items from the end of the source array/string
31421 * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
31422 * the input will be returned unchanged.
31423 * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
31424 * `begin` indicates an offset from the end of `input`. Defaults to `0`.
31425 * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
31426 * less than `limit` elements.
31429 <example module="limitToExample" name="limit-to-filter">
31430 <file name="index.html">
31432 angular.module('limitToExample', [])
31433 .controller('ExampleController', ['$scope', function($scope) {
31434 $scope.numbers = [1,2,3,4,5,6,7,8,9];
31435 $scope.letters = "abcdefghi";
31436 $scope.longNumber = 2345432342;
31437 $scope.numLimit = 3;
31438 $scope.letterLimit = 3;
31439 $scope.longNumberLimit = 3;
31442 <div ng-controller="ExampleController">
31444 Limit {{numbers}} to:
31445 <input type="number" step="1" ng-model="numLimit">
31447 <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
31449 Limit {{letters}} to:
31450 <input type="number" step="1" ng-model="letterLimit">
31452 <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
31454 Limit {{longNumber}} to:
31455 <input type="number" step="1" ng-model="longNumberLimit">
31457 <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
31460 <file name="protractor.js" type="protractor">
31461 var numLimitInput = element(by.model('numLimit'));
31462 var letterLimitInput = element(by.model('letterLimit'));
31463 var longNumberLimitInput = element(by.model('longNumberLimit'));
31464 var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
31465 var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
31466 var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
31468 it('should limit the number array to first three items', function() {
31469 expect(numLimitInput.getAttribute('value')).toBe('3');
31470 expect(letterLimitInput.getAttribute('value')).toBe('3');
31471 expect(longNumberLimitInput.getAttribute('value')).toBe('3');
31472 expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
31473 expect(limitedLetters.getText()).toEqual('Output letters: abc');
31474 expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
31477 // There is a bug in safari and protractor that doesn't like the minus key
31478 // it('should update the output when -3 is entered', function() {
31479 // numLimitInput.clear();
31480 // numLimitInput.sendKeys('-3');
31481 // letterLimitInput.clear();
31482 // letterLimitInput.sendKeys('-3');
31483 // longNumberLimitInput.clear();
31484 // longNumberLimitInput.sendKeys('-3');
31485 // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
31486 // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
31487 // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
31490 it('should not exceed the maximum size of input array', function() {
31491 numLimitInput.clear();
31492 numLimitInput.sendKeys('100');
31493 letterLimitInput.clear();
31494 letterLimitInput.sendKeys('100');
31495 longNumberLimitInput.clear();
31496 longNumberLimitInput.sendKeys('100');
31497 expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
31498 expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
31499 expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
31504 function limitToFilter() {
31505 return function(input, limit, begin) {
31506 if (Math.abs(Number(limit)) === Infinity) {
31507 limit = Number(limit);
31509 limit = toInt(limit);
31511 if (isNumberNaN(limit)) return input;
31513 if (isNumber(input)) input = input.toString();
31514 if (!isArrayLike(input)) return input;
31516 begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
31517 begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
31520 return sliceFn(input, begin, begin + limit);
31523 return sliceFn(input, limit, input.length);
31525 return sliceFn(input, Math.max(0, begin + limit), begin);
31531 function sliceFn(input, begin, end) {
31532 if (isString(input)) return input.slice(begin, end);
31534 return slice.call(input, begin, end);
31543 * Returns an array containing the items from the specified `collection`, ordered by a `comparator`
31544 * function based on the values computed using the `expression` predicate.
31546 * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
31547 * `[{id: 'bar'}, {id: 'foo'}]`.
31549 * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
31552 * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker
31553 * for the preceding one. The `expression` is evaluated against each item and the output is used
31554 * for comparing with other items.
31556 * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
31559 * The comparison is done using the `comparator` function. If none is specified, a default, built-in
31560 * comparator is used (see below for details - in a nutshell, it compares numbers numerically and
31561 * strings alphabetically).
31563 * ### Under the hood
31565 * Ordering the specified `collection` happens in two phases:
31567 * 1. All items are passed through the predicate (or predicates), and the returned values are saved
31568 * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed
31569 * through a predicate that extracts the value of the `label` property, would be transformed to:
31577 * 2. The comparator function is used to sort the items, based on the derived values, types and
31580 * If you use a custom comparator, it will be called with pairs of objects of the form
31581 * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal
31582 * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the
31583 * second, or `1` otherwise.
31585 * In order to ensure that the sorting will be deterministic across platforms, if none of the
31586 * specified predicates can distinguish between two items, `orderBy` will automatically introduce a
31587 * dummy predicate that returns the item's index as `value`.
31588 * (If you are using a custom comparator, make sure it can handle this predicate as well.)
31590 * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
31591 * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
31592 * it to the comparator. The following rules govern the conversion:
31594 * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be
31595 * used instead.<br />
31596 * (If the object has a `valueOf()` method that returns another object, then the returned object
31597 * will be used in subsequent steps.)
31598 * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that
31599 * returns a primitive, its return value will be used instead.<br />
31600 * (If the object has a `toString()` method that returns another object, then the returned object
31601 * will be used in subsequent steps.)
31602 * 3. No conversion; the object itself is used.
31604 * ### The default comparator
31606 * The default, built-in comparator should be sufficient for most usecases. In short, it compares
31607 * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to
31608 * using their index in the original collection, and sorts values of different types by type.
31610 * More specifically, it follows these steps to determine the relative order of items:
31612 * 1. If the compared values are of different types, compare the types themselves alphabetically.
31613 * 2. If both values are of type `string`, compare them alphabetically in a case- and
31614 * locale-insensitive way.
31615 * 3. If both values are objects, compare their indices instead.
31616 * 4. Otherwise, return:
31617 * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).
31618 * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator).
31619 * - `1`, otherwise.
31621 * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being
31622 * saved as numbers and not strings.
31623 * **Note:** For the purpose of sorting, `null` values are treated as the string `'null'` (i.e.
31624 * `type: 'string'`, `value: 'null'`). This may cause unexpected sort order relative to
31627 * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.
31628 * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of
31629 * predicates) to be used by the comparator to determine the order of elements.
31633 * - `Function`: A getter function. This function will be called with each item as argument and
31634 * the return value will be used for sorting.
31635 * - `string`: An Angular expression. This expression will be evaluated against each item and the
31636 * result will be used for sorting. For example, use `'label'` to sort by a property called
31637 * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`
31639 * (The result of a constant expression is interpreted as a property name to be used for
31640 * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a
31641 * property called `special name`.)<br />
31642 * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,
31643 * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,
31644 * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.
31645 * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the
31646 * relative order of two items, the next predicate is used as a tie-breaker.
31648 * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
31650 * @param {boolean=} reverse - If `true`, reverse the sorting order.
31651 * @param {(Function)=} comparator - The comparator function used to determine the relative order of
31652 * value pairs. If omitted, the built-in comparator will be used.
31654 * @returns {Array} - The sorted array.
31658 * ### Ordering a table with `ngRepeat`
31660 * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by
31661 * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means
31662 * it defaults to the built-in comparator.
31664 <example name="orderBy-static" module="orderByExample1">
31665 <file name="index.html">
31666 <div ng-controller="ExampleController">
31667 <table class="friends">
31670 <th>Phone Number</th>
31673 <tr ng-repeat="friend in friends | orderBy:'-age'">
31674 <td>{{friend.name}}</td>
31675 <td>{{friend.phone}}</td>
31676 <td>{{friend.age}}</td>
31681 <file name="script.js">
31682 angular.module('orderByExample1', [])
31683 .controller('ExampleController', ['$scope', function($scope) {
31685 {name: 'John', phone: '555-1212', age: 10},
31686 {name: 'Mary', phone: '555-9876', age: 19},
31687 {name: 'Mike', phone: '555-4321', age: 21},
31688 {name: 'Adam', phone: '555-5678', age: 35},
31689 {name: 'Julie', phone: '555-8765', age: 29}
31693 <file name="style.css">
31695 border-collapse: collapse;
31699 border-bottom: 1px solid;
31701 .friends td, .friends th {
31702 border-left: 1px solid;
31705 .friends td:first-child, .friends th:first-child {
31709 <file name="protractor.js" type="protractor">
31710 // Element locators
31711 var names = element.all(by.repeater('friends').column('friend.name'));
31713 it('should sort friends by age in reverse order', function() {
31714 expect(names.get(0).getText()).toBe('Adam');
31715 expect(names.get(1).getText()).toBe('Julie');
31716 expect(names.get(2).getText()).toBe('Mike');
31717 expect(names.get(3).getText()).toBe('Mary');
31718 expect(names.get(4).getText()).toBe('John');
31725 * ### Changing parameters dynamically
31727 * All parameters can be changed dynamically. The next example shows how you can make the columns of
31728 * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.
31730 <example name="orderBy-dynamic" module="orderByExample2">
31731 <file name="index.html">
31732 <div ng-controller="ExampleController">
31733 <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
31735 <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
31737 <table class="friends">
31740 <button ng-click="sortBy('name')">Name</button>
31741 <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
31744 <button ng-click="sortBy('phone')">Phone Number</button>
31745 <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
31748 <button ng-click="sortBy('age')">Age</button>
31749 <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
31752 <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
31753 <td>{{friend.name}}</td>
31754 <td>{{friend.phone}}</td>
31755 <td>{{friend.age}}</td>
31760 <file name="script.js">
31761 angular.module('orderByExample2', [])
31762 .controller('ExampleController', ['$scope', function($scope) {
31764 {name: 'John', phone: '555-1212', age: 10},
31765 {name: 'Mary', phone: '555-9876', age: 19},
31766 {name: 'Mike', phone: '555-4321', age: 21},
31767 {name: 'Adam', phone: '555-5678', age: 35},
31768 {name: 'Julie', phone: '555-8765', age: 29}
31771 $scope.propertyName = 'age';
31772 $scope.reverse = true;
31773 $scope.friends = friends;
31775 $scope.sortBy = function(propertyName) {
31776 $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
31777 $scope.propertyName = propertyName;
31781 <file name="style.css">
31783 border-collapse: collapse;
31787 border-bottom: 1px solid;
31789 .friends td, .friends th {
31790 border-left: 1px solid;
31793 .friends td:first-child, .friends th:first-child {
31798 content: '\25b2'; // BLACK UP-POINTING TRIANGLE
31800 .sortorder.reverse:after {
31801 content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
31804 <file name="protractor.js" type="protractor">
31805 // Element locators
31806 var unsortButton = element(by.partialButtonText('unsorted'));
31807 var nameHeader = element(by.partialButtonText('Name'));
31808 var phoneHeader = element(by.partialButtonText('Phone'));
31809 var ageHeader = element(by.partialButtonText('Age'));
31810 var firstName = element(by.repeater('friends').column('friend.name').row(0));
31811 var lastName = element(by.repeater('friends').column('friend.name').row(4));
31813 it('should sort friends by some property, when clicking on the column header', function() {
31814 expect(firstName.getText()).toBe('Adam');
31815 expect(lastName.getText()).toBe('John');
31817 phoneHeader.click();
31818 expect(firstName.getText()).toBe('John');
31819 expect(lastName.getText()).toBe('Mary');
31821 nameHeader.click();
31822 expect(firstName.getText()).toBe('Adam');
31823 expect(lastName.getText()).toBe('Mike');
31826 expect(firstName.getText()).toBe('John');
31827 expect(lastName.getText()).toBe('Adam');
31830 it('should sort friends in reverse order, when clicking on the same column', function() {
31831 expect(firstName.getText()).toBe('Adam');
31832 expect(lastName.getText()).toBe('John');
31835 expect(firstName.getText()).toBe('John');
31836 expect(lastName.getText()).toBe('Adam');
31839 expect(firstName.getText()).toBe('Adam');
31840 expect(lastName.getText()).toBe('John');
31843 it('should restore the original order, when clicking "Set to unsorted"', function() {
31844 expect(firstName.getText()).toBe('Adam');
31845 expect(lastName.getText()).toBe('John');
31847 unsortButton.click();
31848 expect(firstName.getText()).toBe('John');
31849 expect(lastName.getText()).toBe('Julie');
31856 * ### Using `orderBy` inside a controller
31858 * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and
31859 * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory
31860 * and retrieve the `orderBy` filter with `$filter('orderBy')`.)
31862 <example name="orderBy-call-manually" module="orderByExample3">
31863 <file name="index.html">
31864 <div ng-controller="ExampleController">
31865 <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
31867 <button ng-click="sortBy(null)">Set to unsorted</button>
31869 <table class="friends">
31872 <button ng-click="sortBy('name')">Name</button>
31873 <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
31876 <button ng-click="sortBy('phone')">Phone Number</button>
31877 <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
31880 <button ng-click="sortBy('age')">Age</button>
31881 <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
31884 <tr ng-repeat="friend in friends">
31885 <td>{{friend.name}}</td>
31886 <td>{{friend.phone}}</td>
31887 <td>{{friend.age}}</td>
31892 <file name="script.js">
31893 angular.module('orderByExample3', [])
31894 .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
31896 {name: 'John', phone: '555-1212', age: 10},
31897 {name: 'Mary', phone: '555-9876', age: 19},
31898 {name: 'Mike', phone: '555-4321', age: 21},
31899 {name: 'Adam', phone: '555-5678', age: 35},
31900 {name: 'Julie', phone: '555-8765', age: 29}
31903 $scope.propertyName = 'age';
31904 $scope.reverse = true;
31905 $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
31907 $scope.sortBy = function(propertyName) {
31908 $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)
31909 ? !$scope.reverse : false;
31910 $scope.propertyName = propertyName;
31911 $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
31915 <file name="style.css">
31917 border-collapse: collapse;
31921 border-bottom: 1px solid;
31923 .friends td, .friends th {
31924 border-left: 1px solid;
31927 .friends td:first-child, .friends th:first-child {
31932 content: '\25b2'; // BLACK UP-POINTING TRIANGLE
31934 .sortorder.reverse:after {
31935 content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
31938 <file name="protractor.js" type="protractor">
31939 // Element locators
31940 var unsortButton = element(by.partialButtonText('unsorted'));
31941 var nameHeader = element(by.partialButtonText('Name'));
31942 var phoneHeader = element(by.partialButtonText('Phone'));
31943 var ageHeader = element(by.partialButtonText('Age'));
31944 var firstName = element(by.repeater('friends').column('friend.name').row(0));
31945 var lastName = element(by.repeater('friends').column('friend.name').row(4));
31947 it('should sort friends by some property, when clicking on the column header', function() {
31948 expect(firstName.getText()).toBe('Adam');
31949 expect(lastName.getText()).toBe('John');
31951 phoneHeader.click();
31952 expect(firstName.getText()).toBe('John');
31953 expect(lastName.getText()).toBe('Mary');
31955 nameHeader.click();
31956 expect(firstName.getText()).toBe('Adam');
31957 expect(lastName.getText()).toBe('Mike');
31960 expect(firstName.getText()).toBe('John');
31961 expect(lastName.getText()).toBe('Adam');
31964 it('should sort friends in reverse order, when clicking on the same column', function() {
31965 expect(firstName.getText()).toBe('Adam');
31966 expect(lastName.getText()).toBe('John');
31969 expect(firstName.getText()).toBe('John');
31970 expect(lastName.getText()).toBe('Adam');
31973 expect(firstName.getText()).toBe('Adam');
31974 expect(lastName.getText()).toBe('John');
31977 it('should restore the original order, when clicking "Set to unsorted"', function() {
31978 expect(firstName.getText()).toBe('Adam');
31979 expect(lastName.getText()).toBe('John');
31981 unsortButton.click();
31982 expect(firstName.getText()).toBe('John');
31983 expect(lastName.getText()).toBe('Julie');
31990 * ### Using a custom comparator
31992 * If you have very specific requirements about the way items are sorted, you can pass your own
31993 * comparator function. For example, you might need to compare some strings in a locale-sensitive
31994 * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
31995 * argument - passing `false` retains the default sorting order, i.e. ascending.)
31997 <example name="orderBy-custom-comparator" module="orderByExample4">
31998 <file name="index.html">
31999 <div ng-controller="ExampleController">
32000 <div class="friends-container custom-comparator">
32001 <h3>Locale-sensitive Comparator</h3>
32002 <table class="friends">
32005 <th>Favorite Letter</th>
32007 <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
32008 <td>{{friend.name}}</td>
32009 <td>{{friend.favoriteLetter}}</td>
32013 <div class="friends-container default-comparator">
32014 <h3>Default Comparator</h3>
32015 <table class="friends">
32018 <th>Favorite Letter</th>
32020 <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
32021 <td>{{friend.name}}</td>
32022 <td>{{friend.favoriteLetter}}</td>
32028 <file name="script.js">
32029 angular.module('orderByExample4', [])
32030 .controller('ExampleController', ['$scope', function($scope) {
32032 {name: 'John', favoriteLetter: 'Ä'},
32033 {name: 'Mary', favoriteLetter: 'Ü'},
32034 {name: 'Mike', favoriteLetter: 'Ö'},
32035 {name: 'Adam', favoriteLetter: 'H'},
32036 {name: 'Julie', favoriteLetter: 'Z'}
32039 $scope.localeSensitiveComparator = function(v1, v2) {
32040 // If we don't get strings, just compare by index
32041 if (v1.type !== 'string' || v2.type !== 'string') {
32042 return (v1.index < v2.index) ? -1 : 1;
32045 // Compare strings alphabetically, taking locale into account
32046 return v1.value.localeCompare(v2.value);
32050 <file name="style.css">
32051 .friends-container {
32052 display: inline-block;
32057 border-collapse: collapse;
32061 border-bottom: 1px solid;
32063 .friends td, .friends th {
32064 border-left: 1px solid;
32067 .friends td:first-child, .friends th:first-child {
32071 <file name="protractor.js" type="protractor">
32072 // Element locators
32073 var container = element(by.css('.custom-comparator'));
32074 var names = container.all(by.repeater('friends').column('friend.name'));
32076 it('should sort friends by favorite letter (in correct alphabetical order)', function() {
32077 expect(names.get(0).getText()).toBe('John');
32078 expect(names.get(1).getText()).toBe('Adam');
32079 expect(names.get(2).getText()).toBe('Mike');
32080 expect(names.get(3).getText()).toBe('Mary');
32081 expect(names.get(4).getText()).toBe('Julie');
32087 orderByFilter.$inject = ['$parse'];
32088 function orderByFilter($parse) {
32089 return function(array, sortPredicate, reverseOrder, compareFn) {
32091 if (array == null) return array;
32092 if (!isArrayLike(array)) {
32093 throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
32096 if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
32097 if (sortPredicate.length === 0) { sortPredicate = ['+']; }
32099 var predicates = processPredicates(sortPredicate);
32101 var descending = reverseOrder ? -1 : 1;
32103 // Define the `compare()` function. Use a default comparator if none is specified.
32104 var compare = isFunction(compareFn) ? compareFn : defaultCompare;
32106 // The next three lines are a version of a Swartzian Transform idiom from Perl
32107 // (sometimes called the Decorate-Sort-Undecorate idiom)
32108 // See https://en.wikipedia.org/wiki/Schwartzian_transform
32109 var compareValues = Array.prototype.map.call(array, getComparisonObject);
32110 compareValues.sort(doComparison);
32111 array = compareValues.map(function(item) { return item.value; });
32115 function getComparisonObject(value, index) {
32116 // NOTE: We are adding an extra `tieBreaker` value based on the element's index.
32117 // This will be used to keep the sort stable when none of the input predicates can
32118 // distinguish between two elements.
32121 tieBreaker: {value: index, type: 'number', index: index},
32122 predicateValues: predicates.map(function(predicate) {
32123 return getPredicateValue(predicate.get(value), index);
32128 function doComparison(v1, v2) {
32129 for (var i = 0, ii = predicates.length; i < ii; i++) {
32130 var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
32132 return result * predicates[i].descending * descending;
32136 return compare(v1.tieBreaker, v2.tieBreaker) * descending;
32140 function processPredicates(sortPredicates) {
32141 return sortPredicates.map(function(predicate) {
32142 var descending = 1, get = identity;
32144 if (isFunction(predicate)) {
32146 } else if (isString(predicate)) {
32147 if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) {
32148 descending = predicate.charAt(0) === '-' ? -1 : 1;
32149 predicate = predicate.substring(1);
32151 if (predicate !== '') {
32152 get = $parse(predicate);
32153 if (get.constant) {
32155 get = function(value) { return value[key]; };
32159 return {get: get, descending: descending};
32163 function isPrimitive(value) {
32164 switch (typeof value) {
32165 case 'number': /* falls through */
32166 case 'boolean': /* falls through */
32174 function objectValue(value) {
32175 // If `valueOf` is a valid function use that
32176 if (isFunction(value.valueOf)) {
32177 value = value.valueOf();
32178 if (isPrimitive(value)) return value;
32180 // If `toString` is a valid function and not the one from `Object.prototype` use that
32181 if (hasCustomToString(value)) {
32182 value = value.toString();
32183 if (isPrimitive(value)) return value;
32189 function getPredicateValue(value, index) {
32190 var type = typeof value;
32191 if (value === null) {
32194 } else if (type === 'object') {
32195 value = objectValue(value);
32197 return {value: value, type: type, index: index};
32200 function defaultCompare(v1, v2) {
32202 var type1 = v1.type;
32203 var type2 = v2.type;
32205 if (type1 === type2) {
32206 var value1 = v1.value;
32207 var value2 = v2.value;
32209 if (type1 === 'string') {
32210 // Compare strings case-insensitively
32211 value1 = value1.toLowerCase();
32212 value2 = value2.toLowerCase();
32213 } else if (type1 === 'object') {
32214 // For basic objects, use the position of the object
32215 // in the collection instead of the value
32216 if (isObject(value1)) value1 = v1.index;
32217 if (isObject(value2)) value2 = v2.index;
32220 if (value1 !== value2) {
32221 result = value1 < value2 ? -1 : 1;
32224 result = type1 < type2 ? -1 : 1;
32231 function ngDirective(directive) {
32232 if (isFunction(directive)) {
32237 directive.restrict = directive.restrict || 'AC';
32238 return valueFn(directive);
32247 * Modifies the default behavior of the html a tag so that the default action is prevented when
32248 * the href attribute is empty.
32250 * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive.
32252 var htmlAnchorDirective = valueFn({
32254 compile: function(element, attr) {
32255 if (!attr.href && !attr.xlinkHref) {
32256 return function(scope, element) {
32257 // If the linked element is not an anchor tag anymore, do nothing
32258 if (element[0].nodeName.toLowerCase() !== 'a') return;
32260 // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
32261 var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
32262 'xlink:href' : 'href';
32263 element.on('click', function(event) {
32264 // if we have no href url, then don't navigate anywhere.
32265 if (!element.attr(href)) {
32266 event.preventDefault();
32281 * Using Angular markup like `{{hash}}` in an href attribute will
32282 * make the link go to the wrong URL if the user clicks it before
32283 * Angular has a chance to replace the `{{hash}}` markup with its
32284 * value. Until Angular replaces the markup the link will be broken
32285 * and will most likely return a 404 error. The `ngHref` directive
32286 * solves this problem.
32288 * The wrong way to write it:
32290 * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
32293 * The correct way to write it:
32295 * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
32299 * @param {template} ngHref any string which can contain `{{}}` markup.
32302 * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
32303 * in links and their different behaviors:
32304 <example name="ng-href">
32305 <file name="index.html">
32306 <input ng-model="value" /><br />
32307 <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
32308 <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
32309 <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
32310 <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
32311 <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
32312 <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
32314 <file name="protractor.js" type="protractor">
32315 it('should execute ng-click but not reload when href without value', function() {
32316 element(by.id('link-1')).click();
32317 expect(element(by.model('value')).getAttribute('value')).toEqual('1');
32318 expect(element(by.id('link-1')).getAttribute('href')).toBe('');
32321 it('should execute ng-click but not reload when href empty string', function() {
32322 element(by.id('link-2')).click();
32323 expect(element(by.model('value')).getAttribute('value')).toEqual('2');
32324 expect(element(by.id('link-2')).getAttribute('href')).toBe('');
32327 it('should execute ng-click and change url when ng-href specified', function() {
32328 expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
32330 element(by.id('link-3')).click();
32332 // At this point, we navigate away from an Angular page, so we need
32333 // to use browser.driver to get the base webdriver.
32335 browser.wait(function() {
32336 return browser.driver.getCurrentUrl().then(function(url) {
32337 return url.match(/\/123$/);
32339 }, 5000, 'page should navigate to /123');
32342 it('should execute ng-click but not reload when href empty string and name specified', function() {
32343 element(by.id('link-4')).click();
32344 expect(element(by.model('value')).getAttribute('value')).toEqual('4');
32345 expect(element(by.id('link-4')).getAttribute('href')).toBe('');
32348 it('should execute ng-click but not reload when no href but name specified', function() {
32349 element(by.id('link-5')).click();
32350 expect(element(by.model('value')).getAttribute('value')).toEqual('5');
32351 expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
32354 it('should only change url when only ng-href', function() {
32355 element(by.model('value')).clear();
32356 element(by.model('value')).sendKeys('6');
32357 expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
32359 element(by.id('link-6')).click();
32361 // At this point, we navigate away from an Angular page, so we need
32362 // to use browser.driver to get the base webdriver.
32363 browser.wait(function() {
32364 return browser.driver.getCurrentUrl().then(function(url) {
32365 return url.match(/\/6$/);
32367 }, 5000, 'page should navigate to /6');
32380 * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
32381 * work right: The browser will fetch from the URL with the literal
32382 * text `{{hash}}` until Angular replaces the expression inside
32383 * `{{hash}}`. The `ngSrc` directive solves this problem.
32385 * The buggy way to write it:
32387 * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
32390 * The correct way to write it:
32392 * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
32396 * @param {template} ngSrc any string which can contain `{{}}` markup.
32406 * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
32407 * work right: The browser will fetch from the URL with the literal
32408 * text `{{hash}}` until Angular replaces the expression inside
32409 * `{{hash}}`. The `ngSrcset` directive solves this problem.
32411 * The buggy way to write it:
32413 * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
32416 * The correct way to write it:
32418 * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
32422 * @param {template} ngSrcset any string which can contain `{{}}` markup.
32433 * This directive sets the `disabled` attribute on the element if the
32434 * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
32436 * A special directive is necessary because we cannot use interpolation inside the `disabled`
32437 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
32440 <example name="ng-disabled">
32441 <file name="index.html">
32442 <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
32443 <button ng-model="button" ng-disabled="checked">Button</button>
32445 <file name="protractor.js" type="protractor">
32446 it('should toggle button', function() {
32447 expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
32448 element(by.model('checked')).click();
32449 expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
32455 * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
32456 * then the `disabled` attribute will be set on the element
32467 * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
32469 * Note that this directive should not be used together with {@link ngModel `ngModel`},
32470 * as this can lead to unexpected behavior.
32472 * A special directive is necessary because we cannot use interpolation inside the `checked`
32473 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
32476 <example name="ng-checked">
32477 <file name="index.html">
32478 <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
32479 <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
32481 <file name="protractor.js" type="protractor">
32482 it('should check both checkBoxes', function() {
32483 expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
32484 element(by.model('master')).click();
32485 expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
32491 * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
32492 * then the `checked` attribute will be set on the element
32504 * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.
32505 * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on
32506 * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.
32508 * A special directive is necessary because we cannot use interpolation inside the `readonly`
32509 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
32512 <example name="ng-readonly">
32513 <file name="index.html">
32514 <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
32515 <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
32517 <file name="protractor.js" type="protractor">
32518 it('should toggle readonly attr', function() {
32519 expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
32520 element(by.model('checked')).click();
32521 expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
32527 * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
32528 * then special attribute "readonly" will be set on the element
32540 * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
32542 * A special directive is necessary because we cannot use interpolation inside the `selected`
32543 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
32545 * <div class="alert alert-warning">
32546 * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only
32547 * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you
32548 * should not use `ngSelected` on the options, as `ngModel` will set the select value and
32549 * selected options.
32553 <example name="ng-selected">
32554 <file name="index.html">
32555 <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
32556 <select aria-label="ngSelected demo">
32557 <option>Hello!</option>
32558 <option id="greet" ng-selected="selected">Greetings!</option>
32561 <file name="protractor.js" type="protractor">
32562 it('should select Greetings!', function() {
32563 expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
32564 element(by.model('selected')).click();
32565 expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
32571 * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
32572 * then special attribute "selected" will be set on the element
32583 * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
32585 * A special directive is necessary because we cannot use interpolation inside the `open`
32586 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
32588 * ## A note about browser compatibility
32590 * Edge, Firefox, and Internet Explorer do not support the `details` element, it is
32591 * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.
32594 <example name="ng-open">
32595 <file name="index.html">
32596 <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
32597 <details id="details" ng-open="open">
32598 <summary>Show/Hide me</summary>
32601 <file name="protractor.js" type="protractor">
32602 it('should toggle open', function() {
32603 expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
32604 element(by.model('open')).click();
32605 expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
32611 * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
32612 * then special attribute "open" will be set on the element
32615 var ngAttributeAliasDirectives = {};
32617 // boolean attrs are evaluated
32618 forEach(BOOLEAN_ATTR, function(propName, attrName) {
32619 // binding to multiple is not supported
32620 if (propName === 'multiple') return;
32622 function defaultLinkFn(scope, element, attr) {
32623 scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
32624 attr.$set(attrName, !!value);
32628 var normalized = directiveNormalize('ng-' + attrName);
32629 var linkFn = defaultLinkFn;
32631 if (propName === 'checked') {
32632 linkFn = function(scope, element, attr) {
32633 // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
32634 if (attr.ngModel !== attr[normalized]) {
32635 defaultLinkFn(scope, element, attr);
32640 ngAttributeAliasDirectives[normalized] = function() {
32649 // aliased input attrs are evaluated
32650 forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
32651 ngAttributeAliasDirectives[ngAttr] = function() {
32654 link: function(scope, element, attr) {
32655 //special case ngPattern when a literal regular expression value
32656 //is used as the expression (this way we don't have to watch anything).
32657 if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') {
32658 var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
32660 attr.$set('ngPattern', new RegExp(match[1], match[2]));
32665 scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
32666 attr.$set(ngAttr, value);
32673 // ng-src, ng-srcset, ng-href are interpolated
32674 forEach(['src', 'srcset', 'href'], function(attrName) {
32675 var normalized = directiveNormalize('ng-' + attrName);
32676 ngAttributeAliasDirectives[normalized] = function() {
32678 priority: 99, // it needs to run after the attributes are interpolated
32679 link: function(scope, element, attr) {
32680 var propName = attrName,
32683 if (attrName === 'href' &&
32684 toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
32685 name = 'xlinkHref';
32686 attr.$attr[name] = 'xlink:href';
32690 attr.$observe(normalized, function(value) {
32692 if (attrName === 'href') {
32693 attr.$set(name, null);
32698 attr.$set(name, value);
32700 // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
32701 // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
32702 // to set the property as well to achieve the desired effect.
32703 // we use attr[attrName] value since $set can sanitize the url.
32704 if (msie && propName) element.prop(propName, attr[name]);
32711 /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
32713 var nullFormCtrl = {
32715 $$renameControl: nullFormRenameControl,
32716 $removeControl: noop,
32717 $setValidity: noop,
32719 $setPristine: noop,
32720 $setSubmitted: noop
32722 SUBMITTED_CLASS = 'ng-submitted';
32724 function nullFormRenameControl(control, name) {
32725 control.$name = name;
32730 * @name form.FormController
32732 * @property {boolean} $pristine True if user has not interacted with the form yet.
32733 * @property {boolean} $dirty True if user has already interacted with the form.
32734 * @property {boolean} $valid True if all of the containing forms and controls are valid.
32735 * @property {boolean} $invalid True if at least one containing control or form is invalid.
32736 * @property {boolean} $pending True if at least one containing control or form is pending.
32737 * @property {boolean} $submitted True if user has submitted the form even if its invalid.
32739 * @property {Object} $error Is an object hash, containing references to controls or
32740 * forms with failing validators, where:
32742 * - keys are validation tokens (error names),
32743 * - values are arrays of controls or forms that have a failing validator for given error name.
32745 * Built-in validation tokens:
32757 * - `datetimelocal`
32763 * `FormController` keeps track of all its controls and nested forms as well as the state of them,
32764 * such as being valid/invalid or dirty/pristine.
32766 * Each {@link ng.directive:form form} directive creates an instance
32767 * of `FormController`.
32770 //asks for $scope to fool the BC controller module
32771 FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
32772 function FormController(element, attrs, $scope, $animate, $interpolate) {
32778 form.$$success = {};
32779 form.$pending = undefined;
32780 form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
32781 form.$dirty = false;
32782 form.$pristine = true;
32783 form.$valid = true;
32784 form.$invalid = false;
32785 form.$submitted = false;
32786 form.$$parentForm = nullFormCtrl;
32790 * @name form.FormController#$rollbackViewValue
32793 * Rollback all form controls pending updates to the `$modelValue`.
32795 * Updates may be pending by a debounced event or because the input is waiting for a some future
32796 * event defined in `ng-model-options`. This method is typically needed by the reset button of
32797 * a form that uses `ng-model-options` to pend updates.
32799 form.$rollbackViewValue = function() {
32800 forEach(controls, function(control) {
32801 control.$rollbackViewValue();
32807 * @name form.FormController#$commitViewValue
32810 * Commit all form controls pending updates to the `$modelValue`.
32812 * Updates may be pending by a debounced event or because the input is waiting for a some future
32813 * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
32814 * usually handles calling this in response to input events.
32816 form.$commitViewValue = function() {
32817 forEach(controls, function(control) {
32818 control.$commitViewValue();
32824 * @name form.FormController#$addControl
32825 * @param {object} control control object, either a {@link form.FormController} or an
32826 * {@link ngModel.NgModelController}
32829 * Register a control with the form. Input elements using ngModelController do this automatically
32830 * when they are linked.
32832 * Note that the current state of the control will not be reflected on the new parent form. This
32833 * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
32836 * However, if the method is used programmatically, for example by adding dynamically created controls,
32837 * or controls that have been previously removed without destroying their corresponding DOM element,
32838 * it's the developers responsibility to make sure the current state propagates to the parent form.
32840 * For example, if an input control is added that is already `$dirty` and has `$error` properties,
32841 * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
32843 form.$addControl = function(control) {
32844 // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
32845 // and not added to the scope. Now we throw an error.
32846 assertNotHasOwnProperty(control.$name, 'input');
32847 controls.push(control);
32849 if (control.$name) {
32850 form[control.$name] = control;
32853 control.$$parentForm = form;
32856 // Private API: rename a form control
32857 form.$$renameControl = function(control, newName) {
32858 var oldName = control.$name;
32860 if (form[oldName] === control) {
32861 delete form[oldName];
32863 form[newName] = control;
32864 control.$name = newName;
32869 * @name form.FormController#$removeControl
32870 * @param {object} control control object, either a {@link form.FormController} or an
32871 * {@link ngModel.NgModelController}
32874 * Deregister a control from the form.
32876 * Input elements using ngModelController do this automatically when they are destroyed.
32878 * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
32879 * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
32880 * different from case to case. For example, removing the only `$dirty` control from a form may or
32881 * may not mean that the form is still `$dirty`.
32883 form.$removeControl = function(control) {
32884 if (control.$name && form[control.$name] === control) {
32885 delete form[control.$name];
32887 forEach(form.$pending, function(value, name) {
32888 form.$setValidity(name, null, control);
32890 forEach(form.$error, function(value, name) {
32891 form.$setValidity(name, null, control);
32893 forEach(form.$$success, function(value, name) {
32894 form.$setValidity(name, null, control);
32897 arrayRemove(controls, control);
32898 control.$$parentForm = nullFormCtrl;
32904 * @name form.FormController#$setValidity
32907 * Sets the validity of a form control.
32909 * This method will also propagate to parent forms.
32911 addSetValidityMethod({
32914 set: function(object, property, controller) {
32915 var list = object[property];
32917 object[property] = [controller];
32919 var index = list.indexOf(controller);
32920 if (index === -1) {
32921 list.push(controller);
32925 unset: function(object, property, controller) {
32926 var list = object[property];
32930 arrayRemove(list, controller);
32931 if (list.length === 0) {
32932 delete object[property];
32940 * @name form.FormController#$setDirty
32943 * Sets the form to a dirty state.
32945 * This method can be called to add the 'ng-dirty' class and set the form to a dirty
32946 * state (ng-dirty class). This method will also propagate to parent forms.
32948 form.$setDirty = function() {
32949 $animate.removeClass(element, PRISTINE_CLASS);
32950 $animate.addClass(element, DIRTY_CLASS);
32951 form.$dirty = true;
32952 form.$pristine = false;
32953 form.$$parentForm.$setDirty();
32958 * @name form.FormController#$setPristine
32961 * Sets the form to its pristine state.
32963 * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes
32964 * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted`
32967 * This method will also propagate to all the controls contained in this form.
32969 * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
32970 * saving or resetting it.
32972 form.$setPristine = function() {
32973 $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
32974 form.$dirty = false;
32975 form.$pristine = true;
32976 form.$submitted = false;
32977 forEach(controls, function(control) {
32978 control.$setPristine();
32984 * @name form.FormController#$setUntouched
32987 * Sets the form to its untouched state.
32989 * This method can be called to remove the 'ng-touched' class and set the form controls to their
32990 * untouched state (ng-untouched class).
32992 * Setting a form controls back to their untouched state is often useful when setting the form
32993 * back to its pristine state.
32995 form.$setUntouched = function() {
32996 forEach(controls, function(control) {
32997 control.$setUntouched();
33003 * @name form.FormController#$setSubmitted
33006 * Sets the form to its submitted state.
33008 form.$setSubmitted = function() {
33009 $animate.addClass(element, SUBMITTED_CLASS);
33010 form.$submitted = true;
33011 form.$$parentForm.$setSubmitted();
33021 * Nestable alias of {@link ng.directive:form `form`} directive. HTML
33022 * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
33023 * sub-group of controls needs to be determined.
33025 * Note: the purpose of `ngForm` is to group controls,
33026 * but not to be a replacement for the `<form>` tag with all of its capabilities
33027 * (e.g. posting to the server, ...).
33029 * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
33030 * related scope, under this name.
33040 * Directive that instantiates
33041 * {@link form.FormController FormController}.
33043 * If the `name` attribute is specified, the form controller is published onto the current scope under
33046 * # Alias: {@link ng.directive:ngForm `ngForm`}
33048 * In Angular, forms can be nested. This means that the outer form is valid when all of the child
33049 * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
33050 * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
33051 * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
33052 * of controls needs to be determined.
33055 * - `ng-valid` is set if the form is valid.
33056 * - `ng-invalid` is set if the form is invalid.
33057 * - `ng-pending` is set if the form is pending.
33058 * - `ng-pristine` is set if the form is pristine.
33059 * - `ng-dirty` is set if the form is dirty.
33060 * - `ng-submitted` is set if the form was submitted.
33062 * Keep in mind that ngAnimate can detect each of these classes when added and removed.
33065 * # Submitting a form and preventing the default action
33067 * Since the role of forms in client-side Angular applications is different than in classical
33068 * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
33069 * page reload that sends the data to the server. Instead some javascript logic should be triggered
33070 * to handle the form submission in an application-specific way.
33072 * For this reason, Angular prevents the default action (form submission to the server) unless the
33073 * `<form>` element has an `action` attribute specified.
33075 * You can use one of the following two ways to specify what javascript method should be called when
33076 * a form is submitted:
33078 * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
33079 * - {@link ng.directive:ngClick ngClick} directive on the first
33080 * button or input field of type submit (input[type=submit])
33082 * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
33083 * or {@link ng.directive:ngClick ngClick} directives.
33084 * This is because of the following form submission rules in the HTML specification:
33086 * - If a form has only one input field then hitting enter in this field triggers form submit
33088 * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
33089 * doesn't trigger submit
33090 * - if a form has one or more input fields and one or more buttons or input[type=submit] then
33091 * hitting enter in any of the input fields will trigger the click handler on the *first* button or
33092 * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
33094 * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
33095 * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
33096 * to have access to the updated model.
33098 * ## Animation Hooks
33100 * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
33101 * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
33102 * other validations that are performed within the form. Animations in ngForm are similar to how
33103 * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
33104 * as JS animations.
33106 * The following example shows a simple way to utilize CSS transitions to style a form element
33107 * that has been rendered as invalid after it has been validated:
33110 * //be sure to include ngAnimate as a module to hook into more
33111 * //advanced animations
33113 * transition:0.5s linear all;
33114 * background: white;
33116 * .my-form.ng-invalid {
33123 <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
33124 <file name="index.html">
33126 angular.module('formExample', [])
33127 .controller('FormController', ['$scope', function($scope) {
33128 $scope.userType = 'guest';
33133 transition:all linear 0.5s;
33134 background: transparent;
33136 .my-form.ng-invalid {
33140 <form name="myForm" ng-controller="FormController" class="my-form">
33141 userType: <input name="input" ng-model="userType" required>
33142 <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
33143 <code>userType = {{userType}}</code><br>
33144 <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
33145 <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
33146 <code>myForm.$valid = {{myForm.$valid}}</code><br>
33147 <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
33150 <file name="protractor.js" type="protractor">
33151 it('should initialize to model', function() {
33152 var userType = element(by.binding('userType'));
33153 var valid = element(by.binding('myForm.input.$valid'));
33155 expect(userType.getText()).toContain('guest');
33156 expect(valid.getText()).toContain('true');
33159 it('should be invalid if empty', function() {
33160 var userType = element(by.binding('userType'));
33161 var valid = element(by.binding('myForm.input.$valid'));
33162 var userInput = element(by.model('userType'));
33165 userInput.sendKeys('');
33167 expect(userType.getText()).toEqual('userType =');
33168 expect(valid.getText()).toContain('false');
33173 * @param {string=} name Name of the form. If specified, the form controller will be published into
33174 * related scope, under this name.
33176 var formDirectiveFactory = function(isNgForm) {
33177 return ['$timeout', '$parse', function($timeout, $parse) {
33178 var formDirective = {
33180 restrict: isNgForm ? 'EAC' : 'E',
33181 require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
33182 controller: FormController,
33183 compile: function ngFormCompile(formElement, attr) {
33184 // Setup initial state of the control
33185 formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
33187 var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
33190 pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
33191 var controller = ctrls[0];
33193 // if `action` attr is not present on the form, prevent the default action (submission)
33194 if (!('action' in attr)) {
33195 // we can't use jq events because if a form is destroyed during submission the default
33196 // action is not prevented. see #1238
33198 // IE 9 is not affected because it doesn't fire a submit event and try to do a full
33199 // page reload if the form was destroyed by submission of the form via a click handler
33200 // on a button in the form. Looks like an IE9 specific bug.
33201 var handleFormSubmission = function(event) {
33202 scope.$apply(function() {
33203 controller.$commitViewValue();
33204 controller.$setSubmitted();
33207 event.preventDefault();
33210 addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
33212 // unregister the preventDefault listener so that we don't not leak memory but in a
33213 // way that will achieve the prevention of the default action.
33214 formElement.on('$destroy', function() {
33215 $timeout(function() {
33216 removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
33221 var parentFormCtrl = ctrls[1] || controller.$$parentForm;
33222 parentFormCtrl.$addControl(controller);
33224 var setter = nameAttr ? getSetter(controller.$name) : noop;
33227 setter(scope, controller);
33228 attr.$observe(nameAttr, function(newValue) {
33229 if (controller.$name === newValue) return;
33230 setter(scope, undefined);
33231 controller.$$parentForm.$$renameControl(controller, newValue);
33232 setter = getSetter(controller.$name);
33233 setter(scope, controller);
33236 formElement.on('$destroy', function() {
33237 controller.$$parentForm.$removeControl(controller);
33238 setter(scope, undefined);
33239 extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
33246 return formDirective;
33248 function getSetter(expression) {
33249 if (expression === '') {
33250 //create an assignable expression, so forms with an empty name can be renamed later
33251 return $parse('this[""]').assign;
33253 return $parse(expression).assign || noop;
33258 var formDirective = formDirectiveFactory();
33259 var ngFormDirective = formDirectiveFactory(true);
33262 VALID_CLASS: false,
33263 INVALID_CLASS: false,
33264 PRISTINE_CLASS: false,
33265 DIRTY_CLASS: false,
33266 ngModelMinErr: false
33269 // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
33270 var ISO_DATE_REGEXP = /^\d{4,}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+(?:[+-][0-2]\d:[0-5]\d|Z)$/;
33271 // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
33272 // Note: We are being more lenient, because browsers are too.
33282 // 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999
33283 var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
33284 // eslint-disable-next-line max-len
33285 var EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
33286 var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
33287 var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
33288 var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
33289 var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
33290 var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
33291 var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
33293 var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
33294 var PARTIAL_VALIDATION_TYPES = createMap();
33295 forEach('date,datetime-local,month,time,week'.split(','), function(type) {
33296 PARTIAL_VALIDATION_TYPES[type] = true;
33303 * @name input[text]
33306 * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
33309 * @param {string} ngModel Assignable angular expression to data-bind to.
33310 * @param {string=} name Property name of the form under which the control is published.
33311 * @param {string=} required Adds `required` validation error key if the value is not entered.
33312 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
33313 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
33314 * `required` when you want to data-bind to the `required` attribute.
33315 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
33317 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
33318 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
33320 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
33321 * that contains the regular expression body that will be converted to a regular expression
33322 * as in the ngPattern directive.
33323 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
33324 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
33325 * If the expression evaluates to a RegExp object, then this is used directly.
33326 * If the expression evaluates to a string, then it will be converted to a RegExp
33327 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
33328 * `new RegExp('^abc$')`.<br />
33329 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
33330 * start at the index of the last search's match, thus not taking the whole input value into
33332 * @param {string=} ngChange Angular expression to be executed when input changes due to user
33333 * interaction with the input element.
33334 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
33335 * This parameter is ignored for input[type=password] controls, which will never trim the
33339 <example name="text-input-directive" module="textInputExample">
33340 <file name="index.html">
33342 angular.module('textInputExample', [])
33343 .controller('ExampleController', ['$scope', function($scope) {
33346 word: /^\s*\w*\s*$/
33350 <form name="myForm" ng-controller="ExampleController">
33351 <label>Single word:
33352 <input type="text" name="input" ng-model="example.text"
33353 ng-pattern="example.word" required ng-trim="false">
33356 <span class="error" ng-show="myForm.input.$error.required">
33358 <span class="error" ng-show="myForm.input.$error.pattern">
33359 Single word only!</span>
33361 <code>text = {{example.text}}</code><br/>
33362 <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
33363 <code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
33364 <code>myForm.$valid = {{myForm.$valid}}</code><br/>
33365 <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
33368 <file name="protractor.js" type="protractor">
33369 var text = element(by.binding('example.text'));
33370 var valid = element(by.binding('myForm.input.$valid'));
33371 var input = element(by.model('example.text'));
33373 it('should initialize to model', function() {
33374 expect(text.getText()).toContain('guest');
33375 expect(valid.getText()).toContain('true');
33378 it('should be invalid if empty', function() {
33380 input.sendKeys('');
33382 expect(text.getText()).toEqual('text =');
33383 expect(valid.getText()).toContain('false');
33386 it('should be invalid if multi word', function() {
33388 input.sendKeys('hello world');
33390 expect(valid.getText()).toContain('false');
33395 'text': textInputType,
33399 * @name input[date]
33402 * Input with date validation and transformation. In browsers that do not yet support
33403 * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
33404 * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
33405 * modern browsers do not yet support this input type, it is important to provide cues to users on the
33406 * expected input format via a placeholder or label.
33408 * The model must always be a Date object, otherwise Angular will throw an error.
33409 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
33411 * The timezone to be used to read/write the `Date` instance in the model can be defined using
33412 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
33414 * @param {string} ngModel Assignable angular expression to data-bind to.
33415 * @param {string=} name Property name of the form under which the control is published.
33416 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
33417 * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
33418 * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
33419 * constraint validation.
33420 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
33421 * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
33422 * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
33423 * constraint validation.
33424 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
33425 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
33426 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
33427 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
33428 * @param {string=} required Sets `required` validation error key if the value is not entered.
33429 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
33430 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
33431 * `required` when you want to data-bind to the `required` attribute.
33432 * @param {string=} ngChange Angular expression to be executed when input changes due to user
33433 * interaction with the input element.
33436 <example name="date-input-directive" module="dateInputExample">
33437 <file name="index.html">
33439 angular.module('dateInputExample', [])
33440 .controller('DateController', ['$scope', function($scope) {
33442 value: new Date(2013, 9, 22)
33446 <form name="myForm" ng-controller="DateController as dateCtrl">
33447 <label for="exampleInput">Pick a date in 2013:</label>
33448 <input type="date" id="exampleInput" name="input" ng-model="example.value"
33449 placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
33451 <span class="error" ng-show="myForm.input.$error.required">
33453 <span class="error" ng-show="myForm.input.$error.date">
33454 Not a valid date!</span>
33456 <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
33457 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
33458 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
33459 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
33460 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
33463 <file name="protractor.js" type="protractor">
33464 var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
33465 var valid = element(by.binding('myForm.input.$valid'));
33467 // currently protractor/webdriver does not support
33468 // sending keys to all known HTML5 input controls
33469 // for various browsers (see https://github.com/angular/protractor/issues/562).
33470 function setInput(val) {
33471 // set the value of the element and force validation.
33472 var scr = "var ipt = document.getElementById('exampleInput'); " +
33473 "ipt.value = '" + val + "';" +
33474 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
33475 browser.executeScript(scr);
33478 it('should initialize to model', function() {
33479 expect(value.getText()).toContain('2013-10-22');
33480 expect(valid.getText()).toContain('myForm.input.$valid = true');
33483 it('should be invalid if empty', function() {
33485 expect(value.getText()).toEqual('value =');
33486 expect(valid.getText()).toContain('myForm.input.$valid = false');
33489 it('should be invalid if over max', function() {
33490 setInput('2015-01-01');
33491 expect(value.getText()).toContain('');
33492 expect(valid.getText()).toContain('myForm.input.$valid = false');
33497 'date': createDateInputType('date', DATE_REGEXP,
33498 createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
33503 * @name input[datetime-local]
33506 * Input with datetime validation and transformation. In browsers that do not yet support
33507 * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
33508 * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
33510 * The model must always be a Date object, otherwise Angular will throw an error.
33511 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
33513 * The timezone to be used to read/write the `Date` instance in the model can be defined using
33514 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
33516 * @param {string} ngModel Assignable angular expression to data-bind to.
33517 * @param {string=} name Property name of the form under which the control is published.
33518 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
33519 * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
33520 * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
33521 * Note that `min` will also add native HTML5 constraint validation.
33522 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
33523 * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
33524 * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
33525 * Note that `max` will also add native HTML5 constraint validation.
33526 * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
33527 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
33528 * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
33529 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
33530 * @param {string=} required Sets `required` validation error key if the value is not entered.
33531 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
33532 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
33533 * `required` when you want to data-bind to the `required` attribute.
33534 * @param {string=} ngChange Angular expression to be executed when input changes due to user
33535 * interaction with the input element.
33538 <example name="datetimelocal-input-directive" module="dateExample">
33539 <file name="index.html">
33541 angular.module('dateExample', [])
33542 .controller('DateController', ['$scope', function($scope) {
33544 value: new Date(2010, 11, 28, 14, 57)
33548 <form name="myForm" ng-controller="DateController as dateCtrl">
33549 <label for="exampleInput">Pick a date between in 2013:</label>
33550 <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
33551 placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
33553 <span class="error" ng-show="myForm.input.$error.required">
33555 <span class="error" ng-show="myForm.input.$error.datetimelocal">
33556 Not a valid date!</span>
33558 <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
33559 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
33560 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
33561 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
33562 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
33565 <file name="protractor.js" type="protractor">
33566 var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
33567 var valid = element(by.binding('myForm.input.$valid'));
33569 // currently protractor/webdriver does not support
33570 // sending keys to all known HTML5 input controls
33571 // for various browsers (https://github.com/angular/protractor/issues/562).
33572 function setInput(val) {
33573 // set the value of the element and force validation.
33574 var scr = "var ipt = document.getElementById('exampleInput'); " +
33575 "ipt.value = '" + val + "';" +
33576 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
33577 browser.executeScript(scr);
33580 it('should initialize to model', function() {
33581 expect(value.getText()).toContain('2010-12-28T14:57:00');
33582 expect(valid.getText()).toContain('myForm.input.$valid = true');
33585 it('should be invalid if empty', function() {
33587 expect(value.getText()).toEqual('value =');
33588 expect(valid.getText()).toContain('myForm.input.$valid = false');
33591 it('should be invalid if over max', function() {
33592 setInput('2015-01-01T23:59:00');
33593 expect(value.getText()).toContain('');
33594 expect(valid.getText()).toContain('myForm.input.$valid = false');
33599 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
33600 createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
33601 'yyyy-MM-ddTHH:mm:ss.sss'),
33605 * @name input[time]
33608 * Input with time validation and transformation. In browsers that do not yet support
33609 * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
33610 * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
33611 * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
33613 * The model must always be a Date object, otherwise Angular will throw an error.
33614 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
33616 * The timezone to be used to read/write the `Date` instance in the model can be defined using
33617 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
33619 * @param {string} ngModel Assignable angular expression to data-bind to.
33620 * @param {string=} name Property name of the form under which the control is published.
33621 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
33622 * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
33623 * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
33624 * native HTML5 constraint validation.
33625 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
33626 * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
33627 * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
33628 * native HTML5 constraint validation.
33629 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
33630 * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
33631 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
33632 * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
33633 * @param {string=} required Sets `required` validation error key if the value is not entered.
33634 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
33635 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
33636 * `required` when you want to data-bind to the `required` attribute.
33637 * @param {string=} ngChange Angular expression to be executed when input changes due to user
33638 * interaction with the input element.
33641 <example name="time-input-directive" module="timeExample">
33642 <file name="index.html">
33644 angular.module('timeExample', [])
33645 .controller('DateController', ['$scope', function($scope) {
33647 value: new Date(1970, 0, 1, 14, 57, 0)
33651 <form name="myForm" ng-controller="DateController as dateCtrl">
33652 <label for="exampleInput">Pick a time between 8am and 5pm:</label>
33653 <input type="time" id="exampleInput" name="input" ng-model="example.value"
33654 placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
33656 <span class="error" ng-show="myForm.input.$error.required">
33658 <span class="error" ng-show="myForm.input.$error.time">
33659 Not a valid date!</span>
33661 <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
33662 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
33663 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
33664 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
33665 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
33668 <file name="protractor.js" type="protractor">
33669 var value = element(by.binding('example.value | date: "HH:mm:ss"'));
33670 var valid = element(by.binding('myForm.input.$valid'));
33672 // currently protractor/webdriver does not support
33673 // sending keys to all known HTML5 input controls
33674 // for various browsers (https://github.com/angular/protractor/issues/562).
33675 function setInput(val) {
33676 // set the value of the element and force validation.
33677 var scr = "var ipt = document.getElementById('exampleInput'); " +
33678 "ipt.value = '" + val + "';" +
33679 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
33680 browser.executeScript(scr);
33683 it('should initialize to model', function() {
33684 expect(value.getText()).toContain('14:57:00');
33685 expect(valid.getText()).toContain('myForm.input.$valid = true');
33688 it('should be invalid if empty', function() {
33690 expect(value.getText()).toEqual('value =');
33691 expect(valid.getText()).toContain('myForm.input.$valid = false');
33694 it('should be invalid if over max', function() {
33695 setInput('23:59:00');
33696 expect(value.getText()).toContain('');
33697 expect(valid.getText()).toContain('myForm.input.$valid = false');
33702 'time': createDateInputType('time', TIME_REGEXP,
33703 createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
33708 * @name input[week]
33711 * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
33712 * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
33713 * week format (yyyy-W##), for example: `2013-W02`.
33715 * The model must always be a Date object, otherwise Angular will throw an error.
33716 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
33718 * The timezone to be used to read/write the `Date` instance in the model can be defined using
33719 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
33721 * @param {string} ngModel Assignable angular expression to data-bind to.
33722 * @param {string=} name Property name of the form under which the control is published.
33723 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
33724 * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
33725 * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
33726 * native HTML5 constraint validation.
33727 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
33728 * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
33729 * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
33730 * native HTML5 constraint validation.
33731 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
33732 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
33733 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
33734 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
33735 * @param {string=} required Sets `required` validation error key if the value is not entered.
33736 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
33737 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
33738 * `required` when you want to data-bind to the `required` attribute.
33739 * @param {string=} ngChange Angular expression to be executed when input changes due to user
33740 * interaction with the input element.
33743 <example name="week-input-directive" module="weekExample">
33744 <file name="index.html">
33746 angular.module('weekExample', [])
33747 .controller('DateController', ['$scope', function($scope) {
33749 value: new Date(2013, 0, 3)
33753 <form name="myForm" ng-controller="DateController as dateCtrl">
33754 <label>Pick a date between in 2013:
33755 <input id="exampleInput" type="week" name="input" ng-model="example.value"
33756 placeholder="YYYY-W##" min="2012-W32"
33757 max="2013-W52" required />
33760 <span class="error" ng-show="myForm.input.$error.required">
33762 <span class="error" ng-show="myForm.input.$error.week">
33763 Not a valid date!</span>
33765 <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
33766 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
33767 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
33768 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
33769 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
33772 <file name="protractor.js" type="protractor">
33773 var value = element(by.binding('example.value | date: "yyyy-Www"'));
33774 var valid = element(by.binding('myForm.input.$valid'));
33776 // currently protractor/webdriver does not support
33777 // sending keys to all known HTML5 input controls
33778 // for various browsers (https://github.com/angular/protractor/issues/562).
33779 function setInput(val) {
33780 // set the value of the element and force validation.
33781 var scr = "var ipt = document.getElementById('exampleInput'); " +
33782 "ipt.value = '" + val + "';" +
33783 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
33784 browser.executeScript(scr);
33787 it('should initialize to model', function() {
33788 expect(value.getText()).toContain('2013-W01');
33789 expect(valid.getText()).toContain('myForm.input.$valid = true');
33792 it('should be invalid if empty', function() {
33794 expect(value.getText()).toEqual('value =');
33795 expect(valid.getText()).toContain('myForm.input.$valid = false');
33798 it('should be invalid if over max', function() {
33799 setInput('2015-W01');
33800 expect(value.getText()).toContain('');
33801 expect(valid.getText()).toContain('myForm.input.$valid = false');
33806 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
33810 * @name input[month]
33813 * Input with month validation and transformation. In browsers that do not yet support
33814 * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
33815 * month format (yyyy-MM), for example: `2009-01`.
33817 * The model must always be a Date object, otherwise Angular will throw an error.
33818 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
33819 * If the model is not set to the first of the month, the next view to model update will set it
33820 * to the first of the month.
33822 * The timezone to be used to read/write the `Date` instance in the model can be defined using
33823 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
33825 * @param {string} ngModel Assignable angular expression to data-bind to.
33826 * @param {string=} name Property name of the form under which the control is published.
33827 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
33828 * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
33829 * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
33830 * native HTML5 constraint validation.
33831 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
33832 * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
33833 * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
33834 * native HTML5 constraint validation.
33835 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
33836 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
33837 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
33838 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
33840 * @param {string=} required Sets `required` validation error key if the value is not entered.
33841 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
33842 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
33843 * `required` when you want to data-bind to the `required` attribute.
33844 * @param {string=} ngChange Angular expression to be executed when input changes due to user
33845 * interaction with the input element.
33848 <example name="month-input-directive" module="monthExample">
33849 <file name="index.html">
33851 angular.module('monthExample', [])
33852 .controller('DateController', ['$scope', function($scope) {
33854 value: new Date(2013, 9, 1)
33858 <form name="myForm" ng-controller="DateController as dateCtrl">
33859 <label for="exampleInput">Pick a month in 2013:</label>
33860 <input id="exampleInput" type="month" name="input" ng-model="example.value"
33861 placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
33863 <span class="error" ng-show="myForm.input.$error.required">
33865 <span class="error" ng-show="myForm.input.$error.month">
33866 Not a valid month!</span>
33868 <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
33869 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
33870 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
33871 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
33872 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
33875 <file name="protractor.js" type="protractor">
33876 var value = element(by.binding('example.value | date: "yyyy-MM"'));
33877 var valid = element(by.binding('myForm.input.$valid'));
33879 // currently protractor/webdriver does not support
33880 // sending keys to all known HTML5 input controls
33881 // for various browsers (https://github.com/angular/protractor/issues/562).
33882 function setInput(val) {
33883 // set the value of the element and force validation.
33884 var scr = "var ipt = document.getElementById('exampleInput'); " +
33885 "ipt.value = '" + val + "';" +
33886 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
33887 browser.executeScript(scr);
33890 it('should initialize to model', function() {
33891 expect(value.getText()).toContain('2013-10');
33892 expect(valid.getText()).toContain('myForm.input.$valid = true');
33895 it('should be invalid if empty', function() {
33897 expect(value.getText()).toEqual('value =');
33898 expect(valid.getText()).toContain('myForm.input.$valid = false');
33901 it('should be invalid if over max', function() {
33902 setInput('2015-01');
33903 expect(value.getText()).toContain('');
33904 expect(valid.getText()).toContain('myForm.input.$valid = false');
33909 'month': createDateInputType('month', MONTH_REGEXP,
33910 createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
33915 * @name input[number]
33918 * Text input with number validation and transformation. Sets the `number` validation
33919 * error if not a valid number.
33921 * <div class="alert alert-warning">
33922 * The model must always be of type `number` otherwise Angular will throw an error.
33923 * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
33924 * error docs for more information and an example of how to convert your model if necessary.
33927 * ## Issues with HTML5 constraint validation
33929 * In browsers that follow the
33930 * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
33931 * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
33932 * If a non-number is entered in the input, the browser will report the value as an empty string,
33933 * which means the view / model values in `ngModel` and subsequently the scope value
33934 * will also be an empty string.
33937 * @param {string} ngModel Assignable angular expression to data-bind to.
33938 * @param {string=} name Property name of the form under which the control is published.
33939 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
33940 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
33941 * @param {string=} required Sets `required` validation error key if the value is not entered.
33942 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
33943 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
33944 * `required` when you want to data-bind to the `required` attribute.
33945 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
33947 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
33948 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
33950 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
33951 * that contains the regular expression body that will be converted to a regular expression
33952 * as in the ngPattern directive.
33953 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
33954 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
33955 * If the expression evaluates to a RegExp object, then this is used directly.
33956 * If the expression evaluates to a string, then it will be converted to a RegExp
33957 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
33958 * `new RegExp('^abc$')`.<br />
33959 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
33960 * start at the index of the last search's match, thus not taking the whole input value into
33962 * @param {string=} ngChange Angular expression to be executed when input changes due to user
33963 * interaction with the input element.
33966 <example name="number-input-directive" module="numberExample">
33967 <file name="index.html">
33969 angular.module('numberExample', [])
33970 .controller('ExampleController', ['$scope', function($scope) {
33976 <form name="myForm" ng-controller="ExampleController">
33978 <input type="number" name="input" ng-model="example.value"
33979 min="0" max="99" required>
33982 <span class="error" ng-show="myForm.input.$error.required">
33984 <span class="error" ng-show="myForm.input.$error.number">
33985 Not valid number!</span>
33987 <tt>value = {{example.value}}</tt><br/>
33988 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
33989 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
33990 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
33991 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
33994 <file name="protractor.js" type="protractor">
33995 var value = element(by.binding('example.value'));
33996 var valid = element(by.binding('myForm.input.$valid'));
33997 var input = element(by.model('example.value'));
33999 it('should initialize to model', function() {
34000 expect(value.getText()).toContain('12');
34001 expect(valid.getText()).toContain('true');
34004 it('should be invalid if empty', function() {
34006 input.sendKeys('');
34007 expect(value.getText()).toEqual('value =');
34008 expect(valid.getText()).toContain('false');
34011 it('should be invalid if over max', function() {
34013 input.sendKeys('123');
34014 expect(value.getText()).toEqual('value =');
34015 expect(valid.getText()).toContain('false');
34020 'number': numberInputType,
34028 * Text input with URL validation. Sets the `url` validation error key if the content is not a
34031 * <div class="alert alert-warning">
34032 * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
34033 * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
34034 * the built-in validators (see the {@link guide/forms Forms guide})
34037 * @param {string} ngModel Assignable angular expression to data-bind to.
34038 * @param {string=} name Property name of the form under which the control is published.
34039 * @param {string=} required Sets `required` validation error key if the value is not entered.
34040 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
34041 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
34042 * `required` when you want to data-bind to the `required` attribute.
34043 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
34045 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
34046 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
34048 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
34049 * that contains the regular expression body that will be converted to a regular expression
34050 * as in the ngPattern directive.
34051 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
34052 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
34053 * If the expression evaluates to a RegExp object, then this is used directly.
34054 * If the expression evaluates to a string, then it will be converted to a RegExp
34055 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
34056 * `new RegExp('^abc$')`.<br />
34057 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
34058 * start at the index of the last search's match, thus not taking the whole input value into
34060 * @param {string=} ngChange Angular expression to be executed when input changes due to user
34061 * interaction with the input element.
34064 <example name="url-input-directive" module="urlExample">
34065 <file name="index.html">
34067 angular.module('urlExample', [])
34068 .controller('ExampleController', ['$scope', function($scope) {
34070 text: 'http://google.com'
34074 <form name="myForm" ng-controller="ExampleController">
34076 <input type="url" name="input" ng-model="url.text" required>
34079 <span class="error" ng-show="myForm.input.$error.required">
34081 <span class="error" ng-show="myForm.input.$error.url">
34082 Not valid url!</span>
34084 <tt>text = {{url.text}}</tt><br/>
34085 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
34086 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
34087 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
34088 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
34089 <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
34092 <file name="protractor.js" type="protractor">
34093 var text = element(by.binding('url.text'));
34094 var valid = element(by.binding('myForm.input.$valid'));
34095 var input = element(by.model('url.text'));
34097 it('should initialize to model', function() {
34098 expect(text.getText()).toContain('http://google.com');
34099 expect(valid.getText()).toContain('true');
34102 it('should be invalid if empty', function() {
34104 input.sendKeys('');
34106 expect(text.getText()).toEqual('text =');
34107 expect(valid.getText()).toContain('false');
34110 it('should be invalid if not url', function() {
34112 input.sendKeys('box');
34114 expect(valid.getText()).toContain('false');
34119 'url': urlInputType,
34124 * @name input[email]
34127 * Text input with email validation. Sets the `email` validation error key if not a valid email
34130 * <div class="alert alert-warning">
34131 * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
34132 * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
34133 * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
34136 * @param {string} ngModel Assignable angular expression to data-bind to.
34137 * @param {string=} name Property name of the form under which the control is published.
34138 * @param {string=} required Sets `required` validation error key if the value is not entered.
34139 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
34140 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
34141 * `required` when you want to data-bind to the `required` attribute.
34142 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
34144 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
34145 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
34147 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
34148 * that contains the regular expression body that will be converted to a regular expression
34149 * as in the ngPattern directive.
34150 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
34151 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
34152 * If the expression evaluates to a RegExp object, then this is used directly.
34153 * If the expression evaluates to a string, then it will be converted to a RegExp
34154 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
34155 * `new RegExp('^abc$')`.<br />
34156 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
34157 * start at the index of the last search's match, thus not taking the whole input value into
34159 * @param {string=} ngChange Angular expression to be executed when input changes due to user
34160 * interaction with the input element.
34163 <example name="email-input-directive" module="emailExample">
34164 <file name="index.html">
34166 angular.module('emailExample', [])
34167 .controller('ExampleController', ['$scope', function($scope) {
34169 text: 'me@example.com'
34173 <form name="myForm" ng-controller="ExampleController">
34175 <input type="email" name="input" ng-model="email.text" required>
34178 <span class="error" ng-show="myForm.input.$error.required">
34180 <span class="error" ng-show="myForm.input.$error.email">
34181 Not valid email!</span>
34183 <tt>text = {{email.text}}</tt><br/>
34184 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
34185 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
34186 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
34187 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
34188 <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
34191 <file name="protractor.js" type="protractor">
34192 var text = element(by.binding('email.text'));
34193 var valid = element(by.binding('myForm.input.$valid'));
34194 var input = element(by.model('email.text'));
34196 it('should initialize to model', function() {
34197 expect(text.getText()).toContain('me@example.com');
34198 expect(valid.getText()).toContain('true');
34201 it('should be invalid if empty', function() {
34203 input.sendKeys('');
34204 expect(text.getText()).toEqual('text =');
34205 expect(valid.getText()).toContain('false');
34208 it('should be invalid if not email', function() {
34210 input.sendKeys('xxx');
34212 expect(valid.getText()).toContain('false');
34217 'email': emailInputType,
34222 * @name input[radio]
34225 * HTML radio button.
34227 * @param {string} ngModel Assignable angular expression to data-bind to.
34228 * @param {string} value The value to which the `ngModel` expression should be set when selected.
34229 * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
34230 * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
34231 * @param {string=} name Property name of the form under which the control is published.
34232 * @param {string=} ngChange Angular expression to be executed when input changes due to user
34233 * interaction with the input element.
34234 * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
34235 * is selected. Should be used instead of the `value` attribute if you need
34236 * a non-string `ngModel` (`boolean`, `array`, ...).
34239 <example name="radio-input-directive" module="radioExample">
34240 <file name="index.html">
34242 angular.module('radioExample', [])
34243 .controller('ExampleController', ['$scope', function($scope) {
34247 $scope.specialValue = {
34253 <form name="myForm" ng-controller="ExampleController">
34255 <input type="radio" ng-model="color.name" value="red">
34259 <input type="radio" ng-model="color.name" ng-value="specialValue">
34263 <input type="radio" ng-model="color.name" value="blue">
34266 <tt>color = {{color.name | json}}</tt><br/>
34268 Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
34270 <file name="protractor.js" type="protractor">
34271 it('should change state', function() {
34272 var inputs = element.all(by.model('color.name'));
34273 var color = element(by.binding('color.name'));
34275 expect(color.getText()).toContain('blue');
34277 inputs.get(0).click();
34278 expect(color.getText()).toContain('red');
34280 inputs.get(1).click();
34281 expect(color.getText()).toContain('green');
34286 'radio': radioInputType,
34290 * @name input[range]
34293 * Native range input with validation and transformation.
34295 * <div class="alert alert-warning">
34297 * In v1.5.9+, in order to avoid interfering with already existing, custom directives for
34298 * `input[range]`, you need to let Angular know that you want to enable its built-in support.
34299 * You can do this by adding the `ng-input-range` attribute to the input element. E.g.:
34300 * `<input type="range" ng-input-range ... />`
34303 * Input elements without the `ng-input-range` attibute will continue to be treated the same
34304 * as in previous versions (e.g. their model value will be a string not a number and Angular
34305 * will not take `min`/`max`/`step` attributes and properties into account).
34308 * **Note:** From v1.6.x onwards, the support for `input[range]` will be always enabled and
34309 * the `ng-input-range` attribute will have no effect.
34312 * This documentation page refers to elements which have the built-in support enabled; i.e.
34313 * elements _with_ the `ng-input-range` attribute.
34317 * The model for the range input must always be a `Number`.
34319 * IE9 and other browsers that do not support the `range` type fall back
34320 * to a text input without any default values for `min`, `max` and `step`. Model binding,
34321 * validation and number parsing are nevertheless supported.
34323 * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`
34324 * in a way that never allows the input to hold an invalid value. That means:
34325 * - any non-numerical value is set to `(max + min) / 2`.
34326 * - any numerical value that is less than the current min val, or greater than the current max val
34327 * is set to the min / max val respectively.
34328 * - additionally, the current `step` is respected, so the nearest value that satisfies a step
34331 * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))
34334 * This has the following consequences for Angular:
34336 * Since the element value should always reflect the current model value, a range input
34337 * will set the bound ngModel expression to the value that the browser has set for the
34338 * input element. For example, in the following input `<input type="range" ng-input-range ng-model="model.value">`,
34339 * if the application sets `model.value = null`, the browser will set the input to `'50'`.
34340 * Angular will then set the model to `50`, to prevent input and model value being out of sync.
34342 * That means the model for range will immediately be set to `50` after `ngModel` has been
34343 * initialized. It also means a range input can never have the required error.
34345 * This does not only affect changes to the model value, but also to the values of the `min`,
34346 * `max`, and `step` attributes. When these change in a way that will cause the browser to modify
34347 * the input value, Angular will also update the model value.
34349 * Automatic value adjustment also means that a range input element can never have the `required`,
34350 * `min`, or `max` errors.
34352 * However, `step` is currently only fully implemented by Firefox. Other browsers have problems
34353 * when the step value changes dynamically - they do not adjust the element value correctly, but
34354 * instead may set the `stepMismatch` error. If that's the case, the Angular will set the `step`
34355 * error on the input, and set the model to `undefined`.
34357 * Note that `input[range]` is not compatible with `ngMax`, `ngMin`, and `ngStep`, because they do
34358 * not set the `min` and `max` attributes, which means that the browser won't automatically adjust
34359 * the input value based on their values, and will always assume min = 0, max = 100, and step = 1.
34361 * @param ngInputRange The presense of this attribute enables the built-in support for
34363 * @param {string} ngModel Assignable angular expression to data-bind to.
34364 * @param {string=} name Property name of the form under which the control is published.
34365 * @param {string=} min Sets the `min` validation to ensure that the value entered is greater
34366 * than `min`. Can be interpolated.
34367 * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.
34368 * Can be interpolated.
34369 * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`
34370 * Can be interpolated.
34371 * @param {string=} ngChange Angular expression to be executed when the ngModel value changes due
34372 * to user interaction with the input element.
34373 * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the
34374 * element. **Note** : `ngChecked` should not be used alongside `ngModel`.
34375 * Checkout {@link ng.directive:ngChecked ngChecked} for usage.
34378 <example name="range-input-directive" module="rangeExample">
34379 <file name="index.html">
34381 angular.module('rangeExample', [])
34382 .controller('ExampleController', ['$scope', function($scope) {
34388 <form name="myForm" ng-controller="ExampleController">
34390 Model as range: <input type="range" ng-input-range name="range" ng-model="value" min="{{min}}" max="{{max}}">
34392 Model as number: <input type="number" ng-model="value"><br>
34393 Min: <input type="number" ng-model="min"><br>
34394 Max: <input type="number" ng-model="max"><br>
34395 value = <code>{{value}}</code><br/>
34396 myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
34397 myForm.range.$error = <code>{{myForm.range.$error}}</code>
34402 * ## Range Input with ngMin & ngMax attributes
34405 <example name="range-input-directive-ng" module="rangeExample">
34406 <file name="index.html">
34408 angular.module('rangeExample', [])
34409 .controller('ExampleController', ['$scope', function($scope) {
34415 <form name="myForm" ng-controller="ExampleController">
34416 Model as range: <input type="range" ng-input-range name="range" ng-model="value" ng-min="min" ng-max="max">
34418 Model as number: <input type="number" ng-model="value"><br>
34419 Min: <input type="number" ng-model="min"><br>
34420 Max: <input type="number" ng-model="max"><br>
34421 value = <code>{{value}}</code><br/>
34422 myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
34423 myForm.range.$error = <code>{{myForm.range.$error}}</code>
34429 'range': rangeInputType,
34433 * @name input[checkbox]
34438 * @param {string} ngModel Assignable angular expression to data-bind to.
34439 * @param {string=} name Property name of the form under which the control is published.
34440 * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
34441 * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
34442 * @param {string=} ngChange Angular expression to be executed when input changes due to user
34443 * interaction with the input element.
34446 <example name="checkbox-input-directive" module="checkboxExample">
34447 <file name="index.html">
34449 angular.module('checkboxExample', [])
34450 .controller('ExampleController', ['$scope', function($scope) {
34451 $scope.checkboxModel = {
34457 <form name="myForm" ng-controller="ExampleController">
34459 <input type="checkbox" ng-model="checkboxModel.value1">
34462 <input type="checkbox" ng-model="checkboxModel.value2"
34463 ng-true-value="'YES'" ng-false-value="'NO'">
34465 <tt>value1 = {{checkboxModel.value1}}</tt><br/>
34466 <tt>value2 = {{checkboxModel.value2}}</tt><br/>
34469 <file name="protractor.js" type="protractor">
34470 it('should change state', function() {
34471 var value1 = element(by.binding('checkboxModel.value1'));
34472 var value2 = element(by.binding('checkboxModel.value2'));
34474 expect(value1.getText()).toContain('true');
34475 expect(value2.getText()).toContain('YES');
34477 element(by.model('checkboxModel.value1')).click();
34478 element(by.model('checkboxModel.value2')).click();
34480 expect(value1.getText()).toContain('false');
34481 expect(value2.getText()).toContain('NO');
34486 'checkbox': checkboxInputType,
34495 function stringBasedInputType(ctrl) {
34496 ctrl.$formatters.push(function(value) {
34497 return ctrl.$isEmpty(value) ? value : value.toString();
34501 function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
34502 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
34503 stringBasedInputType(ctrl);
34506 function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
34507 var type = lowercase(element[0].type);
34509 // In composition mode, users are still inputting intermediate text buffer,
34510 // hold the listener until composition is done.
34511 // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
34512 if (!$sniffer.android) {
34513 var composing = false;
34515 element.on('compositionstart', function() {
34519 element.on('compositionend', function() {
34527 var listener = function(ev) {
34529 $browser.defer.cancel(timeout);
34532 if (composing) return;
34533 var value = element.val(),
34534 event = ev && ev.type;
34536 // By default we will trim the value
34537 // If the attribute ng-trim exists we will avoid trimming
34538 // If input type is 'password', the value is never trimmed
34539 if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
34540 value = trim(value);
34543 // If a control is suffering from bad input (due to native validators), browsers discard its
34544 // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
34545 // control's value is the same empty value twice in a row.
34546 if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
34547 ctrl.$setViewValue(value, event);
34551 // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
34552 // input event on backspace, delete or cut
34553 if ($sniffer.hasEvent('input')) {
34554 element.on('input', listener);
34556 var deferListener = function(ev, input, origValue) {
34558 timeout = $browser.defer(function() {
34560 if (!input || input.value !== origValue) {
34567 element.on('keydown', /** @this */ function(event) {
34568 var key = event.keyCode;
34571 // command modifiers arrows
34572 if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
34574 deferListener(event, this, this.value);
34577 // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
34578 if ($sniffer.hasEvent('paste')) {
34579 element.on('paste cut', deferListener);
34583 // if user paste into input using mouse on older browser
34584 // or form autocomplete on newer browser, we need "change" event to catch it
34585 element.on('change', listener);
34587 // Some native input types (date-family) have the ability to change validity without
34588 // firing any input/change events.
34589 // For these event types, when native validators are present and the browser supports the type,
34590 // check for validity changes on various DOM events.
34591 if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
34592 element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {
34594 var validity = this[VALIDITY_STATE_PROPERTY];
34595 var origBadInput = validity.badInput;
34596 var origTypeMismatch = validity.typeMismatch;
34597 timeout = $browser.defer(function() {
34599 if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
34607 ctrl.$render = function() {
34608 // Workaround for Firefox validation #12102.
34609 var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
34610 if (element.val() !== value) {
34611 element.val(value);
34616 function weekParser(isoWeek, existingDate) {
34617 if (isDate(isoWeek)) {
34621 if (isString(isoWeek)) {
34622 WEEK_REGEXP.lastIndex = 0;
34623 var parts = WEEK_REGEXP.exec(isoWeek);
34625 var year = +parts[1],
34631 firstThurs = getFirstThursdayOfYear(year),
34632 addDays = (week - 1) * 7;
34634 if (existingDate) {
34635 hours = existingDate.getHours();
34636 minutes = existingDate.getMinutes();
34637 seconds = existingDate.getSeconds();
34638 milliseconds = existingDate.getMilliseconds();
34641 return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
34648 function createDateParser(regexp, mapping) {
34649 return function(iso, date) {
34656 if (isString(iso)) {
34657 // When a date is JSON'ified to wraps itself inside of an extra
34658 // set of double quotes. This makes the date parsing code unable
34659 // to match the date string and parse it as a date.
34660 if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') {
34661 iso = iso.substring(1, iso.length - 1);
34663 if (ISO_DATE_REGEXP.test(iso)) {
34664 return new Date(iso);
34666 regexp.lastIndex = 0;
34667 parts = regexp.exec(iso);
34673 yyyy: date.getFullYear(),
34674 MM: date.getMonth() + 1,
34675 dd: date.getDate(),
34676 HH: date.getHours(),
34677 mm: date.getMinutes(),
34678 ss: date.getSeconds(),
34679 sss: date.getMilliseconds() / 1000
34682 map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
34685 forEach(parts, function(part, index) {
34686 if (index < mapping.length) {
34687 map[mapping[index]] = +part;
34690 return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
34698 function createDateInputType(type, regexp, parseDate, format) {
34699 return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
34700 badInputChecker(scope, element, attr, ctrl);
34701 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
34702 var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
34705 ctrl.$$parserName = type;
34706 ctrl.$parsers.push(function(value) {
34707 if (ctrl.$isEmpty(value)) return null;
34708 if (regexp.test(value)) {
34709 // Note: We cannot read ctrl.$modelValue, as there might be a different
34710 // parser/formatter in the processing chain so that the model
34711 // contains some different data format!
34712 var parsedDate = parseDate(value, previousDate);
34714 parsedDate = convertTimezoneToLocal(parsedDate, timezone);
34721 ctrl.$formatters.push(function(value) {
34722 if (value && !isDate(value)) {
34723 throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
34725 if (isValidDate(value)) {
34726 previousDate = value;
34727 if (previousDate && timezone) {
34728 previousDate = convertTimezoneToLocal(previousDate, timezone, true);
34730 return $filter('date')(value, format, timezone);
34732 previousDate = null;
34737 if (isDefined(attr.min) || attr.ngMin) {
34739 ctrl.$validators.min = function(value) {
34740 return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
34742 attr.$observe('min', function(val) {
34743 minVal = parseObservedDateValue(val);
34748 if (isDefined(attr.max) || attr.ngMax) {
34750 ctrl.$validators.max = function(value) {
34751 return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
34753 attr.$observe('max', function(val) {
34754 maxVal = parseObservedDateValue(val);
34759 function isValidDate(value) {
34760 // Invalid Date: getTime() returns NaN
34761 return value && !(value.getTime && value.getTime() !== value.getTime());
34764 function parseObservedDateValue(val) {
34765 return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
34770 function badInputChecker(scope, element, attr, ctrl) {
34771 var node = element[0];
34772 var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
34773 if (nativeValidation) {
34774 ctrl.$parsers.push(function(value) {
34775 var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
34776 return validity.badInput || validity.typeMismatch ? undefined : value;
34781 function numberFormatterParser(ctrl) {
34782 ctrl.$$parserName = 'number';
34783 ctrl.$parsers.push(function(value) {
34784 if (ctrl.$isEmpty(value)) return null;
34785 if (NUMBER_REGEXP.test(value)) return parseFloat(value);
34789 ctrl.$formatters.push(function(value) {
34790 if (!ctrl.$isEmpty(value)) {
34791 if (!isNumber(value)) {
34792 throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
34794 value = value.toString();
34800 function parseNumberAttrVal(val) {
34801 if (isDefined(val) && !isNumber(val)) {
34802 val = parseFloat(val);
34804 return !isNumberNaN(val) ? val : undefined;
34807 function isNumberInteger(num) {
34808 // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066
34809 // (minus the assumption that `num` is a number)
34811 // eslint-disable-next-line no-bitwise
34812 return (num | 0) === num;
34815 function countDecimals(num) {
34816 var numString = num.toString();
34817 var decimalSymbolIndex = numString.indexOf('.');
34819 if (decimalSymbolIndex === -1) {
34820 if (-1 < num && num < 1) {
34821 // It may be in the exponential notation format (`1e-X`)
34822 var match = /e-(\d+)$/.exec(numString);
34825 return Number(match[1]);
34832 return numString.length - decimalSymbolIndex - 1;
34835 function isValidForStep(viewValue, stepBase, step) {
34836 // At this point `stepBase` and `step` are expected to be non-NaN values
34837 // and `viewValue` is expected to be a valid stringified number.
34838 var value = Number(viewValue);
34840 // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or
34841 // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers.
34842 if (!isNumberInteger(value) || !isNumberInteger(stepBase) || !isNumberInteger(step)) {
34843 var decimalCount = Math.max(countDecimals(value), countDecimals(stepBase), countDecimals(step));
34844 var multiplier = Math.pow(10, decimalCount);
34846 value = value * multiplier;
34847 stepBase = stepBase * multiplier;
34848 step = step * multiplier;
34851 return (value - stepBase) % step === 0;
34854 function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
34855 badInputChecker(scope, element, attr, ctrl);
34856 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
34857 numberFormatterParser(ctrl);
34862 if (isDefined(attr.min) || attr.ngMin) {
34863 ctrl.$validators.min = function(value) {
34864 return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
34867 attr.$observe('min', function(val) {
34868 minVal = parseNumberAttrVal(val);
34869 // TODO(matsko): implement validateLater to reduce number of validations
34874 if (isDefined(attr.max) || attr.ngMax) {
34875 ctrl.$validators.max = function(value) {
34876 return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
34879 attr.$observe('max', function(val) {
34880 maxVal = parseNumberAttrVal(val);
34881 // TODO(matsko): implement validateLater to reduce number of validations
34887 function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {
34888 badInputChecker(scope, element, attr, ctrl);
34889 numberFormatterParser(ctrl);
34890 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
34892 var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',
34893 minVal = supportsRange ? 0 : undefined,
34894 maxVal = supportsRange ? 100 : undefined,
34895 stepVal = supportsRange ? 1 : undefined,
34896 validity = element[0].validity,
34897 hasMinAttr = isDefined(attr.min),
34898 hasMaxAttr = isDefined(attr.max),
34899 hasStepAttr = isDefined(attr.step);
34901 var originalRender = ctrl.$render;
34903 ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?
34904 //Browsers that implement range will set these values automatically, but reading the adjusted values after
34905 //$render would cause the min / max validators to be applied with the wrong value
34906 function rangeRender() {
34908 ctrl.$setViewValue(element.val());
34913 ctrl.$validators.min = supportsRange ?
34914 // Since all browsers set the input to a valid value, we don't need to check validity
34915 function noopMinValidator() { return true; } :
34916 // non-support browsers validate the min val
34917 function minValidator(modelValue, viewValue) {
34918 return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;
34921 setInitialValueAndObserver('min', minChange);
34925 ctrl.$validators.max = supportsRange ?
34926 // Since all browsers set the input to a valid value, we don't need to check validity
34927 function noopMaxValidator() { return true; } :
34928 // non-support browsers validate the max val
34929 function maxValidator(modelValue, viewValue) {
34930 return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;
34933 setInitialValueAndObserver('max', maxChange);
34937 ctrl.$validators.step = supportsRange ?
34938 function nativeStepValidator() {
34939 // Currently, only FF implements the spec on step change correctly (i.e. adjusting the
34940 // input element value to a valid value). It's possible that other browsers set the stepMismatch
34941 // validity error instead, so we can at least report an error in that case.
34942 return !validity.stepMismatch;
34944 // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would
34945 function stepValidator(modelValue, viewValue) {
34946 return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
34947 isValidForStep(viewValue, minVal || 0, stepVal);
34950 setInitialValueAndObserver('step', stepChange);
34953 function setInitialValueAndObserver(htmlAttrName, changeFn) {
34954 // interpolated attributes set the attribute value only after a digest, but we need the
34955 // attribute value when the input is first rendered, so that the browser can adjust the
34956 // input value based on the min/max value
34957 element.attr(htmlAttrName, attr[htmlAttrName]);
34958 attr.$observe(htmlAttrName, changeFn);
34961 function minChange(val) {
34962 minVal = parseNumberAttrVal(val);
34963 // ignore changes before model is initialized
34964 if (isNumberNaN(ctrl.$modelValue)) {
34968 if (supportsRange) {
34969 var elVal = element.val();
34970 // IE11 doesn't set the el val correctly if the minVal is greater than the element value
34971 if (minVal > elVal) {
34973 element.val(elVal);
34975 ctrl.$setViewValue(elVal);
34977 // TODO(matsko): implement validateLater to reduce number of validations
34982 function maxChange(val) {
34983 maxVal = parseNumberAttrVal(val);
34984 // ignore changes before model is initialized
34985 if (isNumberNaN(ctrl.$modelValue)) {
34989 if (supportsRange) {
34990 var elVal = element.val();
34991 // IE11 doesn't set the el val correctly if the maxVal is less than the element value
34992 if (maxVal < elVal) {
34993 element.val(maxVal);
34994 // IE11 and Chrome don't set the value to the minVal when max < min
34995 elVal = maxVal < minVal ? minVal : maxVal;
34997 ctrl.$setViewValue(elVal);
34999 // TODO(matsko): implement validateLater to reduce number of validations
35004 function stepChange(val) {
35005 stepVal = parseNumberAttrVal(val);
35006 // ignore changes before model is initialized
35007 if (isNumberNaN(ctrl.$modelValue)) {
35011 // Some browsers don't adjust the input value correctly, but set the stepMismatch error
35012 if (supportsRange && ctrl.$viewValue !== element.val()) {
35013 ctrl.$setViewValue(element.val());
35015 // TODO(matsko): implement validateLater to reduce number of validations
35021 function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
35022 // Note: no badInputChecker here by purpose as `url` is only a validation
35023 // in browsers, i.e. we can always read out input.value even if it is not valid!
35024 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
35025 stringBasedInputType(ctrl);
35027 ctrl.$$parserName = 'url';
35028 ctrl.$validators.url = function(modelValue, viewValue) {
35029 var value = modelValue || viewValue;
35030 return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
35034 function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
35035 // Note: no badInputChecker here by purpose as `url` is only a validation
35036 // in browsers, i.e. we can always read out input.value even if it is not valid!
35037 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
35038 stringBasedInputType(ctrl);
35040 ctrl.$$parserName = 'email';
35041 ctrl.$validators.email = function(modelValue, viewValue) {
35042 var value = modelValue || viewValue;
35043 return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
35047 function radioInputType(scope, element, attr, ctrl) {
35048 // make the name unique, if not defined
35049 if (isUndefined(attr.name)) {
35050 element.attr('name', nextUid());
35053 var listener = function(ev) {
35054 if (element[0].checked) {
35055 ctrl.$setViewValue(attr.value, ev && ev.type);
35059 element.on('click', listener);
35061 ctrl.$render = function() {
35062 var value = attr.value;
35063 // We generally use strict comparison. This is behavior we cannot change without a BC.
35064 // eslint-disable-next-line eqeqeq
35065 element[0].checked = (value == ctrl.$viewValue);
35068 attr.$observe('value', ctrl.$render);
35071 function parseConstantExpr($parse, context, name, expression, fallback) {
35073 if (isDefined(expression)) {
35074 parseFn = $parse(expression);
35075 if (!parseFn.constant) {
35076 throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
35077 '`{1}`.', name, expression);
35079 return parseFn(context);
35084 function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
35085 var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
35086 var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
35088 var listener = function(ev) {
35089 ctrl.$setViewValue(element[0].checked, ev && ev.type);
35092 element.on('click', listener);
35094 ctrl.$render = function() {
35095 element[0].checked = ctrl.$viewValue;
35098 // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
35099 // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
35100 // it to a boolean.
35101 ctrl.$isEmpty = function(value) {
35102 return value === false;
35105 ctrl.$formatters.push(function(value) {
35106 return equals(value, trueValue);
35109 ctrl.$parsers.push(function(value) {
35110 return value ? trueValue : falseValue;
35121 * HTML textarea element control with angular data-binding. The data-binding and validation
35122 * properties of this element are exactly the same as those of the
35123 * {@link ng.directive:input input element}.
35125 * @param {string} ngModel Assignable angular expression to data-bind to.
35126 * @param {string=} name Property name of the form under which the control is published.
35127 * @param {string=} required Sets `required` validation error key if the value is not entered.
35128 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
35129 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
35130 * `required` when you want to data-bind to the `required` attribute.
35131 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
35133 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
35134 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
35136 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
35137 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
35138 * If the expression evaluates to a RegExp object, then this is used directly.
35139 * If the expression evaluates to a string, then it will be converted to a RegExp
35140 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
35141 * `new RegExp('^abc$')`.<br />
35142 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
35143 * start at the index of the last search's match, thus not taking the whole input value into
35145 * @param {string=} ngChange Angular expression to be executed when input changes due to user
35146 * interaction with the input element.
35147 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
35151 * When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily
35152 * insert the placeholder value as the textarea's content. If the placeholder value contains
35153 * interpolation (`{{ ... }}`), an error will be logged in the console when Angular tries to update
35154 * the value of the by-then-removed text node. This doesn't affect the functionality of the
35155 * textarea, but can be undesirable.
35157 * You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of
35158 * `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can
35159 * find more details on `ngAttr` in the
35160 * [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the
35171 * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
35172 * input state control, and validation.
35173 * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
35175 * <div class="alert alert-warning">
35176 * **Note:** Not every feature offered is available for all input types.
35177 * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
35180 * @param {string} ngModel Assignable angular expression to data-bind to.
35181 * @param {string=} name Property name of the form under which the control is published.
35182 * @param {string=} required Sets `required` validation error key if the value is not entered.
35183 * @param {boolean=} ngRequired Sets `required` attribute if set to true
35184 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
35186 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
35187 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
35189 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
35190 * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
35191 * If the expression evaluates to a RegExp object, then this is used directly.
35192 * If the expression evaluates to a string, then it will be converted to a RegExp
35193 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
35194 * `new RegExp('^abc$')`.<br />
35195 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
35196 * start at the index of the last search's match, thus not taking the whole input value into
35198 * @param {string=} ngChange Angular expression to be executed when input changes due to user
35199 * interaction with the input element.
35200 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
35201 * This parameter is ignored for input[type=password] controls, which will never trim the
35205 <example name="input-directive" module="inputExample">
35206 <file name="index.html">
35208 angular.module('inputExample', [])
35209 .controller('ExampleController', ['$scope', function($scope) {
35210 $scope.user = {name: 'guest', last: 'visitor'};
35213 <div ng-controller="ExampleController">
35214 <form name="myForm">
35217 <input type="text" name="userName" ng-model="user.name" required>
35220 <span class="error" ng-show="myForm.userName.$error.required">
35225 <input type="text" name="lastName" ng-model="user.last"
35226 ng-minlength="3" ng-maxlength="10">
35229 <span class="error" ng-show="myForm.lastName.$error.minlength">
35231 <span class="error" ng-show="myForm.lastName.$error.maxlength">
35236 <tt>user = {{user}}</tt><br/>
35237 <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
35238 <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
35239 <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
35240 <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
35241 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
35242 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
35243 <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
35244 <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
35247 <file name="protractor.js" type="protractor">
35248 var user = element(by.exactBinding('user'));
35249 var userNameValid = element(by.binding('myForm.userName.$valid'));
35250 var lastNameValid = element(by.binding('myForm.lastName.$valid'));
35251 var lastNameError = element(by.binding('myForm.lastName.$error'));
35252 var formValid = element(by.binding('myForm.$valid'));
35253 var userNameInput = element(by.model('user.name'));
35254 var userLastInput = element(by.model('user.last'));
35256 it('should initialize to model', function() {
35257 expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
35258 expect(userNameValid.getText()).toContain('true');
35259 expect(formValid.getText()).toContain('true');
35262 it('should be invalid if empty when required', function() {
35263 userNameInput.clear();
35264 userNameInput.sendKeys('');
35266 expect(user.getText()).toContain('{"last":"visitor"}');
35267 expect(userNameValid.getText()).toContain('false');
35268 expect(formValid.getText()).toContain('false');
35271 it('should be valid if empty when min length is set', function() {
35272 userLastInput.clear();
35273 userLastInput.sendKeys('');
35275 expect(user.getText()).toContain('{"name":"guest","last":""}');
35276 expect(lastNameValid.getText()).toContain('true');
35277 expect(formValid.getText()).toContain('true');
35280 it('should be invalid if less than required min length', function() {
35281 userLastInput.clear();
35282 userLastInput.sendKeys('xx');
35284 expect(user.getText()).toContain('{"name":"guest"}');
35285 expect(lastNameValid.getText()).toContain('false');
35286 expect(lastNameError.getText()).toContain('minlength');
35287 expect(formValid.getText()).toContain('false');
35290 it('should be invalid if longer than max length', function() {
35291 userLastInput.clear();
35292 userLastInput.sendKeys('some ridiculously long name');
35294 expect(user.getText()).toContain('{"name":"guest"}');
35295 expect(lastNameValid.getText()).toContain('false');
35296 expect(lastNameError.getText()).toContain('maxlength');
35297 expect(formValid.getText()).toContain('false');
35302 var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
35303 function($browser, $sniffer, $filter, $parse) {
35306 require: ['?ngModel'],
35308 pre: function(scope, element, attr, ctrls) {
35310 var type = lowercase(attr.type);
35311 if ((type === 'range') && !attr.hasOwnProperty('ngInputRange')) {
35314 (inputType[type] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
35315 $browser, $filter, $parse);
35324 var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
35330 * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
35331 * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
35334 * `ngValue` is useful when dynamically generating lists of radio buttons using
35335 * {@link ngRepeat `ngRepeat`}, as shown below.
35337 * Likewise, `ngValue` can be used to generate `<option>` elements for
35338 * the {@link select `select`} element. In that case however, only strings are supported
35339 * for the `value `attribute, so the resulting `ngModel` will always be a string.
35340 * Support for `select` models with non-string values is available via `ngOptions`.
35343 * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
35344 * of the `input` element
35347 <example name="ngValue-directive" module="valueExample">
35348 <file name="index.html">
35350 angular.module('valueExample', [])
35351 .controller('ExampleController', ['$scope', function($scope) {
35352 $scope.names = ['pizza', 'unicorns', 'robots'];
35353 $scope.my = { favorite: 'unicorns' };
35356 <form ng-controller="ExampleController">
35357 <h2>Which is your favorite?</h2>
35358 <label ng-repeat="name in names" for="{{name}}">
35360 <input type="radio"
35361 ng-model="my.favorite"
35366 <div>You chose {{my.favorite}}</div>
35369 <file name="protractor.js" type="protractor">
35370 var favorite = element(by.binding('my.favorite'));
35372 it('should initialize to model', function() {
35373 expect(favorite.getText()).toContain('unicorns');
35375 it('should bind the values to the inputs', function() {
35376 element.all(by.model('my.favorite')).get(0).click();
35377 expect(favorite.getText()).toContain('pizza');
35382 var ngValueDirective = function() {
35386 compile: function(tpl, tplAttr) {
35387 if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
35388 return function ngValueConstantLink(scope, elm, attr) {
35389 attr.$set('value', scope.$eval(attr.ngValue));
35392 return function ngValueLink(scope, elm, attr) {
35393 scope.$watch(attr.ngValue, function valueWatchAction(value) {
35394 attr.$set('value', value);
35408 * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
35409 * with the value of a given expression, and to update the text content when the value of that
35410 * expression changes.
35412 * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
35413 * `{{ expression }}` which is similar but less verbose.
35415 * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
35416 * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
35417 * element attribute, it makes the bindings invisible to the user while the page is loading.
35419 * An alternative solution to this problem would be using the
35420 * {@link ng.directive:ngCloak ngCloak} directive.
35424 * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
35427 * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
35428 <example module="bindExample" name="ng-bind">
35429 <file name="index.html">
35431 angular.module('bindExample', [])
35432 .controller('ExampleController', ['$scope', function($scope) {
35433 $scope.name = 'Whirled';
35436 <div ng-controller="ExampleController">
35437 <label>Enter name: <input type="text" ng-model="name"></label><br>
35438 Hello <span ng-bind="name"></span>!
35441 <file name="protractor.js" type="protractor">
35442 it('should check ng-bind', function() {
35443 var nameInput = element(by.model('name'));
35445 expect(element(by.binding('name')).getText()).toBe('Whirled');
35447 nameInput.sendKeys('world');
35448 expect(element(by.binding('name')).getText()).toBe('world');
35453 var ngBindDirective = ['$compile', function($compile) {
35456 compile: function ngBindCompile(templateElement) {
35457 $compile.$$addBindingClass(templateElement);
35458 return function ngBindLink(scope, element, attr) {
35459 $compile.$$addBindingInfo(element, attr.ngBind);
35460 element = element[0];
35461 scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
35462 element.textContent = isUndefined(value) ? '' : value;
35472 * @name ngBindTemplate
35475 * The `ngBindTemplate` directive specifies that the element
35476 * text content should be replaced with the interpolation of the template
35477 * in the `ngBindTemplate` attribute.
35478 * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
35479 * expressions. This directive is needed since some HTML elements
35480 * (such as TITLE and OPTION) cannot contain SPAN elements.
35483 * @param {string} ngBindTemplate template of form
35484 * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
35487 * Try it here: enter text in text box and watch the greeting change.
35488 <example module="bindExample" name="ng-bind-template">
35489 <file name="index.html">
35491 angular.module('bindExample', [])
35492 .controller('ExampleController', ['$scope', function($scope) {
35493 $scope.salutation = 'Hello';
35494 $scope.name = 'World';
35497 <div ng-controller="ExampleController">
35498 <label>Salutation: <input type="text" ng-model="salutation"></label><br>
35499 <label>Name: <input type="text" ng-model="name"></label><br>
35500 <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
35503 <file name="protractor.js" type="protractor">
35504 it('should check ng-bind', function() {
35505 var salutationElem = element(by.binding('salutation'));
35506 var salutationInput = element(by.model('salutation'));
35507 var nameInput = element(by.model('name'));
35509 expect(salutationElem.getText()).toBe('Hello World!');
35511 salutationInput.clear();
35512 salutationInput.sendKeys('Greetings');
35514 nameInput.sendKeys('user');
35516 expect(salutationElem.getText()).toBe('Greetings user!');
35521 var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
35523 compile: function ngBindTemplateCompile(templateElement) {
35524 $compile.$$addBindingClass(templateElement);
35525 return function ngBindTemplateLink(scope, element, attr) {
35526 var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
35527 $compile.$$addBindingInfo(element, interpolateFn.expressions);
35528 element = element[0];
35529 attr.$observe('ngBindTemplate', function(value) {
35530 element.textContent = isUndefined(value) ? '' : value;
35543 * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
35544 * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
35545 * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
35546 * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
35547 * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
35549 * You may also bypass sanitization for values you know are safe. To do so, bind to
35550 * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
35551 * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
35553 * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
35554 * will have an exception (instead of an exploit.)
35557 * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
35561 <example module="bindHtmlExample" deps="angular-sanitize.js" name="ng-bind-html">
35562 <file name="index.html">
35563 <div ng-controller="ExampleController">
35564 <p ng-bind-html="myHTML"></p>
35568 <file name="script.js">
35569 angular.module('bindHtmlExample', ['ngSanitize'])
35570 .controller('ExampleController', ['$scope', function($scope) {
35572 'I am an <code>HTML</code>string with ' +
35573 '<a href="#">links!</a> and other <em>stuff</em>';
35577 <file name="protractor.js" type="protractor">
35578 it('should check ng-bind-html', function() {
35579 expect(element(by.binding('myHTML')).getText()).toBe(
35580 'I am an HTMLstring with links! and other stuff');
35585 var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
35588 compile: function ngBindHtmlCompile(tElement, tAttrs) {
35589 var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
35590 var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
35591 // Unwrap the value to compare the actual inner safe value, not the wrapper object.
35592 return $sce.valueOf(val);
35594 $compile.$$addBindingClass(tElement);
35596 return function ngBindHtmlLink(scope, element, attr) {
35597 $compile.$$addBindingInfo(element, attr.ngBindHtml);
35599 scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
35600 // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
35601 var value = ngBindHtmlGetter(scope);
35602 element.html($sce.getTrustedHtml(value) || '');
35614 * Evaluate the given expression when the user changes the input.
35615 * The expression is evaluated immediately, unlike the JavaScript onchange event
35616 * which only triggers at the end of a change (usually, when the user leaves the
35617 * form element or presses the return key).
35619 * The `ngChange` expression is only evaluated when a change in the input value causes
35620 * a new value to be committed to the model.
35622 * It will not be evaluated:
35623 * * if the value returned from the `$parsers` transformation pipeline has not changed
35624 * * if the input has continued to be invalid since the model will stay `null`
35625 * * if the model is changed programmatically and not by a change to the input value
35628 * Note, this directive requires `ngModel` to be present.
35631 * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
35635 * <example name="ngChange-directive" module="changeExample">
35636 * <file name="index.html">
35638 * angular.module('changeExample', [])
35639 * .controller('ExampleController', ['$scope', function($scope) {
35640 * $scope.counter = 0;
35641 * $scope.change = function() {
35642 * $scope.counter++;
35646 * <div ng-controller="ExampleController">
35647 * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
35648 * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
35649 * <label for="ng-change-example2">Confirmed</label><br />
35650 * <tt>debug = {{confirmed}}</tt><br/>
35651 * <tt>counter = {{counter}}</tt><br/>
35654 * <file name="protractor.js" type="protractor">
35655 * var counter = element(by.binding('counter'));
35656 * var debug = element(by.binding('confirmed'));
35658 * it('should evaluate the expression if changing from view', function() {
35659 * expect(counter.getText()).toContain('0');
35661 * element(by.id('ng-change-example1')).click();
35663 * expect(counter.getText()).toContain('1');
35664 * expect(debug.getText()).toContain('true');
35667 * it('should not evaluate the expression if changing from model', function() {
35668 * element(by.id('ng-change-example2')).click();
35670 * expect(counter.getText()).toContain('0');
35671 * expect(debug.getText()).toContain('true');
35676 var ngChangeDirective = valueFn({
35678 require: 'ngModel',
35679 link: function(scope, element, attr, ctrl) {
35680 ctrl.$viewChangeListeners.push(function() {
35681 scope.$eval(attr.ngChange);
35688 ngClassEvenDirective,
35689 ngClassOddDirective
35692 function classDirective(name, selector) {
35693 name = 'ngClass' + name;
35694 return ['$animate', function($animate) {
35697 link: function(scope, element, attr) {
35700 attr.$observe('class', function(value) {
35701 ngClassWatchAction(scope.$eval(attr[name]));
35705 if (name !== 'ngClass') {
35706 scope.$watch('$index', function($index, old$index) {
35707 /* eslint-disable no-bitwise */
35708 var mod = $index & 1;
35709 if (mod !== (old$index & 1)) {
35710 var classes = arrayClasses(oldVal);
35711 if (mod === selector) {
35712 addClasses(classes);
35714 removeClasses(classes);
35717 /* eslint-enable */
35721 scope.$watch(attr[name], ngClassWatchAction, true);
35723 function addClasses(classes) {
35724 var newClasses = digestClassCounts(classes, 1);
35725 attr.$addClass(newClasses);
35728 function removeClasses(classes) {
35729 var newClasses = digestClassCounts(classes, -1);
35730 attr.$removeClass(newClasses);
35733 function digestClassCounts(classes, count) {
35734 // Use createMap() to prevent class assumptions involving property
35735 // names in Object.prototype
35736 var classCounts = element.data('$classCounts') || createMap();
35737 var classesToUpdate = [];
35738 forEach(classes, function(className) {
35739 if (count > 0 || classCounts[className]) {
35740 classCounts[className] = (classCounts[className] || 0) + count;
35741 if (classCounts[className] === +(count > 0)) {
35742 classesToUpdate.push(className);
35746 element.data('$classCounts', classCounts);
35747 return classesToUpdate.join(' ');
35750 function updateClasses(oldClasses, newClasses) {
35751 var toAdd = arrayDifference(newClasses, oldClasses);
35752 var toRemove = arrayDifference(oldClasses, newClasses);
35753 toAdd = digestClassCounts(toAdd, 1);
35754 toRemove = digestClassCounts(toRemove, -1);
35755 if (toAdd && toAdd.length) {
35756 $animate.addClass(element, toAdd);
35758 if (toRemove && toRemove.length) {
35759 $animate.removeClass(element, toRemove);
35763 function ngClassWatchAction(newVal) {
35764 // eslint-disable-next-line no-bitwise
35765 if (selector === true || (scope.$index & 1) === selector) {
35766 var newClasses = arrayClasses(newVal || []);
35768 addClasses(newClasses);
35769 } else if (!equals(newVal,oldVal)) {
35770 var oldClasses = arrayClasses(oldVal);
35771 updateClasses(oldClasses, newClasses);
35774 if (isArray(newVal)) {
35775 oldVal = newVal.map(function(v) { return shallowCopy(v); });
35777 oldVal = shallowCopy(newVal);
35783 function arrayDifference(tokens1, tokens2) {
35787 for (var i = 0; i < tokens1.length; i++) {
35788 var token = tokens1[i];
35789 for (var j = 0; j < tokens2.length; j++) {
35790 if (token === tokens2[j]) continue outer;
35792 values.push(token);
35797 function arrayClasses(classVal) {
35799 if (isArray(classVal)) {
35800 forEach(classVal, function(v) {
35801 classes = classes.concat(arrayClasses(v));
35804 } else if (isString(classVal)) {
35805 return classVal.split(' ');
35806 } else if (isObject(classVal)) {
35807 forEach(classVal, function(v, k) {
35809 classes = classes.concat(k.split(' '));
35825 * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
35826 * an expression that represents all classes to be added.
35828 * The directive operates in three different ways, depending on which of three types the expression
35831 * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
35834 * 2. If the expression evaluates to an object, then for each key-value pair of the
35835 * object with a truthy value the corresponding key is used as a class name.
35837 * 3. If the expression evaluates to an array, each element of the array should either be a string as in
35838 * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
35839 * to give you more control over what CSS classes appear. See the code below for an example of this.
35842 * The directive won't add duplicate classes if a particular class was already set.
35844 * When the expression changes, the previously added classes are removed and only then are the
35845 * new classes added.
35848 * You should not use {@link guide/interpolation interpolation} in the value of the `class`
35849 * attribute, when using the `ngClass` directive on the same element.
35850 * See {@link guide/interpolation#known-issues here} for more info.
35853 * | Animation | Occurs |
35854 * |----------------------------------|-------------------------------------|
35855 * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
35856 * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
35859 * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
35860 * of the evaluation can be a string representing space delimited class
35861 * names, an array, or a map of class names to boolean values. In the case of a map, the
35862 * names of the properties whose values are truthy will be added as css classes to the
35865 * @example Example that demonstrates basic bindings via ngClass directive.
35866 <example name="ng-class">
35867 <file name="index.html">
35868 <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
35870 <input type="checkbox" ng-model="deleted">
35871 deleted (apply "strike" class)
35874 <input type="checkbox" ng-model="important">
35875 important (apply "bold" class)
35878 <input type="checkbox" ng-model="error">
35879 error (apply "has-error" class)
35882 <p ng-class="style">Using String Syntax</p>
35883 <input type="text" ng-model="style"
35884 placeholder="Type: bold strike red" aria-label="Type: bold strike red">
35886 <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
35887 <input ng-model="style1"
35888 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
35889 <input ng-model="style2"
35890 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
35891 <input ng-model="style3"
35892 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
35894 <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
35895 <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
35896 <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
35898 <file name="style.css">
35900 text-decoration: line-through;
35910 background-color: yellow;
35916 <file name="protractor.js" type="protractor">
35917 var ps = element.all(by.css('p'));
35919 it('should let you toggle the class', function() {
35921 expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
35922 expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
35924 element(by.model('important')).click();
35925 expect(ps.first().getAttribute('class')).toMatch(/bold/);
35927 element(by.model('error')).click();
35928 expect(ps.first().getAttribute('class')).toMatch(/has-error/);
35931 it('should let you toggle string example', function() {
35932 expect(ps.get(1).getAttribute('class')).toBe('');
35933 element(by.model('style')).clear();
35934 element(by.model('style')).sendKeys('red');
35935 expect(ps.get(1).getAttribute('class')).toBe('red');
35938 it('array example should have 3 classes', function() {
35939 expect(ps.get(2).getAttribute('class')).toBe('');
35940 element(by.model('style1')).sendKeys('bold');
35941 element(by.model('style2')).sendKeys('strike');
35942 element(by.model('style3')).sendKeys('red');
35943 expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
35946 it('array with map example should have 2 classes', function() {
35947 expect(ps.last().getAttribute('class')).toBe('');
35948 element(by.model('style4')).sendKeys('bold');
35949 element(by.model('warning')).click();
35950 expect(ps.last().getAttribute('class')).toBe('bold orange');
35957 The example below demonstrates how to perform animations using ngClass.
35959 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class">
35960 <file name="index.html">
35961 <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
35962 <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
35964 <span class="base-class" ng-class="myVar">Sample Text</span>
35966 <file name="style.css">
35968 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
35971 .base-class.my-class {
35976 <file name="protractor.js" type="protractor">
35977 it('should check ng-class', function() {
35978 expect(element(by.css('.base-class')).getAttribute('class')).not.
35979 toMatch(/my-class/);
35981 element(by.id('setbtn')).click();
35983 expect(element(by.css('.base-class')).getAttribute('class')).
35984 toMatch(/my-class/);
35986 element(by.id('clearbtn')).click();
35988 expect(element(by.css('.base-class')).getAttribute('class')).not.
35989 toMatch(/my-class/);
35995 ## ngClass and pre-existing CSS3 Transitions/Animations
35996 The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
35997 Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
35998 any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
35999 to view the step by step details of {@link $animate#addClass $animate.addClass} and
36000 {@link $animate#removeClass $animate.removeClass}.
36002 var ngClassDirective = classDirective('', true);
36010 * The `ngClassOdd` and `ngClassEven` directives work exactly as
36011 * {@link ng.directive:ngClass ngClass}, except they work in
36012 * conjunction with `ngRepeat` and take effect only on odd (even) rows.
36014 * This directive can be applied only within the scope of an
36015 * {@link ng.directive:ngRepeat ngRepeat}.
36018 * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
36019 * of the evaluation can be a string representing space delimited class names or an array.
36022 <example name="ng-class-odd">
36023 <file name="index.html">
36024 <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
36025 <li ng-repeat="name in names">
36026 <span ng-class-odd="'odd'" ng-class-even="'even'">
36032 <file name="style.css">
36040 <file name="protractor.js" type="protractor">
36041 it('should check ng-class-odd and ng-class-even', function() {
36042 expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
36044 expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
36050 var ngClassOddDirective = classDirective('Odd', 0);
36054 * @name ngClassEven
36058 * The `ngClassOdd` and `ngClassEven` directives work exactly as
36059 * {@link ng.directive:ngClass ngClass}, except they work in
36060 * conjunction with `ngRepeat` and take effect only on odd (even) rows.
36062 * This directive can be applied only within the scope of an
36063 * {@link ng.directive:ngRepeat ngRepeat}.
36066 * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
36067 * result of the evaluation can be a string representing space delimited class names or an array.
36070 <example name="ng-class-even">
36071 <file name="index.html">
36072 <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
36073 <li ng-repeat="name in names">
36074 <span ng-class-odd="'odd'" ng-class-even="'even'">
36075 {{name}}
36080 <file name="style.css">
36088 <file name="protractor.js" type="protractor">
36089 it('should check ng-class-odd and ng-class-even', function() {
36090 expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
36092 expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
36098 var ngClassEvenDirective = classDirective('Even', 1);
36106 * The `ngCloak` directive is used to prevent the Angular html template from being briefly
36107 * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
36108 * directive to avoid the undesirable flicker effect caused by the html template display.
36110 * The directive can be applied to the `<body>` element, but the preferred usage is to apply
36111 * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
36112 * of the browser view.
36114 * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
36115 * `angular.min.js`.
36116 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
36119 * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
36120 * display: none !important;
36124 * When this css rule is loaded by the browser, all html elements (including their children) that
36125 * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
36126 * during the compilation of the template it deletes the `ngCloak` element attribute, making
36127 * the compiled element visible.
36129 * For the best result, the `angular.js` script must be loaded in the head section of the html
36130 * document; alternatively, the css rule above must be included in the external stylesheet of the
36136 <example name="ng-cloak">
36137 <file name="index.html">
36138 <div id="template1" ng-cloak>{{ 'hello' }}</div>
36139 <div id="template2" class="ng-cloak">{{ 'world' }}</div>
36141 <file name="protractor.js" type="protractor">
36142 it('should remove the template directive and css class', function() {
36143 expect($('#template1').getAttribute('ng-cloak')).
36145 expect($('#template2').getAttribute('ng-cloak')).
36152 var ngCloakDirective = ngDirective({
36153 compile: function(element, attr) {
36154 attr.$set('ngCloak', undefined);
36155 element.removeClass('ng-cloak');
36161 * @name ngController
36164 * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
36165 * supports the principles behind the Model-View-Controller design pattern.
36167 * MVC components in angular:
36169 * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
36170 * are accessed through bindings.
36171 * * View — The template (HTML with data bindings) that is rendered into the View.
36172 * * Controller — The `ngController` directive specifies a Controller class; the class contains business
36173 * logic behind the application to decorate the scope with functions and values
36175 * Note that you can also attach controllers to the DOM by declaring it in a route definition
36176 * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
36177 * again using `ng-controller` in the template itself. This will cause the controller to be attached
36178 * and executed twice.
36183 * @param {expression} ngController Name of a constructor function registered with the current
36184 * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
36185 * that on the current scope evaluates to a constructor function.
36187 * The controller instance can be published into a scope property by specifying
36188 * `ng-controller="as propertyName"`.
36190 * If the current `$controllerProvider` is configured to use globals (via
36191 * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
36192 * also be the name of a globally accessible constructor function (not recommended).
36195 * Here is a simple form for editing user contact information. Adding, removing, clearing, and
36196 * greeting are methods declared on the controller (see source tab). These methods can
36197 * easily be called from the angular markup. Any changes to the data are automatically reflected
36198 * in the View without the need for a manual update.
36200 * Two different declaration styles are included below:
36202 * * one binds methods and properties directly onto the controller using `this`:
36203 * `ng-controller="SettingsController1 as settings"`
36204 * * one injects `$scope` into the controller:
36205 * `ng-controller="SettingsController2"`
36207 * The second option is more common in the Angular community, and is generally used in boilerplates
36208 * and in this guide. However, there are advantages to binding properties directly to the controller
36209 * and avoiding scope.
36211 * * Using `controller as` makes it obvious which controller you are accessing in the template when
36212 * multiple controllers apply to an element.
36213 * * If you are writing your controllers as classes you have easier access to the properties and
36214 * methods, which will appear on the scope, from inside the controller code.
36215 * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
36216 * inheritance masking primitives.
36218 * This example demonstrates the `controller as` syntax.
36220 * <example name="ngControllerAs" module="controllerAsExample">
36221 * <file name="index.html">
36222 * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
36223 * <label>Name: <input type="text" ng-model="settings.name"/></label>
36224 * <button ng-click="settings.greet()">greet</button><br/>
36227 * <li ng-repeat="contact in settings.contacts">
36228 * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
36229 * <option>phone</option>
36230 * <option>email</option>
36232 * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
36233 * <button ng-click="settings.clearContact(contact)">clear</button>
36234 * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
36236 * <li><button ng-click="settings.addContact()">add</button></li>
36240 * <file name="app.js">
36241 * angular.module('controllerAsExample', [])
36242 * .controller('SettingsController1', SettingsController1);
36244 * function SettingsController1() {
36245 * this.name = 'John Smith';
36246 * this.contacts = [
36247 * {type: 'phone', value: '408 555 1212'},
36248 * {type: 'email', value: 'john.smith@example.org'}
36252 * SettingsController1.prototype.greet = function() {
36253 * alert(this.name);
36256 * SettingsController1.prototype.addContact = function() {
36257 * this.contacts.push({type: 'email', value: 'yourname@example.org'});
36260 * SettingsController1.prototype.removeContact = function(contactToRemove) {
36261 * var index = this.contacts.indexOf(contactToRemove);
36262 * this.contacts.splice(index, 1);
36265 * SettingsController1.prototype.clearContact = function(contact) {
36266 * contact.type = 'phone';
36267 * contact.value = '';
36270 * <file name="protractor.js" type="protractor">
36271 * it('should check controller as', function() {
36272 * var container = element(by.id('ctrl-as-exmpl'));
36273 * expect(container.element(by.model('settings.name'))
36274 * .getAttribute('value')).toBe('John Smith');
36276 * var firstRepeat =
36277 * container.element(by.repeater('contact in settings.contacts').row(0));
36278 * var secondRepeat =
36279 * container.element(by.repeater('contact in settings.contacts').row(1));
36281 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
36282 * .toBe('408 555 1212');
36284 * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
36285 * .toBe('john.smith@example.org');
36287 * firstRepeat.element(by.buttonText('clear')).click();
36289 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
36292 * container.element(by.buttonText('add')).click();
36294 * expect(container.element(by.repeater('contact in settings.contacts').row(2))
36295 * .element(by.model('contact.value'))
36296 * .getAttribute('value'))
36297 * .toBe('yourname@example.org');
36302 * This example demonstrates the "attach to `$scope`" style of controller.
36304 * <example name="ngController" module="controllerExample">
36305 * <file name="index.html">
36306 * <div id="ctrl-exmpl" ng-controller="SettingsController2">
36307 * <label>Name: <input type="text" ng-model="name"/></label>
36308 * <button ng-click="greet()">greet</button><br/>
36311 * <li ng-repeat="contact in contacts">
36312 * <select ng-model="contact.type" id="select_{{$index}}">
36313 * <option>phone</option>
36314 * <option>email</option>
36316 * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
36317 * <button ng-click="clearContact(contact)">clear</button>
36318 * <button ng-click="removeContact(contact)">X</button>
36320 * <li>[ <button ng-click="addContact()">add</button> ]</li>
36324 * <file name="app.js">
36325 * angular.module('controllerExample', [])
36326 * .controller('SettingsController2', ['$scope', SettingsController2]);
36328 * function SettingsController2($scope) {
36329 * $scope.name = 'John Smith';
36330 * $scope.contacts = [
36331 * {type:'phone', value:'408 555 1212'},
36332 * {type:'email', value:'john.smith@example.org'}
36335 * $scope.greet = function() {
36336 * alert($scope.name);
36339 * $scope.addContact = function() {
36340 * $scope.contacts.push({type:'email', value:'yourname@example.org'});
36343 * $scope.removeContact = function(contactToRemove) {
36344 * var index = $scope.contacts.indexOf(contactToRemove);
36345 * $scope.contacts.splice(index, 1);
36348 * $scope.clearContact = function(contact) {
36349 * contact.type = 'phone';
36350 * contact.value = '';
36354 * <file name="protractor.js" type="protractor">
36355 * it('should check controller', function() {
36356 * var container = element(by.id('ctrl-exmpl'));
36358 * expect(container.element(by.model('name'))
36359 * .getAttribute('value')).toBe('John Smith');
36361 * var firstRepeat =
36362 * container.element(by.repeater('contact in contacts').row(0));
36363 * var secondRepeat =
36364 * container.element(by.repeater('contact in contacts').row(1));
36366 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
36367 * .toBe('408 555 1212');
36368 * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
36369 * .toBe('john.smith@example.org');
36371 * firstRepeat.element(by.buttonText('clear')).click();
36373 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
36376 * container.element(by.buttonText('add')).click();
36378 * expect(container.element(by.repeater('contact in contacts').row(2))
36379 * .element(by.model('contact.value'))
36380 * .getAttribute('value'))
36381 * .toBe('yourname@example.org');
36387 var ngControllerDirective = [function() {
36404 * Angular has some features that can conflict with certain restrictions that are applied when using
36405 * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
36407 * If you intend to implement CSP with these rules then you must tell Angular not to use these
36410 * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
36413 * The following default rules in CSP affect Angular:
36415 * * The use of `eval()`, `Function(string)` and similar functions to dynamically create and execute
36416 * code from strings is forbidden. Angular makes use of this in the {@link $parse} service to
36417 * provide a 30% increase in the speed of evaluating Angular expressions. (This CSP rule can be
36418 * disabled with the CSP keyword `unsafe-eval`, but it is generally not recommended as it would
36419 * weaken the protections offered by CSP.)
36421 * * The use of inline resources, such as inline `<script>` and `<style>` elements, are forbidden.
36422 * This prevents apps from injecting custom styles directly into the document. Angular makes use of
36423 * this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}). To make these
36424 * directives work when a CSP rule is blocking inline styles, you must link to the `angular-csp.css`
36425 * in your HTML manually. (This CSP rule can be disabled with the CSP keyword `unsafe-inline`, but
36426 * it is generally not recommended as it would weaken the protections offered by CSP.)
36428 * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking dynamic code
36429 * creation from strings (e.g., `unsafe-eval` not specified in CSP header) and automatically
36430 * deactivates this feature in the {@link $parse} service. This autodetection, however, triggers a
36431 * CSP error to be logged in the console:
36434 * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
36435 * script in the following Content Security Policy directive: "default-src 'self'". Note that
36436 * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
36439 * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
36440 * directive on an element of the HTML document that appears before the `<script>` tag that loads
36441 * the `angular.js` file.
36443 * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
36445 * You can specify which of the CSP related Angular features should be deactivated by providing
36446 * a value for the `ng-csp` attribute. The options are as follows:
36448 * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
36450 * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
36452 * You can use these values in the following combinations:
36455 * * No declaration means that Angular will assume that you can do inline styles, but it will do
36456 * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous
36457 * versions of Angular.
36459 * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
36460 * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous
36461 * versions of Angular.
36463 * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can
36464 * inject inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
36466 * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
36467 * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
36469 * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
36470 * styles nor use eval, which is the same as an empty: ng-csp.
36471 * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
36474 * This example shows how to apply the `ngCsp` directive to the `html` tag.
36477 <html ng-app ng-csp>
36483 <!-- Note: the `.csp` suffix in the example name triggers CSP mode in our http server! -->
36484 <example name="example.csp" module="cspExample" ng-csp="true">
36485 <file name="index.html">
36486 <div ng-controller="MainController as ctrl">
36488 <button ng-click="ctrl.inc()" id="inc">Increment</button>
36489 <span id="counter">
36495 <button ng-click="ctrl.evil()" id="evil">Evil</button>
36496 <span id="evilError">
36502 <file name="script.js">
36503 angular.module('cspExample', [])
36504 .controller('MainController', function MainController() {
36506 this.inc = function() {
36509 this.evil = function() {
36511 eval('1+2'); // eslint-disable-line no-eval
36513 this.evilError = e.message;
36518 <file name="protractor.js" type="protractor">
36519 var util, webdriver;
36521 var incBtn = element(by.id('inc'));
36522 var counter = element(by.id('counter'));
36523 var evilBtn = element(by.id('evil'));
36524 var evilError = element(by.id('evilError'));
36526 function getAndClearSevereErrors() {
36527 return browser.manage().logs().get('browser').then(function(browserLog) {
36528 return browserLog.filter(function(logEntry) {
36529 return logEntry.level.value > webdriver.logging.Level.WARNING.value;
36534 function clearErrors() {
36535 getAndClearSevereErrors();
36538 function expectNoErrors() {
36539 getAndClearSevereErrors().then(function(filteredLog) {
36540 expect(filteredLog.length).toEqual(0);
36541 if (filteredLog.length) {
36542 console.log('browser console errors: ' + util.inspect(filteredLog));
36547 function expectError(regex) {
36548 getAndClearSevereErrors().then(function(filteredLog) {
36550 filteredLog.forEach(function(log) {
36551 if (log.message.match(regex)) {
36556 throw new Error('expected an error that matches ' + regex);
36561 beforeEach(function() {
36562 util = require('util');
36563 webdriver = require('selenium-webdriver');
36566 // For now, we only test on Chrome,
36567 // as Safari does not load the page with Protractor's injected scripts,
36568 // and Firefox webdriver always disables content security policy (#6358)
36569 if (browser.params.browser !== 'chrome') {
36573 it('should not report errors when the page is loaded', function() {
36574 // clear errors so we are not dependent on previous tests
36576 // Need to reload the page as the page is already loaded when
36578 browser.driver.getCurrentUrl().then(function(url) {
36584 it('should evaluate expressions', function() {
36585 expect(counter.getText()).toEqual('0');
36587 expect(counter.getText()).toEqual('1');
36591 it('should throw and report an error when using "eval"', function() {
36593 expect(evilError.getText()).toMatch(/Content Security Policy/);
36594 expectError(/Content Security Policy/);
36600 // `ngCsp` is not implemented as a proper directive any more, because we need it be processed while
36601 // we bootstrap the app (before `$parse` is instantiated). For this reason, we just have the `csp()`
36602 // fn that looks for the `ng-csp` attribute anywhere in the current doc.
36609 * The ngClick directive allows you to specify custom behavior when
36610 * an element is clicked.
36614 * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
36615 * click. ({@link guide/expression#-event- Event object is available as `$event`})
36618 <example name="ng-click">
36619 <file name="index.html">
36620 <button ng-click="count = count + 1" ng-init="count=0">
36627 <file name="protractor.js" type="protractor">
36628 it('should check ng-click', function() {
36629 expect(element(by.binding('count')).getText()).toMatch('0');
36630 element(by.css('button')).click();
36631 expect(element(by.binding('count')).getText()).toMatch('1');
36637 * A collection of directives that allows creation of custom event handlers that are defined as
36638 * angular expressions and are compiled and executed within the current scope.
36640 var ngEventDirectives = {};
36642 // For events that might fire synchronously during DOM manipulation
36643 // we need to execute their event handlers asynchronously using $evalAsync,
36644 // so that they are not executed in an inconsistent state.
36645 var forceAsyncEvents = {
36650 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
36651 function(eventName) {
36652 var directiveName = directiveNormalize('ng-' + eventName);
36653 ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
36656 compile: function($element, attr) {
36657 // We expose the powerful $event object on the scope that provides access to the Window,
36658 // etc. that isn't protected by the fast paths in $parse. We explicitly request better
36659 // checks at the cost of speed since event handler expressions are not executed as
36660 // frequently as regular change detection.
36661 var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
36662 return function ngEventHandler(scope, element) {
36663 element.on(eventName, function(event) {
36664 var callback = function() {
36665 fn(scope, {$event:event});
36667 if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
36668 scope.$evalAsync(callback);
36670 scope.$apply(callback);
36685 * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
36689 * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
36690 * a dblclick. (The Event object is available as `$event`)
36693 <example name="ng-dblclick">
36694 <file name="index.html">
36695 <button ng-dblclick="count = count + 1" ng-init="count=0">
36696 Increment (on double click)
36706 * @name ngMousedown
36709 * The ngMousedown directive allows you to specify custom behavior on mousedown event.
36713 * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
36714 * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
36717 <example name="ng-mousedown">
36718 <file name="index.html">
36719 <button ng-mousedown="count = count + 1" ng-init="count=0">
36720 Increment (on mouse down)
36733 * Specify custom behavior on mouseup event.
36737 * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
36738 * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
36741 <example name="ng-mouseup">
36742 <file name="index.html">
36743 <button ng-mouseup="count = count + 1" ng-init="count=0">
36744 Increment (on mouse up)
36753 * @name ngMouseover
36756 * Specify custom behavior on mouseover event.
36760 * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
36761 * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
36764 <example name="ng-mouseover">
36765 <file name="index.html">
36766 <button ng-mouseover="count = count + 1" ng-init="count=0">
36767 Increment (when mouse is over)
36777 * @name ngMouseenter
36780 * Specify custom behavior on mouseenter event.
36784 * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
36785 * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
36788 <example name="ng-mouseenter">
36789 <file name="index.html">
36790 <button ng-mouseenter="count = count + 1" ng-init="count=0">
36791 Increment (when mouse enters)
36801 * @name ngMouseleave
36804 * Specify custom behavior on mouseleave event.
36808 * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
36809 * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
36812 <example name="ng-mouseleave">
36813 <file name="index.html">
36814 <button ng-mouseleave="count = count + 1" ng-init="count=0">
36815 Increment (when mouse leaves)
36825 * @name ngMousemove
36828 * Specify custom behavior on mousemove event.
36832 * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
36833 * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
36836 <example name="ng-mousemove">
36837 <file name="index.html">
36838 <button ng-mousemove="count = count + 1" ng-init="count=0">
36839 Increment (when mouse moves)
36852 * Specify custom behavior on keydown event.
36856 * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
36857 * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
36860 <example name="ng-keydown">
36861 <file name="index.html">
36862 <input ng-keydown="count = count + 1" ng-init="count=0">
36863 key down count: {{count}}
36874 * Specify custom behavior on keyup event.
36878 * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
36879 * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
36882 <example name="ng-keyup">
36883 <file name="index.html">
36884 <p>Typing in the input box below updates the key count</p>
36885 <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
36887 <p>Typing in the input box below updates the keycode</p>
36888 <input ng-keyup="event=$event">
36889 <p>event keyCode: {{ event.keyCode }}</p>
36890 <p>event altKey: {{ event.altKey }}</p>
36901 * Specify custom behavior on keypress event.
36904 * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
36905 * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
36906 * and can be interrogated for keyCode, altKey, etc.)
36909 <example name="ng-keypress">
36910 <file name="index.html">
36911 <input ng-keypress="count = count + 1" ng-init="count=0">
36912 key press count: {{count}}
36923 * Enables binding angular expressions to onsubmit events.
36925 * Additionally it prevents the default action (which for form means sending the request to the
36926 * server and reloading the current page), but only if the form does not contain `action`,
36927 * `data-action`, or `x-action` attributes.
36929 * <div class="alert alert-warning">
36930 * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
36931 * `ngSubmit` handlers together. See the
36932 * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
36933 * for a detailed discussion of when `ngSubmit` may be triggered.
36938 * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
36939 * ({@link guide/expression#-event- Event object is available as `$event`})
36942 <example module="submitExample" name="ng-submit">
36943 <file name="index.html">
36945 angular.module('submitExample', [])
36946 .controller('ExampleController', ['$scope', function($scope) {
36948 $scope.text = 'hello';
36949 $scope.submit = function() {
36951 $scope.list.push(this.text);
36957 <form ng-submit="submit()" ng-controller="ExampleController">
36958 Enter text and hit enter:
36959 <input type="text" ng-model="text" name="text" />
36960 <input type="submit" id="submit" value="Submit" />
36961 <pre>list={{list}}</pre>
36964 <file name="protractor.js" type="protractor">
36965 it('should check ng-submit', function() {
36966 expect(element(by.binding('list')).getText()).toBe('list=[]');
36967 element(by.css('#submit')).click();
36968 expect(element(by.binding('list')).getText()).toContain('hello');
36969 expect(element(by.model('text')).getAttribute('value')).toBe('');
36971 it('should ignore empty strings', function() {
36972 expect(element(by.binding('list')).getText()).toBe('list=[]');
36973 element(by.css('#submit')).click();
36974 element(by.css('#submit')).click();
36975 expect(element(by.binding('list')).getText()).toContain('hello');
36986 * Specify custom behavior on focus event.
36988 * Note: As the `focus` event is executed synchronously when calling `input.focus()`
36989 * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
36990 * during an `$apply` to ensure a consistent state.
36992 * @element window, input, select, textarea, a
36994 * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
36995 * focus. ({@link guide/expression#-event- Event object is available as `$event`})
36998 * See {@link ng.directive:ngClick ngClick}
37006 * Specify custom behavior on blur event.
37008 * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
37009 * an element has lost focus.
37011 * Note: As the `blur` event is executed synchronously also during DOM manipulations
37012 * (e.g. removing a focussed input),
37013 * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
37014 * during an `$apply` to ensure a consistent state.
37016 * @element window, input, select, textarea, a
37018 * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
37019 * blur. ({@link guide/expression#-event- Event object is available as `$event`})
37022 * See {@link ng.directive:ngClick ngClick}
37030 * Specify custom behavior on copy event.
37032 * @element window, input, select, textarea, a
37034 * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
37035 * copy. ({@link guide/expression#-event- Event object is available as `$event`})
37038 <example name="ng-copy">
37039 <file name="index.html">
37040 <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
37051 * Specify custom behavior on cut event.
37053 * @element window, input, select, textarea, a
37055 * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
37056 * cut. ({@link guide/expression#-event- Event object is available as `$event`})
37059 <example name="ng-cut">
37060 <file name="index.html">
37061 <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
37072 * Specify custom behavior on paste event.
37074 * @element window, input, select, textarea, a
37076 * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
37077 * paste. ({@link guide/expression#-event- Event object is available as `$event`})
37080 <example name="ng-paste">
37081 <file name="index.html">
37082 <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
37095 * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
37096 * {expression}. If the expression assigned to `ngIf` evaluates to a false
37097 * value then the element is removed from the DOM, otherwise a clone of the
37098 * element is reinserted into the DOM.
37100 * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
37101 * element in the DOM rather than changing its visibility via the `display` css property. A common
37102 * case when this difference is significant is when using css selectors that rely on an element's
37103 * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
37105 * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
37106 * is created when the element is restored. The scope created within `ngIf` inherits from
37107 * its parent scope using
37108 * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
37109 * An important implication of this is if `ngModel` is used within `ngIf` to bind to
37110 * a javascript primitive defined in the parent scope. In this case any modifications made to the
37111 * variable within the child scope will override (hide) the value in the parent scope.
37113 * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
37114 * is if an element's class attribute is directly modified after it's compiled, using something like
37115 * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
37116 * the added class will be lost because the original compiled state is used to regenerate the element.
37118 * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
37119 * and `leave` effects.
37122 * | Animation | Occurs |
37123 * |----------------------------------|-------------------------------------|
37124 * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
37125 * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
37130 * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
37131 * the element is removed from the DOM tree. If it is truthy a copy of the compiled
37132 * element is added to the DOM tree.
37135 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-if">
37136 <file name="index.html">
37137 <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
37139 <span ng-if="checked" class="animate-if">
37140 This is removed when the checkbox is unchecked.
37143 <file name="animations.css">
37146 border:1px solid black;
37150 .animate-if.ng-enter, .animate-if.ng-leave {
37151 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
37154 .animate-if.ng-enter,
37155 .animate-if.ng-leave.ng-leave-active {
37159 .animate-if.ng-leave,
37160 .animate-if.ng-enter.ng-enter-active {
37166 var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
37168 multiElement: true,
37169 transclude: 'element',
37174 link: function($scope, $element, $attr, ctrl, $transclude) {
37175 var block, childScope, previousElements;
37176 $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
37180 $transclude(function(clone, newScope) {
37181 childScope = newScope;
37182 clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
37183 // Note: We only need the first/last node of the cloned nodes.
37184 // However, we need to keep the reference to the jqlite wrapper as it might be changed later
37185 // by a directive with templateUrl when its template arrives.
37189 $animate.enter(clone, $element.parent(), $element);
37193 if (previousElements) {
37194 previousElements.remove();
37195 previousElements = null;
37198 childScope.$destroy();
37202 previousElements = getBlockNodes(block.clone);
37203 $animate.leave(previousElements).done(function(response) {
37204 if (response !== false) previousElements = null;
37220 * Fetches, compiles and includes an external HTML fragment.
37222 * By default, the template URL is restricted to the same domain and protocol as the
37223 * application document. This is done by calling {@link $sce#getTrustedResourceUrl
37224 * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
37225 * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
37226 * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
37227 * ng.$sce Strict Contextual Escaping}.
37229 * In addition, the browser's
37230 * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
37231 * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
37232 * policy may further restrict whether the template is successfully loaded.
37233 * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
37234 * access on some browsers.
37237 * | Animation | Occurs |
37238 * |----------------------------------|-------------------------------------|
37239 * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
37240 * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
37242 * The enter and leave animation occur concurrently.
37247 * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
37248 * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
37249 * @param {string=} onload Expression to evaluate when a new partial is loaded.
37250 * <div class="alert alert-warning">
37251 * **Note:** When using onload on SVG elements in IE11, the browser will try to call
37252 * a function with the name on the window element, which will usually throw a
37253 * "function is undefined" error. To fix this, you can instead use `data-onload` or a
37254 * different form that {@link guide/directive#normalization matches} `onload`.
37257 * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
37258 * $anchorScroll} to scroll the viewport after the content is loaded.
37260 * - If the attribute is not set, disable scrolling.
37261 * - If the attribute is set without value, enable scrolling.
37262 * - Otherwise enable scrolling only if the expression evaluates to truthy value.
37265 <example module="includeExample" deps="angular-animate.js" animations="true" name="ng-include">
37266 <file name="index.html">
37267 <div ng-controller="ExampleController">
37268 <select ng-model="template" ng-options="t.name for t in templates">
37269 <option value="">(blank)</option>
37271 url of the template: <code>{{template.url}}</code>
37273 <div class="slide-animate-container">
37274 <div class="slide-animate" ng-include="template.url"></div>
37278 <file name="script.js">
37279 angular.module('includeExample', ['ngAnimate'])
37280 .controller('ExampleController', ['$scope', function($scope) {
37282 [{ name: 'template1.html', url: 'template1.html'},
37283 { name: 'template2.html', url: 'template2.html'}];
37284 $scope.template = $scope.templates[0];
37287 <file name="template1.html">
37288 Content of template1.html
37290 <file name="template2.html">
37291 Content of template2.html
37293 <file name="animations.css">
37294 .slide-animate-container {
37297 border:1px solid black;
37306 .slide-animate.ng-enter, .slide-animate.ng-leave {
37307 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
37318 .slide-animate.ng-enter {
37321 .slide-animate.ng-enter.ng-enter-active {
37325 .slide-animate.ng-leave {
37328 .slide-animate.ng-leave.ng-leave-active {
37332 <file name="protractor.js" type="protractor">
37333 var templateSelect = element(by.model('template'));
37334 var includeElem = element(by.css('[ng-include]'));
37336 it('should load template1.html', function() {
37337 expect(includeElem.getText()).toMatch(/Content of template1.html/);
37340 it('should load template2.html', function() {
37341 if (browser.params.browser === 'firefox') {
37342 // Firefox can't handle using selects
37343 // See https://github.com/angular/protractor/issues/480
37346 templateSelect.click();
37347 templateSelect.all(by.css('option')).get(2).click();
37348 expect(includeElem.getText()).toMatch(/Content of template2.html/);
37351 it('should change to blank', function() {
37352 if (browser.params.browser === 'firefox') {
37353 // Firefox can't handle using selects
37356 templateSelect.click();
37357 templateSelect.all(by.css('option')).get(0).click();
37358 expect(includeElem.isPresent()).toBe(false);
37367 * @name ngInclude#$includeContentRequested
37368 * @eventType emit on the scope ngInclude was declared in
37370 * Emitted every time the ngInclude content is requested.
37372 * @param {Object} angularEvent Synthetic event object.
37373 * @param {String} src URL of content to load.
37379 * @name ngInclude#$includeContentLoaded
37380 * @eventType emit on the current ngInclude scope
37382 * Emitted every time the ngInclude content is reloaded.
37384 * @param {Object} angularEvent Synthetic event object.
37385 * @param {String} src URL of content to load.
37391 * @name ngInclude#$includeContentError
37392 * @eventType emit on the scope ngInclude was declared in
37394 * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
37396 * @param {Object} angularEvent Synthetic event object.
37397 * @param {String} src URL of content to load.
37399 var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
37400 function($templateRequest, $anchorScroll, $animate) {
37405 transclude: 'element',
37406 controller: angular.noop,
37407 compile: function(element, attr) {
37408 var srcExp = attr.ngInclude || attr.src,
37409 onloadExp = attr.onload || '',
37410 autoScrollExp = attr.autoscroll;
37412 return function(scope, $element, $attr, ctrl, $transclude) {
37413 var changeCounter = 0,
37418 var cleanupLastIncludeContent = function() {
37419 if (previousElement) {
37420 previousElement.remove();
37421 previousElement = null;
37423 if (currentScope) {
37424 currentScope.$destroy();
37425 currentScope = null;
37427 if (currentElement) {
37428 $animate.leave(currentElement).done(function(response) {
37429 if (response !== false) previousElement = null;
37431 previousElement = currentElement;
37432 currentElement = null;
37436 scope.$watch(srcExp, function ngIncludeWatchAction(src) {
37437 var afterAnimation = function(response) {
37438 if (response !== false && isDefined(autoScrollExp) &&
37439 (!autoScrollExp || scope.$eval(autoScrollExp))) {
37443 var thisChangeId = ++changeCounter;
37446 //set the 2nd param to true to ignore the template request error so that the inner
37447 //contents and scope can be cleaned up.
37448 $templateRequest(src, true).then(function(response) {
37449 if (scope.$$destroyed) return;
37451 if (thisChangeId !== changeCounter) return;
37452 var newScope = scope.$new();
37453 ctrl.template = response;
37455 // Note: This will also link all children of ng-include that were contained in the original
37456 // html. If that content contains controllers, ... they could pollute/change the scope.
37457 // However, using ng-include on an element with additional content does not make sense...
37458 // Note: We can't remove them in the cloneAttchFn of $transclude as that
37459 // function is called before linking the content, which would apply child
37460 // directives to non existing elements.
37461 var clone = $transclude(newScope, function(clone) {
37462 cleanupLastIncludeContent();
37463 $animate.enter(clone, null, $element).done(afterAnimation);
37466 currentScope = newScope;
37467 currentElement = clone;
37469 currentScope.$emit('$includeContentLoaded', src);
37470 scope.$eval(onloadExp);
37472 if (scope.$$destroyed) return;
37474 if (thisChangeId === changeCounter) {
37475 cleanupLastIncludeContent();
37476 scope.$emit('$includeContentError', src);
37479 scope.$emit('$includeContentRequested', src);
37481 cleanupLastIncludeContent();
37482 ctrl.template = null;
37490 // This directive is called during the $transclude call of the first `ngInclude` directive.
37491 // It will replace and compile the content of the element with the loaded template.
37492 // We need this directive so that the element content is already filled when
37493 // the link function of another directive on the same element as ngInclude
37495 var ngIncludeFillContentDirective = ['$compile',
37496 function($compile) {
37500 require: 'ngInclude',
37501 link: function(scope, $element, $attr, ctrl) {
37502 if (toString.call($element[0]).match(/SVG/)) {
37503 // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
37504 // support innerHTML, so detect this here and try to generate the contents
37507 $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
37508 function namespaceAdaptedClone(clone) {
37509 $element.append(clone);
37510 }, {futureParentElement: $element});
37514 $element.html(ctrl.template);
37515 $compile($element.contents())(scope);
37526 * The `ngInit` directive allows you to evaluate an expression in the
37529 * <div class="alert alert-danger">
37530 * This directive can be abused to add unnecessary amounts of logic into your templates.
37531 * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
37532 * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
37533 * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
37534 * rather than `ngInit` to initialize values on a scope.
37537 * <div class="alert alert-warning">
37538 * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
37539 * sure you have parentheses to ensure correct operator precedence:
37540 * <pre class="prettyprint">
37541 * `<div ng-init="test1 = ($index | toString)"></div>`
37548 * @param {expression} ngInit {@link guide/expression Expression} to eval.
37551 <example module="initExample" name="ng-init">
37552 <file name="index.html">
37554 angular.module('initExample', [])
37555 .controller('ExampleController', ['$scope', function($scope) {
37556 $scope.list = [['a', 'b'], ['c', 'd']];
37559 <div ng-controller="ExampleController">
37560 <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
37561 <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
37562 <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
37567 <file name="protractor.js" type="protractor">
37568 it('should alias index positions', function() {
37569 var elements = element.all(by.css('.example-init'));
37570 expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
37571 expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
37572 expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
37573 expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
37578 var ngInitDirective = ngDirective({
37580 compile: function() {
37582 pre: function(scope, element, attrs) {
37583 scope.$eval(attrs.ngInit);
37594 * Text input that converts between a delimited string and an array of strings. The default
37595 * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
37596 * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
37598 * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
37599 * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
37600 * list item is respected. This implies that the user of the directive is responsible for
37601 * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
37602 * tab or newline character.
37603 * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
37604 * when joining the list items back together) and whitespace around each list item is stripped
37605 * before it is added to the model.
37607 * ### Example with Validation
37609 * <example name="ngList-directive" module="listExample">
37610 * <file name="app.js">
37611 * angular.module('listExample', [])
37612 * .controller('ExampleController', ['$scope', function($scope) {
37613 * $scope.names = ['morpheus', 'neo', 'trinity'];
37616 * <file name="index.html">
37617 * <form name="myForm" ng-controller="ExampleController">
37618 * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
37619 * <span role="alert">
37620 * <span class="error" ng-show="myForm.namesInput.$error.required">
37624 * <tt>names = {{names}}</tt><br/>
37625 * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
37626 * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
37627 * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
37628 * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
37631 * <file name="protractor.js" type="protractor">
37632 * var listInput = element(by.model('names'));
37633 * var names = element(by.exactBinding('names'));
37634 * var valid = element(by.binding('myForm.namesInput.$valid'));
37635 * var error = element(by.css('span.error'));
37637 * it('should initialize to model', function() {
37638 * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
37639 * expect(valid.getText()).toContain('true');
37640 * expect(error.getCssValue('display')).toBe('none');
37643 * it('should be invalid if empty', function() {
37644 * listInput.clear();
37645 * listInput.sendKeys('');
37647 * expect(names.getText()).toContain('');
37648 * expect(valid.getText()).toContain('false');
37649 * expect(error.getCssValue('display')).not.toBe('none');
37654 * ### Example - splitting on newline
37655 * <example name="ngList-directive-newlines">
37656 * <file name="index.html">
37657 * <textarea ng-model="list" ng-list=" " ng-trim="false"></textarea>
37658 * <pre>{{ list | json }}</pre>
37660 * <file name="protractor.js" type="protractor">
37661 * it("should split the text by newlines", function() {
37662 * var listInput = element(by.model('list'));
37663 * var output = element(by.binding('list | json'));
37664 * listInput.sendKeys('abc\ndef\nghi');
37665 * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
37671 * @param {string=} ngList optional delimiter that should be used to split the value.
37673 var ngListDirective = function() {
37677 require: 'ngModel',
37678 link: function(scope, element, attr, ctrl) {
37679 // We want to control whitespace trimming so we use this convoluted approach
37680 // to access the ngList attribute, which doesn't pre-trim the attribute
37681 var ngList = element.attr(attr.$attr.ngList) || ', ';
37682 var trimValues = attr.ngTrim !== 'false';
37683 var separator = trimValues ? trim(ngList) : ngList;
37685 var parse = function(viewValue) {
37686 // If the viewValue is invalid (say required but empty) it will be `undefined`
37687 if (isUndefined(viewValue)) return;
37692 forEach(viewValue.split(separator), function(value) {
37693 if (value) list.push(trimValues ? trim(value) : value);
37700 ctrl.$parsers.push(parse);
37701 ctrl.$formatters.push(function(value) {
37702 if (isArray(value)) {
37703 return value.join(ngList);
37709 // Override the standard $isEmpty because an empty array means the input is empty.
37710 ctrl.$isEmpty = function(value) {
37711 return !value || !value.length;
37717 /* global VALID_CLASS: true,
37718 INVALID_CLASS: true,
37719 PRISTINE_CLASS: true,
37721 UNTOUCHED_CLASS: true,
37722 TOUCHED_CLASS: true
37725 var VALID_CLASS = 'ng-valid',
37726 INVALID_CLASS = 'ng-invalid',
37727 PRISTINE_CLASS = 'ng-pristine',
37728 DIRTY_CLASS = 'ng-dirty',
37729 UNTOUCHED_CLASS = 'ng-untouched',
37730 TOUCHED_CLASS = 'ng-touched',
37731 PENDING_CLASS = 'ng-pending',
37732 EMPTY_CLASS = 'ng-empty',
37733 NOT_EMPTY_CLASS = 'ng-not-empty';
37735 var ngModelMinErr = minErr('ngModel');
37739 * @name ngModel.NgModelController
37741 * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
37742 * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
37744 * @property {*} $modelValue The value in the model that the control is bound to.
37745 * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
37746 the control reads value from the DOM. The functions are called in array order, each passing
37747 its return value through to the next. The last return value is forwarded to the
37748 {@link ngModel.NgModelController#$validators `$validators`} collection.
37750 Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
37753 Returning `undefined` from a parser means a parse error occurred. In that case,
37754 no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
37755 will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
37756 is set to `true`. The parse error is stored in `ngModel.$error.parse`.
37759 * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
37760 the model value changes. The functions are called in reverse array order, each passing the value through to the
37761 next. The last return value is used as the actual DOM value.
37762 Used to format / convert values for display in the control.
37764 * function formatter(value) {
37766 * return value.toUpperCase();
37769 * ngModel.$formatters.push(formatter);
37772 * @property {Object.<string, function>} $validators A collection of validators that are applied
37773 * whenever the model value changes. The key value within the object refers to the name of the
37774 * validator while the function refers to the validation operation. The validation operation is
37775 * provided with the model value as an argument and must return a true or false value depending
37776 * on the response of that validation.
37779 * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
37780 * var value = modelValue || viewValue;
37781 * return /[0-9]+/.test(value) &&
37782 * /[a-z]+/.test(value) &&
37783 * /[A-Z]+/.test(value) &&
37784 * /\W+/.test(value);
37788 * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
37789 * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
37790 * is expected to return a promise when it is run during the model validation process. Once the promise
37791 * is delivered then the validation status will be set to true when fulfilled and false when rejected.
37792 * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
37793 * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
37794 * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
37795 * will only run once all synchronous validators have passed.
37797 * Please note that if $http is used then it is important that the server returns a success HTTP response code
37798 * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
37801 * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
37802 * var value = modelValue || viewValue;
37804 * // Lookup user by username
37805 * return $http.get('/api/users/' + value).
37806 * then(function resolved() {
37807 * //username exists, this means validation fails
37808 * return $q.reject('exists');
37809 * }, function rejected() {
37810 * //username does not exist, therefore this validation passes
37816 * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
37817 * view value has changed. It is called with no arguments, and its return value is ignored.
37818 * This can be used in place of additional $watches against the model value.
37820 * @property {Object} $error An object hash with all failing validator ids as keys.
37821 * @property {Object} $pending An object hash with all pending validator ids as keys.
37823 * @property {boolean} $untouched True if control has not lost focus yet.
37824 * @property {boolean} $touched True if control has lost focus.
37825 * @property {boolean} $pristine True if user has not interacted with the control yet.
37826 * @property {boolean} $dirty True if user has already interacted with the control.
37827 * @property {boolean} $valid True if there is no error.
37828 * @property {boolean} $invalid True if at least one error on the control.
37829 * @property {string} $name The name attribute of the control.
37833 * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
37834 * The controller contains services for data-binding, validation, CSS updates, and value formatting
37835 * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
37836 * listening to DOM events.
37837 * Such DOM related logic should be provided by other directives which make use of
37838 * `NgModelController` for data-binding to control elements.
37839 * Angular provides this DOM logic for most {@link input `input`} elements.
37840 * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
37841 * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
37844 * ### Custom Control Example
37845 * This example shows how to use `NgModelController` with a custom control to achieve
37846 * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
37847 * collaborate together to achieve the desired result.
37849 * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
37850 * contents be edited in place by the user.
37852 * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
37853 * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
37854 * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
37855 * that content using the `$sce` service.
37857 * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
37858 <file name="style.css">
37859 [contenteditable] {
37860 border: 1px solid black;
37861 background-color: white;
37866 border: 1px solid red;
37870 <file name="script.js">
37871 angular.module('customControl', ['ngSanitize']).
37872 directive('contenteditable', ['$sce', function($sce) {
37874 restrict: 'A', // only activate on element attribute
37875 require: '?ngModel', // get a hold of NgModelController
37876 link: function(scope, element, attrs, ngModel) {
37877 if (!ngModel) return; // do nothing if no ng-model
37879 // Specify how UI should be updated
37880 ngModel.$render = function() {
37881 element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
37884 // Listen for change events to enable binding
37885 element.on('blur keyup change', function() {
37886 scope.$evalAsync(read);
37888 read(); // initialize
37890 // Write data to the model
37892 var html = element.html();
37893 // When we clear the content editable the browser leaves a <br> behind
37894 // If strip-br attribute is provided then we strip this out
37895 if (attrs.stripBr && html === '<br>') {
37898 ngModel.$setViewValue(html);
37904 <file name="index.html">
37905 <form name="myForm">
37906 <div contenteditable
37907 name="myWidget" ng-model="userContent"
37909 required>Change me!</div>
37910 <span ng-show="myForm.myWidget.$error.required">Required!</span>
37912 <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
37915 <file name="protractor.js" type="protractor">
37916 it('should data-bind and become invalid', function() {
37917 if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {
37918 // SafariDriver can't handle contenteditable
37919 // and Firefox driver can't clear contenteditables very well
37922 var contentEditable = element(by.css('[contenteditable]'));
37923 var content = 'Change me!';
37925 expect(contentEditable.getText()).toEqual(content);
37927 contentEditable.clear();
37928 contentEditable.sendKeys(protractor.Key.BACK_SPACE);
37929 expect(contentEditable.getText()).toEqual('');
37930 expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
37937 var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
37938 /** @this */ function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
37939 this.$viewValue = Number.NaN;
37940 this.$modelValue = Number.NaN;
37941 this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
37942 this.$validators = {};
37943 this.$asyncValidators = {};
37944 this.$parsers = [];
37945 this.$formatters = [];
37946 this.$viewChangeListeners = [];
37947 this.$untouched = true;
37948 this.$touched = false;
37949 this.$pristine = true;
37950 this.$dirty = false;
37951 this.$valid = true;
37952 this.$invalid = false;
37953 this.$error = {}; // keep invalid keys here
37954 this.$$success = {}; // keep valid keys here
37955 this.$pending = undefined; // keep pending keys here
37956 this.$name = $interpolate($attr.name || '', false)($scope);
37957 this.$$parentForm = nullFormCtrl;
37959 var parsedNgModel = $parse($attr.ngModel),
37960 parsedNgModelAssign = parsedNgModel.assign,
37961 ngModelGet = parsedNgModel,
37962 ngModelSet = parsedNgModelAssign,
37963 pendingDebounce = null,
37967 this.$$setOptions = function(options) {
37968 ctrl.$options = options;
37969 if (options && options.getterSetter) {
37970 var invokeModelGetter = $parse($attr.ngModel + '()'),
37971 invokeModelSetter = $parse($attr.ngModel + '($$$p)');
37973 ngModelGet = function($scope) {
37974 var modelValue = parsedNgModel($scope);
37975 if (isFunction(modelValue)) {
37976 modelValue = invokeModelGetter($scope);
37980 ngModelSet = function($scope, newValue) {
37981 if (isFunction(parsedNgModel($scope))) {
37982 invokeModelSetter($scope, {$$$p: newValue});
37984 parsedNgModelAssign($scope, newValue);
37987 } else if (!parsedNgModel.assign) {
37988 throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}',
37989 $attr.ngModel, startingTag($element));
37995 * @name ngModel.NgModelController#$render
37998 * Called when the view needs to be updated. It is expected that the user of the ng-model
37999 * directive will implement this method.
38001 * The `$render()` method is invoked in the following situations:
38003 * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
38004 * committed value then `$render()` is called to update the input control.
38005 * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
38006 * the `$viewValue` are different from last time.
38008 * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
38009 * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
38010 * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
38011 * invoked if you only change a property on the objects.
38013 this.$render = noop;
38017 * @name ngModel.NgModelController#$isEmpty
38020 * This is called when we need to determine if the value of an input is empty.
38022 * For instance, the required directive does this to work out if the input has data or not.
38024 * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
38026 * You can override this for input directives whose concept of being empty is different from the
38027 * default. The `checkboxInputType` directive does this because in its case a value of `false`
38030 * @param {*} value The value of the input to check for emptiness.
38031 * @returns {boolean} True if `value` is "empty".
38033 this.$isEmpty = function(value) {
38034 // eslint-disable-next-line no-self-compare
38035 return isUndefined(value) || value === '' || value === null || value !== value;
38038 this.$$updateEmptyClasses = function(value) {
38039 if (ctrl.$isEmpty(value)) {
38040 $animate.removeClass($element, NOT_EMPTY_CLASS);
38041 $animate.addClass($element, EMPTY_CLASS);
38043 $animate.removeClass($element, EMPTY_CLASS);
38044 $animate.addClass($element, NOT_EMPTY_CLASS);
38049 var currentValidationRunId = 0;
38053 * @name ngModel.NgModelController#$setValidity
38056 * Change the validity state, and notify the form.
38058 * This method can be called within $parsers/$formatters or a custom validation implementation.
38059 * However, in most cases it should be sufficient to use the `ngModel.$validators` and
38060 * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
38062 * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
38063 * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
38064 * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
38065 * The `validationErrorKey` should be in camelCase and will get converted into dash-case
38066 * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
38067 * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
38068 * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
38069 * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
38070 * Skipped is used by Angular when validators do not run because of parse errors and
38071 * when `$asyncValidators` do not run because any of the `$validators` failed.
38073 addSetValidityMethod({
38075 $element: $element,
38076 set: function(object, property) {
38077 object[property] = true;
38079 unset: function(object, property) {
38080 delete object[property];
38087 * @name ngModel.NgModelController#$setPristine
38090 * Sets the control to its pristine state.
38092 * This method can be called to remove the `ng-dirty` class and set the control to its pristine
38093 * state (`ng-pristine` class). A model is considered to be pristine when the control
38094 * has not been changed from when first compiled.
38096 this.$setPristine = function() {
38097 ctrl.$dirty = false;
38098 ctrl.$pristine = true;
38099 $animate.removeClass($element, DIRTY_CLASS);
38100 $animate.addClass($element, PRISTINE_CLASS);
38105 * @name ngModel.NgModelController#$setDirty
38108 * Sets the control to its dirty state.
38110 * This method can be called to remove the `ng-pristine` class and set the control to its dirty
38111 * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
38112 * from when first compiled.
38114 this.$setDirty = function() {
38115 ctrl.$dirty = true;
38116 ctrl.$pristine = false;
38117 $animate.removeClass($element, PRISTINE_CLASS);
38118 $animate.addClass($element, DIRTY_CLASS);
38119 ctrl.$$parentForm.$setDirty();
38124 * @name ngModel.NgModelController#$setUntouched
38127 * Sets the control to its untouched state.
38129 * This method can be called to remove the `ng-touched` class and set the control to its
38130 * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
38131 * by default, however this function can be used to restore that state if the model has
38132 * already been touched by the user.
38134 this.$setUntouched = function() {
38135 ctrl.$touched = false;
38136 ctrl.$untouched = true;
38137 $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
38142 * @name ngModel.NgModelController#$setTouched
38145 * Sets the control to its touched state.
38147 * This method can be called to remove the `ng-untouched` class and set the control to its
38148 * touched state (`ng-touched` class). A model is considered to be touched when the user has
38149 * first focused the control element and then shifted focus away from the control (blur event).
38151 this.$setTouched = function() {
38152 ctrl.$touched = true;
38153 ctrl.$untouched = false;
38154 $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
38159 * @name ngModel.NgModelController#$rollbackViewValue
38162 * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
38163 * which may be caused by a pending debounced event or because the input is waiting for some
38166 * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
38167 * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of
38168 * sync with the ngModel's `$modelValue`.
38170 * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
38171 * and reset the input to the last committed view value.
38173 * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
38174 * programmatically before these debounced/future events have resolved/occurred, because Angular's
38175 * dirty checking mechanism is not able to tell whether the model has actually changed or not.
38177 * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
38178 * input which may have such events pending. This is important in order to make sure that the
38179 * input field will be updated with the new model value and any pending operations are cancelled.
38181 * <example name="ng-model-cancel-update" module="cancel-update-example">
38182 * <file name="app.js">
38183 * angular.module('cancel-update-example', [])
38185 * .controller('CancelUpdateController', ['$scope', function($scope) {
38186 * $scope.model = {value1: '', value2: ''};
38188 * $scope.setEmpty = function(e, value, rollback) {
38189 * if (e.keyCode === 27) {
38190 * e.preventDefault();
38192 * $scope.myForm[value].$rollbackViewValue();
38194 * $scope.model[value] = '';
38199 * <file name="index.html">
38200 * <div ng-controller="CancelUpdateController">
38201 * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
38202 * empty them. Follow these steps and observe the difference:</p>
38204 * <li>Type something in the input. You will see that the model is not yet updated</li>
38205 * <li>Press the Escape key.
38207 * <li> In the first example, nothing happens, because the model is already '', and no
38208 * update is detected. If you blur the input, the model will be set to the current view.
38210 * <li> In the second example, the pending update is cancelled, and the input is set back
38211 * to the last committed view value (''). Blurring the input does nothing.
38217 * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
38219 * <p id="inputDescription1">Without $rollbackViewValue():</p>
38220 * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
38221 * ng-keydown="setEmpty($event, 'value1')">
38222 * value1: "{{ model.value1 }}"
38226 * <p id="inputDescription2">With $rollbackViewValue():</p>
38227 * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
38228 * ng-keydown="setEmpty($event, 'value2', true)">
38229 * value2: "{{ model.value2 }}"
38234 <file name="style.css">
38236 display: table-cell;
38239 padding-right: 30px;
38245 this.$rollbackViewValue = function() {
38246 $timeout.cancel(pendingDebounce);
38247 ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
38253 * @name ngModel.NgModelController#$validate
38256 * Runs each of the registered validators (first synchronous validators and then
38257 * asynchronous validators).
38258 * If the validity changes to invalid, the model will be set to `undefined`,
38259 * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
38260 * If the validity changes to valid, it will set the model to the last available valid
38261 * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
38263 this.$validate = function() {
38264 // ignore $validate before model is initialized
38265 if (isNumberNaN(ctrl.$modelValue)) {
38269 var viewValue = ctrl.$$lastCommittedViewValue;
38270 // Note: we use the $$rawModelValue as $modelValue might have been
38271 // set to undefined during a view -> model update that found validation
38272 // errors. We can't parse the view here, since that could change
38273 // the model although neither viewValue nor the model on the scope changed
38274 var modelValue = ctrl.$$rawModelValue;
38276 var prevValid = ctrl.$valid;
38277 var prevModelValue = ctrl.$modelValue;
38279 var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
38281 ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
38282 // If there was no change in validity, don't update the model
38283 // This prevents changing an invalid modelValue to undefined
38284 if (!allowInvalid && prevValid !== allValid) {
38285 // Note: Don't check ctrl.$valid here, as we could have
38286 // external validators (e.g. calculated on the server),
38287 // that just call $setValidity and need the model value
38288 // to calculate their validity.
38289 ctrl.$modelValue = allValid ? modelValue : undefined;
38291 if (ctrl.$modelValue !== prevModelValue) {
38292 ctrl.$$writeModelToScope();
38299 this.$$runValidators = function(modelValue, viewValue, doneCallback) {
38300 currentValidationRunId++;
38301 var localValidationRunId = currentValidationRunId;
38303 // check parser error
38304 if (!processParseErrors()) {
38305 validationDone(false);
38308 if (!processSyncValidators()) {
38309 validationDone(false);
38312 processAsyncValidators();
38314 function processParseErrors() {
38315 var errorKey = ctrl.$$parserName || 'parse';
38316 if (isUndefined(parserValid)) {
38317 setValidity(errorKey, null);
38319 if (!parserValid) {
38320 forEach(ctrl.$validators, function(v, name) {
38321 setValidity(name, null);
38323 forEach(ctrl.$asyncValidators, function(v, name) {
38324 setValidity(name, null);
38327 // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
38328 setValidity(errorKey, parserValid);
38329 return parserValid;
38334 function processSyncValidators() {
38335 var syncValidatorsValid = true;
38336 forEach(ctrl.$validators, function(validator, name) {
38337 var result = validator(modelValue, viewValue);
38338 syncValidatorsValid = syncValidatorsValid && result;
38339 setValidity(name, result);
38341 if (!syncValidatorsValid) {
38342 forEach(ctrl.$asyncValidators, function(v, name) {
38343 setValidity(name, null);
38350 function processAsyncValidators() {
38351 var validatorPromises = [];
38352 var allValid = true;
38353 forEach(ctrl.$asyncValidators, function(validator, name) {
38354 var promise = validator(modelValue, viewValue);
38355 if (!isPromiseLike(promise)) {
38356 throw ngModelMinErr('nopromise',
38357 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise);
38359 setValidity(name, undefined);
38360 validatorPromises.push(promise.then(function() {
38361 setValidity(name, true);
38364 setValidity(name, false);
38367 if (!validatorPromises.length) {
38368 validationDone(true);
38370 $q.all(validatorPromises).then(function() {
38371 validationDone(allValid);
38376 function setValidity(name, isValid) {
38377 if (localValidationRunId === currentValidationRunId) {
38378 ctrl.$setValidity(name, isValid);
38382 function validationDone(allValid) {
38383 if (localValidationRunId === currentValidationRunId) {
38385 doneCallback(allValid);
38392 * @name ngModel.NgModelController#$commitViewValue
38395 * Commit a pending update to the `$modelValue`.
38397 * Updates may be pending by a debounced event or because the input is waiting for a some future
38398 * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
38399 * usually handles calling this in response to input events.
38401 this.$commitViewValue = function() {
38402 var viewValue = ctrl.$viewValue;
38404 $timeout.cancel(pendingDebounce);
38406 // If the view value has not changed then we should just exit, except in the case where there is
38407 // a native validator on the element. In this case the validation state may have changed even though
38408 // the viewValue has stayed empty.
38409 if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
38412 ctrl.$$updateEmptyClasses(viewValue);
38413 ctrl.$$lastCommittedViewValue = viewValue;
38416 if (ctrl.$pristine) {
38419 this.$$parseAndValidate();
38422 this.$$parseAndValidate = function() {
38423 var viewValue = ctrl.$$lastCommittedViewValue;
38424 var modelValue = viewValue;
38425 parserValid = isUndefined(modelValue) ? undefined : true;
38428 for (var i = 0; i < ctrl.$parsers.length; i++) {
38429 modelValue = ctrl.$parsers[i](modelValue);
38430 if (isUndefined(modelValue)) {
38431 parserValid = false;
38436 if (isNumberNaN(ctrl.$modelValue)) {
38437 // ctrl.$modelValue has not been touched yet...
38438 ctrl.$modelValue = ngModelGet($scope);
38440 var prevModelValue = ctrl.$modelValue;
38441 var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
38442 ctrl.$$rawModelValue = modelValue;
38444 if (allowInvalid) {
38445 ctrl.$modelValue = modelValue;
38446 writeToModelIfNeeded();
38449 // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
38450 // This can happen if e.g. $setViewValue is called from inside a parser
38451 ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
38452 if (!allowInvalid) {
38453 // Note: Don't check ctrl.$valid here, as we could have
38454 // external validators (e.g. calculated on the server),
38455 // that just call $setValidity and need the model value
38456 // to calculate their validity.
38457 ctrl.$modelValue = allValid ? modelValue : undefined;
38458 writeToModelIfNeeded();
38462 function writeToModelIfNeeded() {
38463 if (ctrl.$modelValue !== prevModelValue) {
38464 ctrl.$$writeModelToScope();
38469 this.$$writeModelToScope = function() {
38470 ngModelSet($scope, ctrl.$modelValue);
38471 forEach(ctrl.$viewChangeListeners, function(listener) {
38475 $exceptionHandler(e);
38482 * @name ngModel.NgModelController#$setViewValue
38485 * Update the view value.
38487 * This method should be called when a control wants to change the view value; typically,
38488 * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
38489 * directive calls it when the value of the input changes and {@link ng.directive:select select}
38490 * calls it when an option is selected.
38492 * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
38493 * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
38494 * value sent directly for processing, finally to be applied to `$modelValue` and then the
38495 * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
38496 * in the `$viewChangeListeners` list, are called.
38498 * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
38499 * and the `default` trigger is not listed, all those actions will remain pending until one of the
38500 * `updateOn` events is triggered on the DOM element.
38501 * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
38502 * directive is used with a custom debounce for this particular event.
38503 * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
38504 * is specified, once the timer runs out.
38506 * When used with standard inputs, the view value will always be a string (which is in some cases
38507 * parsed into another type, such as a `Date` object for `input[date]`.)
38508 * However, custom controls might also pass objects to this method. In this case, we should make
38509 * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
38510 * perform a deep watch of objects, it only looks for a change of identity. If you only change
38511 * the property of the object then ngModel will not realize that the object has changed and
38512 * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
38513 * not change properties of the copy once it has been passed to `$setViewValue`.
38514 * Otherwise you may cause the model value on the scope to change incorrectly.
38516 * <div class="alert alert-info">
38517 * In any case, the value passed to the method should always reflect the current value
38518 * of the control. For example, if you are calling `$setViewValue` for an input element,
38519 * you should pass the input DOM value. Otherwise, the control and the scope model become
38520 * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
38521 * the control's DOM value in any way. If we want to change the control's DOM value
38522 * programmatically, we should update the `ngModel` scope expression. Its new value will be
38523 * picked up by the model controller, which will run it through the `$formatters`, `$render` it
38524 * to update the DOM, and finally call `$validate` on it.
38527 * @param {*} value value from the view.
38528 * @param {string} trigger Event that triggered the update.
38530 this.$setViewValue = function(value, trigger) {
38531 ctrl.$viewValue = value;
38532 if (!ctrl.$options || ctrl.$options.updateOnDefault) {
38533 ctrl.$$debounceViewValueCommit(trigger);
38537 this.$$debounceViewValueCommit = function(trigger) {
38538 var debounceDelay = 0,
38539 options = ctrl.$options,
38542 if (options && isDefined(options.debounce)) {
38543 debounce = options.debounce;
38544 if (isNumber(debounce)) {
38545 debounceDelay = debounce;
38546 } else if (isNumber(debounce[trigger])) {
38547 debounceDelay = debounce[trigger];
38548 } else if (isNumber(debounce['default'])) {
38549 debounceDelay = debounce['default'];
38553 $timeout.cancel(pendingDebounce);
38554 if (debounceDelay) {
38555 pendingDebounce = $timeout(function() {
38556 ctrl.$commitViewValue();
38558 } else if ($rootScope.$$phase) {
38559 ctrl.$commitViewValue();
38561 $scope.$apply(function() {
38562 ctrl.$commitViewValue();
38568 // Note: we cannot use a normal scope.$watch as we want to detect the following:
38569 // 1. scope value is 'a'
38570 // 2. user enters 'b'
38571 // 3. ng-change kicks in and reverts scope value to 'a'
38572 // -> scope value did not change since the last digest as
38573 // ng-change executes in apply phase
38574 // 4. view should be changed back to 'a'
38575 $scope.$watch(function ngModelWatch() {
38576 var modelValue = ngModelGet($scope);
38578 // if scope model value and ngModel value are out of sync
38579 // TODO(perf): why not move this to the action fn?
38580 if (modelValue !== ctrl.$modelValue &&
38581 // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
38582 // eslint-disable-next-line no-self-compare
38583 (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
38585 ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
38586 parserValid = undefined;
38588 var formatters = ctrl.$formatters,
38589 idx = formatters.length;
38591 var viewValue = modelValue;
38593 viewValue = formatters[idx](viewValue);
38595 if (ctrl.$viewValue !== viewValue) {
38596 ctrl.$$updateEmptyClasses(viewValue);
38597 ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
38600 // It is possible that model and view value have been updated during render
38601 ctrl.$$runValidators(ctrl.$modelValue, ctrl.$viewValue, noop);
38618 * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
38619 * property on the scope using {@link ngModel.NgModelController NgModelController},
38620 * which is created and exposed by this directive.
38622 * `ngModel` is responsible for:
38624 * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
38626 * - Providing validation behavior (i.e. required, number, email, url).
38627 * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
38628 * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
38629 * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
38630 * - Registering the control with its parent {@link ng.directive:form form}.
38632 * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
38633 * current scope. If the property doesn't already exist on this scope, it will be created
38634 * implicitly and added to the scope.
38636 * For best practices on using `ngModel`, see:
38638 * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
38640 * For basic examples, how to use `ngModel`, see:
38642 * - {@link ng.directive:input input}
38643 * - {@link input[text] text}
38644 * - {@link input[checkbox] checkbox}
38645 * - {@link input[radio] radio}
38646 * - {@link input[number] number}
38647 * - {@link input[email] email}
38648 * - {@link input[url] url}
38649 * - {@link input[date] date}
38650 * - {@link input[datetime-local] datetime-local}
38651 * - {@link input[time] time}
38652 * - {@link input[month] month}
38653 * - {@link input[week] week}
38654 * - {@link ng.directive:select select}
38655 * - {@link ng.directive:textarea textarea}
38657 * # Complex Models (objects or collections)
38659 * By default, `ngModel` watches the model by reference, not value. This is important to know when
38660 * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
38661 * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
38663 * The model must be assigned an entirely new object or collection before a re-rendering will occur.
38665 * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
38666 * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
38667 * if the select is given the `multiple` attribute.
38669 * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
38670 * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
38671 * not trigger a re-rendering of the model.
38674 * The following CSS classes are added and removed on the associated input/select/textarea element
38675 * depending on the validity of the model.
38677 * - `ng-valid`: the model is valid
38678 * - `ng-invalid`: the model is invalid
38679 * - `ng-valid-[key]`: for each valid key added by `$setValidity`
38680 * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
38681 * - `ng-pristine`: the control hasn't been interacted with yet
38682 * - `ng-dirty`: the control has been interacted with
38683 * - `ng-touched`: the control has been blurred
38684 * - `ng-untouched`: the control hasn't been blurred
38685 * - `ng-pending`: any `$asyncValidators` are unfulfilled
38686 * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
38687 * by the {@link ngModel.NgModelController#$isEmpty} method
38688 * - `ng-not-empty`: the view contains a non-empty value
38690 * Keep in mind that ngAnimate can detect each of these classes when added and removed.
38692 * ## Animation Hooks
38694 * Animations within models are triggered when any of the associated CSS classes are added and removed
38695 * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
38696 * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
38697 * The animations that are triggered within ngModel are similar to how they work in ngClass and
38698 * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
38700 * The following example shows a simple way to utilize CSS transitions to style an input element
38701 * that has been rendered as invalid after it has been validated:
38704 * //be sure to include ngAnimate as a module to hook into more
38705 * //advanced animations
38707 * transition:0.5s linear all;
38708 * background: white;
38710 * .my-input.ng-invalid {
38717 * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model">
38718 <file name="index.html">
38720 angular.module('inputExample', [])
38721 .controller('ExampleController', ['$scope', function($scope) {
38727 transition:all linear 0.5s;
38728 background: transparent;
38730 .my-input.ng-invalid {
38735 <p id="inputDescription">
38736 Update input to see transitions when valid/invalid.
38737 Integer is a valid value.
38739 <form name="testForm" ng-controller="ExampleController">
38740 <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
38741 aria-describedby="inputDescription" />
38746 * ## Binding to a getter/setter
38748 * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
38749 * function that returns a representation of the model when called with zero arguments, and sets
38750 * the internal state of a model when called with an argument. It's sometimes useful to use this
38751 * for models that have an internal representation that's different from what the model exposes
38754 * <div class="alert alert-success">
38755 * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
38756 * frequently than other parts of your code.
38759 * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
38760 * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
38761 * a `<form>`, which will enable this behavior for all `<input>`s within it. See
38762 * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
38764 * The following example shows how to use `ngModel` with a getter/setter:
38767 * <example name="ngModel-getter-setter" module="getterSetterExample">
38768 <file name="index.html">
38769 <div ng-controller="ExampleController">
38770 <form name="userForm">
38772 <input type="text" name="userName"
38773 ng-model="user.name"
38774 ng-model-options="{ getterSetter: true }" />
38777 <pre>user.name = <span ng-bind="user.name()"></span></pre>
38780 <file name="app.js">
38781 angular.module('getterSetterExample', [])
38782 .controller('ExampleController', ['$scope', function($scope) {
38783 var _name = 'Brian';
38785 name: function(newName) {
38786 // Note that newName can be undefined for two reasons:
38787 // 1. Because it is called as a getter and thus called with no arguments
38788 // 2. Because the property should actually be set to undefined. This happens e.g. if the
38789 // input is invalid
38790 return arguments.length ? (_name = newName) : _name;
38797 var ngModelDirective = ['$rootScope', function($rootScope) {
38800 require: ['ngModel', '^?form', '^?ngModelOptions'],
38801 controller: NgModelController,
38802 // Prelink needs to run before any input directive
38803 // so that we can set the NgModelOptions in NgModelController
38804 // before anyone else uses it.
38806 compile: function ngModelCompile(element) {
38807 // Setup initial state of the control
38808 element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
38811 pre: function ngModelPreLink(scope, element, attr, ctrls) {
38812 var modelCtrl = ctrls[0],
38813 formCtrl = ctrls[1] || modelCtrl.$$parentForm;
38815 modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
38817 // notify others, especially parent forms
38818 formCtrl.$addControl(modelCtrl);
38820 attr.$observe('name', function(newValue) {
38821 if (modelCtrl.$name !== newValue) {
38822 modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
38826 scope.$on('$destroy', function() {
38827 modelCtrl.$$parentForm.$removeControl(modelCtrl);
38830 post: function ngModelPostLink(scope, element, attr, ctrls) {
38831 var modelCtrl = ctrls[0];
38832 if (modelCtrl.$options && modelCtrl.$options.updateOn) {
38833 element.on(modelCtrl.$options.updateOn, function(ev) {
38834 modelCtrl.$$debounceViewValueCommit(ev && ev.type);
38838 element.on('blur', function() {
38839 if (modelCtrl.$touched) return;
38841 if ($rootScope.$$phase) {
38842 scope.$evalAsync(modelCtrl.$setTouched);
38844 scope.$apply(modelCtrl.$setTouched);
38855 var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
38859 * @name ngModelOptions
38862 * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
38863 * events that will trigger a model update and/or a debouncing delay so that the actual update only
38864 * takes place when a timer expires; this timer will be reset after another change takes place.
38866 * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
38867 * be different from the value in the actual model. This means that if you update the model you
38868 * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
38869 * order to make sure it is synchronized with the model and that any debounced action is canceled.
38871 * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
38872 * method is by making sure the input is placed inside a form that has a `name` attribute. This is
38873 * important because `form` controllers are published to the related scope under the name in their
38874 * `name` attribute.
38876 * Any pending changes will take place immediately when an enclosing form is submitted via the
38877 * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
38878 * to have access to the updated model.
38880 * `ngModelOptions` has an effect on the element it's declared on and its descendants.
38882 * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
38883 * - `updateOn`: string specifying which event should the input be bound to. You can set several
38884 * events using an space delimited list. There is a special event called `default` that
38885 * matches the default events belonging of the control.
38886 * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
38887 * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
38888 * custom value for each event. For example:
38889 * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
38890 * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
38891 * not validate correctly instead of the default behavior of setting the model to undefined.
38892 * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
38893 `ngModel` as getters/setters.
38894 * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
38895 * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
38896 * continental US time zone abbreviations, but for general use, use a time zone offset, for
38897 * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
38898 * If not specified, the timezone of the browser will be used.
38902 The following example shows how to override immediate updates. Changes on the inputs within the
38903 form will update the model only when the control loses focus (blur event). If `escape` key is
38904 pressed while the input field is focused, the value is reset to the value in the current model.
38906 <example name="ngModelOptions-directive-blur" module="optionsExample">
38907 <file name="index.html">
38908 <div ng-controller="ExampleController">
38909 <form name="userForm">
38911 <input type="text" name="userName"
38912 ng-model="user.name"
38913 ng-model-options="{ updateOn: 'blur' }"
38914 ng-keyup="cancel($event)" />
38917 <input type="text" ng-model="user.data" />
38920 <pre>user.name = <span ng-bind="user.name"></span></pre>
38921 <pre>user.data = <span ng-bind="user.data"></span></pre>
38924 <file name="app.js">
38925 angular.module('optionsExample', [])
38926 .controller('ExampleController', ['$scope', function($scope) {
38927 $scope.user = { name: 'John', data: '' };
38929 $scope.cancel = function(e) {
38930 if (e.keyCode === 27) {
38931 $scope.userForm.userName.$rollbackViewValue();
38936 <file name="protractor.js" type="protractor">
38937 var model = element(by.binding('user.name'));
38938 var input = element(by.model('user.name'));
38939 var other = element(by.model('user.data'));
38941 it('should allow custom events', function() {
38942 input.sendKeys(' Doe');
38944 expect(model.getText()).toEqual('John');
38946 expect(model.getText()).toEqual('John Doe');
38949 it('should $rollbackViewValue when model changes', function() {
38950 input.sendKeys(' Doe');
38951 expect(input.getAttribute('value')).toEqual('John Doe');
38952 input.sendKeys(protractor.Key.ESCAPE);
38953 expect(input.getAttribute('value')).toEqual('John');
38955 expect(model.getText()).toEqual('John');
38960 This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
38961 If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
38963 <example name="ngModelOptions-directive-debounce" module="optionsExample">
38964 <file name="index.html">
38965 <div ng-controller="ExampleController">
38966 <form name="userForm">
38968 <input type="text" name="userName"
38969 ng-model="user.name"
38970 ng-model-options="{ debounce: 1000 }" />
38972 <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
38975 <pre>user.name = <span ng-bind="user.name"></span></pre>
38978 <file name="app.js">
38979 angular.module('optionsExample', [])
38980 .controller('ExampleController', ['$scope', function($scope) {
38981 $scope.user = { name: 'Igor' };
38986 This one shows how to bind to getter/setters:
38988 <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
38989 <file name="index.html">
38990 <div ng-controller="ExampleController">
38991 <form name="userForm">
38993 <input type="text" name="userName"
38994 ng-model="user.name"
38995 ng-model-options="{ getterSetter: true }" />
38998 <pre>user.name = <span ng-bind="user.name()"></span></pre>
39001 <file name="app.js">
39002 angular.module('getterSetterExample', [])
39003 .controller('ExampleController', ['$scope', function($scope) {
39004 var _name = 'Brian';
39006 name: function(newName) {
39007 // Note that newName can be undefined for two reasons:
39008 // 1. Because it is called as a getter and thus called with no arguments
39009 // 2. Because the property should actually be set to undefined. This happens e.g. if the
39010 // input is invalid
39011 return arguments.length ? (_name = newName) : _name;
39018 var ngModelOptionsDirective = function() {
39021 controller: ['$scope', '$attrs', function NgModelOptionsController($scope, $attrs) {
39023 this.$options = copy($scope.$eval($attrs.ngModelOptions));
39024 // Allow adding/overriding bound events
39025 if (isDefined(this.$options.updateOn)) {
39026 this.$options.updateOnDefault = false;
39027 // extract "default" pseudo-event from list of events that can trigger a model update
39028 this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
39029 that.$options.updateOnDefault = true;
39033 this.$options.updateOnDefault = true;
39042 function addSetValidityMethod(context) {
39043 var ctrl = context.ctrl,
39044 $element = context.$element,
39047 unset = context.unset,
39048 $animate = context.$animate;
39050 classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
39052 ctrl.$setValidity = setValidity;
39054 function setValidity(validationErrorKey, state, controller) {
39055 if (isUndefined(state)) {
39056 createAndSet('$pending', validationErrorKey, controller);
39058 unsetAndCleanup('$pending', validationErrorKey, controller);
39060 if (!isBoolean(state)) {
39061 unset(ctrl.$error, validationErrorKey, controller);
39062 unset(ctrl.$$success, validationErrorKey, controller);
39065 unset(ctrl.$error, validationErrorKey, controller);
39066 set(ctrl.$$success, validationErrorKey, controller);
39068 set(ctrl.$error, validationErrorKey, controller);
39069 unset(ctrl.$$success, validationErrorKey, controller);
39072 if (ctrl.$pending) {
39073 cachedToggleClass(PENDING_CLASS, true);
39074 ctrl.$valid = ctrl.$invalid = undefined;
39075 toggleValidationCss('', null);
39077 cachedToggleClass(PENDING_CLASS, false);
39078 ctrl.$valid = isObjectEmpty(ctrl.$error);
39079 ctrl.$invalid = !ctrl.$valid;
39080 toggleValidationCss('', ctrl.$valid);
39083 // re-read the state as the set/unset methods could have
39084 // combined state in ctrl.$error[validationError] (used for forms),
39085 // where setting/unsetting only increments/decrements the value,
39086 // and does not replace it.
39088 if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
39089 combinedState = undefined;
39090 } else if (ctrl.$error[validationErrorKey]) {
39091 combinedState = false;
39092 } else if (ctrl.$$success[validationErrorKey]) {
39093 combinedState = true;
39095 combinedState = null;
39098 toggleValidationCss(validationErrorKey, combinedState);
39099 ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
39102 function createAndSet(name, value, controller) {
39106 set(ctrl[name], value, controller);
39109 function unsetAndCleanup(name, value, controller) {
39111 unset(ctrl[name], value, controller);
39113 if (isObjectEmpty(ctrl[name])) {
39114 ctrl[name] = undefined;
39118 function cachedToggleClass(className, switchValue) {
39119 if (switchValue && !classCache[className]) {
39120 $animate.addClass($element, className);
39121 classCache[className] = true;
39122 } else if (!switchValue && classCache[className]) {
39123 $animate.removeClass($element, className);
39124 classCache[className] = false;
39128 function toggleValidationCss(validationErrorKey, isValid) {
39129 validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
39131 cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
39132 cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
39136 function isObjectEmpty(obj) {
39138 for (var prop in obj) {
39139 if (obj.hasOwnProperty(prop)) {
39149 * @name ngNonBindable
39154 * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
39155 * DOM element. This is useful if the element contains what appears to be Angular directives and
39156 * bindings but which should be ignored by Angular. This could be the case if you have a site that
39157 * displays snippets of code, for instance.
39162 * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
39163 * but the one wrapped in `ngNonBindable` is left alone.
39166 <example name="ng-non-bindable">
39167 <file name="index.html">
39168 <div>Normal: {{1 + 2}}</div>
39169 <div ng-non-bindable>Ignored: {{1 + 2}}</div>
39171 <file name="protractor.js" type="protractor">
39172 it('should check ng-non-bindable', function() {
39173 expect(element(by.binding('1 + 2')).getText()).toContain('3');
39174 expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
39179 var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
39181 /* exported ngOptionsDirective */
39183 /* global jqLiteRemove */
39185 var ngOptionsMinErr = minErr('ngOptions');
39194 * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
39195 * elements for the `<select>` element using the array or object obtained by evaluating the
39196 * `ngOptions` comprehension expression.
39198 * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `<option>` elements
39199 * instead of `ngOptions` to achieve a similar result.
39200 * However, `ngOptions` provides some benefits such as reducing memory and
39201 * increasing speed by not creating a new scope for each repeated instance, as well as providing
39202 * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
39203 * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
39204 * to a non-string value. This is because an option element can only be bound to string values at
39207 * When an item in the `<select>` menu is selected, the array element or object property
39208 * represented by the selected option will be bound to the model identified by the `ngModel`
39211 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
39212 * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
39213 * option. See example below for demonstration.
39215 * ## Complex Models (objects or collections)
39217 * By default, `ngModel` watches the model by reference, not value. This is important to know when
39218 * binding the select to a model that is an object or a collection.
39220 * One issue occurs if you want to preselect an option. For example, if you set
39221 * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
39222 * because the objects are not identical. So by default, you should always reference the item in your collection
39223 * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
39225 * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
39226 * of the item not by reference, but by the result of the `track by` expression. For example, if your
39227 * collection items have an id property, you would `track by item.id`.
39229 * A different issue with objects or collections is that ngModel won't detect if an object property or
39230 * a collection item changes. For that reason, `ngOptions` additionally watches the model using
39231 * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
39232 * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
39233 * has not changed identity, but only a property on the object or an item in the collection changes.
39235 * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
39236 * if the model is an array). This means that changing a property deeper than the first level inside the
39237 * object/collection will not trigger a re-rendering.
39239 * ## `select` **`as`**
39241 * Using `select` **`as`** will bind the result of the `select` expression to the model, but
39242 * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
39243 * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
39244 * is used, the result of that expression will be set as the value of the `option` and `select` elements.
39247 * ### `select` **`as`** and **`track by`**
39249 * <div class="alert alert-warning">
39250 * Be careful when using `select` **`as`** and **`track by`** in the same expression.
39253 * Given this array of items on the $scope:
39256 * $scope.items = [{
39259 * subItem: { name: 'aSubItem' }
39263 * subItem: { name: 'bSubItem' }
39270 * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
39273 * $scope.selected = $scope.items[0];
39276 * but this will not work:
39279 * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
39282 * $scope.selected = $scope.items[0].subItem;
39285 * In both examples, the **`track by`** expression is applied successfully to each `item` in the
39286 * `items` array. Because the selected option has been set programmatically in the controller, the
39287 * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
39288 * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
39289 * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
39290 * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
39291 * is not matched against any `<option>` and the `<select>` appears as having no selected value.
39294 * @param {string} ngModel Assignable angular expression to data-bind to.
39295 * @param {string=} name Property name of the form under which the control is published.
39296 * @param {string=} required The control is considered valid only if value is entered.
39297 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
39298 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
39299 * `required` when you want to data-bind to the `required` attribute.
39300 * @param {comprehension_expression=} ngOptions in one of the following forms:
39302 * * for array data sources:
39303 * * `label` **`for`** `value` **`in`** `array`
39304 * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
39305 * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
39306 * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
39307 * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
39308 * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
39309 * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
39310 * (for including a filter with `track by`)
39311 * * for object data sources:
39312 * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
39313 * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
39314 * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
39315 * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
39316 * * `select` **`as`** `label` **`group by`** `group`
39317 * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
39318 * * `select` **`as`** `label` **`disable when`** `disable`
39319 * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
39323 * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
39324 * * `value`: local variable which will refer to each item in the `array` or each property value
39325 * of `object` during iteration.
39326 * * `key`: local variable which will refer to a property name in `object` during iteration.
39327 * * `label`: The result of this expression will be the label for `<option>` element. The
39328 * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
39329 * * `select`: The result of this expression will be bound to the model of the parent `<select>`
39330 * element. If not specified, `select` expression will default to `value`.
39331 * * `group`: The result of this expression will be used to group options using the `<optgroup>`
39333 * * `disable`: The result of this expression will be used to disable the rendered `<option>`
39334 * element. Return `true` to disable.
39335 * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
39336 * used to identify the objects in the array. The `trackexpr` will most likely refer to the
39337 * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
39338 * even when the options are recreated (e.g. reloaded from the server).
39341 <example module="selectExample" name="select">
39342 <file name="index.html">
39344 angular.module('selectExample', [])
39345 .controller('ExampleController', ['$scope', function($scope) {
39347 {name:'black', shade:'dark'},
39348 {name:'white', shade:'light', notAnOption: true},
39349 {name:'red', shade:'dark'},
39350 {name:'blue', shade:'dark', notAnOption: true},
39351 {name:'yellow', shade:'light', notAnOption: false}
39353 $scope.myColor = $scope.colors[2]; // red
39356 <div ng-controller="ExampleController">
39358 <li ng-repeat="color in colors">
39359 <label>Name: <input ng-model="color.name"></label>
39360 <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
39361 <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
39364 <button ng-click="colors.push({})">add</button>
39368 <label>Color (null not allowed):
39369 <select ng-model="myColor" ng-options="color.name for color in colors"></select>
39371 <label>Color (null allowed):
39372 <span class="nullable">
39373 <select ng-model="myColor" ng-options="color.name for color in colors">
39374 <option value="">-- choose color --</option>
39376 </span></label><br/>
39378 <label>Color grouped by shade:
39379 <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
39383 <label>Color grouped by shade, with some disabled:
39384 <select ng-model="myColor"
39385 ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
39391 Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
39394 Currently selected: {{ {selected_color:myColor} }}
39395 <div style="border:solid 1px black; height:20px"
39396 ng-style="{'background-color':myColor.name}">
39400 <file name="protractor.js" type="protractor">
39401 it('should check ng-options', function() {
39402 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
39403 element.all(by.model('myColor')).first().click();
39404 element.all(by.css('select[ng-model="myColor"] option')).first().click();
39405 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
39406 element(by.css('.nullable select[ng-model="myColor"]')).click();
39407 element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
39408 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
39414 /* eslint-disable max-len */
39415 // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555000000000666666666666600000007777777777777000000000000000888888888800000000000000000009999999999
39416 var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([$\w][$\w]*)|(?:\(\s*([$\w][$\w]*)\s*,\s*([$\w][$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
39417 // 1: value expression (valueFn)
39418 // 2: label expression (displayFn)
39419 // 3: group by expression (groupByFn)
39420 // 4: disable when expression (disableWhenFn)
39421 // 5: array item variable name
39422 // 6: object item key variable name
39423 // 7: object item value variable name
39424 // 8: collection expression
39425 // 9: track by expression
39426 /* eslint-enable */
39429 var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
39431 function parseOptionsExpression(optionsExp, selectElement, scope) {
39433 var match = optionsExp.match(NG_OPTIONS_REGEXP);
39435 throw ngOptionsMinErr('iexp',
39436 'Expected expression in form of ' +
39437 '\'_select_ (as _label_)? for (_key_,)?_value_ in _collection_\'' +
39438 ' but got \'{0}\'. Element: {1}',
39439 optionsExp, startingTag(selectElement));
39442 // Extract the parts from the ngOptions expression
39444 // The variable name for the value of the item in the collection
39445 var valueName = match[5] || match[7];
39446 // The variable name for the key of the item in the collection
39447 var keyName = match[6];
39449 // An expression that generates the viewValue for an option if there is a label expression
39450 var selectAs = / as /.test(match[0]) && match[1];
39451 // An expression that is used to track the id of each object in the options collection
39452 var trackBy = match[9];
39453 // An expression that generates the viewValue for an option if there is no label expression
39454 var valueFn = $parse(match[2] ? match[1] : valueName);
39455 var selectAsFn = selectAs && $parse(selectAs);
39456 var viewValueFn = selectAsFn || valueFn;
39457 var trackByFn = trackBy && $parse(trackBy);
39459 // Get the value by which we are going to track the option
39460 // if we have a trackFn then use that (passing scope and locals)
39461 // otherwise just hash the given viewValue
39462 var getTrackByValueFn = trackBy ?
39463 function(value, locals) { return trackByFn(scope, locals); } :
39464 function getHashOfValue(value) { return hashKey(value); };
39465 var getTrackByValue = function(value, key) {
39466 return getTrackByValueFn(value, getLocals(value, key));
39469 var displayFn = $parse(match[2] || match[1]);
39470 var groupByFn = $parse(match[3] || '');
39471 var disableWhenFn = $parse(match[4] || '');
39472 var valuesFn = $parse(match[8]);
39475 var getLocals = keyName ? function(value, key) {
39476 locals[keyName] = key;
39477 locals[valueName] = value;
39479 } : function(value) {
39480 locals[valueName] = value;
39485 function Option(selectValue, viewValue, label, group, disabled) {
39486 this.selectValue = selectValue;
39487 this.viewValue = viewValue;
39488 this.label = label;
39489 this.group = group;
39490 this.disabled = disabled;
39493 function getOptionValuesKeys(optionValues) {
39494 var optionValuesKeys;
39496 if (!keyName && isArrayLike(optionValues)) {
39497 optionValuesKeys = optionValues;
39499 // if object, extract keys, in enumeration order, unsorted
39500 optionValuesKeys = [];
39501 for (var itemKey in optionValues) {
39502 if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
39503 optionValuesKeys.push(itemKey);
39507 return optionValuesKeys;
39512 getTrackByValue: getTrackByValue,
39513 getWatchables: $parse(valuesFn, function(optionValues) {
39514 // Create a collection of things that we would like to watch (watchedArray)
39515 // so that they can all be watched using a single $watchCollection
39516 // that only runs the handler once if anything changes
39517 var watchedArray = [];
39518 optionValues = optionValues || [];
39520 var optionValuesKeys = getOptionValuesKeys(optionValues);
39521 var optionValuesLength = optionValuesKeys.length;
39522 for (var index = 0; index < optionValuesLength; index++) {
39523 var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
39524 var value = optionValues[key];
39526 var locals = getLocals(value, key);
39527 var selectValue = getTrackByValueFn(value, locals);
39528 watchedArray.push(selectValue);
39530 // Only need to watch the displayFn if there is a specific label expression
39531 if (match[2] || match[1]) {
39532 var label = displayFn(scope, locals);
39533 watchedArray.push(label);
39536 // Only need to watch the disableWhenFn if there is a specific disable expression
39538 var disableWhen = disableWhenFn(scope, locals);
39539 watchedArray.push(disableWhen);
39542 return watchedArray;
39545 getOptions: function() {
39547 var optionItems = [];
39548 var selectValueMap = {};
39550 // The option values were already computed in the `getWatchables` fn,
39551 // which must have been called to trigger `getOptions`
39552 var optionValues = valuesFn(scope) || [];
39553 var optionValuesKeys = getOptionValuesKeys(optionValues);
39554 var optionValuesLength = optionValuesKeys.length;
39556 for (var index = 0; index < optionValuesLength; index++) {
39557 var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
39558 var value = optionValues[key];
39559 var locals = getLocals(value, key);
39560 var viewValue = viewValueFn(scope, locals);
39561 var selectValue = getTrackByValueFn(viewValue, locals);
39562 var label = displayFn(scope, locals);
39563 var group = groupByFn(scope, locals);
39564 var disabled = disableWhenFn(scope, locals);
39565 var optionItem = new Option(selectValue, viewValue, label, group, disabled);
39567 optionItems.push(optionItem);
39568 selectValueMap[selectValue] = optionItem;
39572 items: optionItems,
39573 selectValueMap: selectValueMap,
39574 getOptionFromViewValue: function(value) {
39575 return selectValueMap[getTrackByValue(value)];
39577 getViewValueFromOption: function(option) {
39578 // If the viewValue could be an object that may be mutated by the application,
39579 // we need to make a copy and not return the reference to the value on the option.
39580 return trackBy ? copy(option.viewValue) : option.viewValue;
39588 // we can't just jqLite('<option>') since jqLite is not smart enough
39589 // to create it in <select> and IE barfs otherwise.
39590 var optionTemplate = window.document.createElement('option'),
39591 optGroupTemplate = window.document.createElement('optgroup');
39593 function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
39595 var selectCtrl = ctrls[0];
39596 var ngModelCtrl = ctrls[1];
39597 var multiple = attr.multiple;
39599 // The emptyOption allows the application developer to provide their own custom "empty"
39600 // option when the viewValue does not match any of the option values.
39602 for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
39603 if (children[i].value === '') {
39604 emptyOption = children.eq(i);
39609 var providedEmptyOption = !!emptyOption;
39610 var emptyOptionRendered = false;
39612 var unknownOption = jqLite(optionTemplate.cloneNode(false));
39613 unknownOption.val('?');
39616 var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
39617 // This stores the newly created options before they are appended to the select.
39618 // Since the contents are removed from the fragment when it is appended,
39619 // we only need to create it once.
39620 var listFragment = $document[0].createDocumentFragment();
39622 var renderEmptyOption = function() {
39623 if (!providedEmptyOption) {
39624 selectElement.prepend(emptyOption);
39626 selectElement.val('');
39627 if (emptyOptionRendered) {
39628 emptyOption.prop('selected', true); // needed for IE
39629 emptyOption.attr('selected', true);
39633 var removeEmptyOption = function() {
39634 if (!providedEmptyOption) {
39635 emptyOption.remove();
39636 } else if (emptyOptionRendered) {
39637 emptyOption.removeAttr('selected');
39641 var renderUnknownOption = function() {
39642 selectElement.prepend(unknownOption);
39643 selectElement.val('?');
39644 unknownOption.prop('selected', true); // needed for IE
39645 unknownOption.attr('selected', true);
39648 var removeUnknownOption = function() {
39649 unknownOption.remove();
39652 // Update the controller methods for multiple selectable options
39655 selectCtrl.writeValue = function writeNgOptionsValue(value) {
39656 var selectedOption = options.selectValueMap[selectElement.val()];
39657 var option = options.getOptionFromViewValue(value);
39659 // Make sure to remove the selected attribute from the previously selected option
39660 // Otherwise, screen readers might get confused
39661 if (selectedOption) selectedOption.element.removeAttribute('selected');
39664 // Don't update the option when it is already selected.
39665 // For example, the browser will select the first option by default. In that case,
39666 // most properties are set automatically - except the `selected` attribute, which we
39669 if (selectElement[0].value !== option.selectValue) {
39670 removeUnknownOption();
39671 removeEmptyOption();
39673 selectElement[0].value = option.selectValue;
39674 option.element.selected = true;
39677 option.element.setAttribute('selected', 'selected');
39679 if (value === null || providedEmptyOption) {
39680 removeUnknownOption();
39681 renderEmptyOption();
39683 removeEmptyOption();
39684 renderUnknownOption();
39689 selectCtrl.readValue = function readNgOptionsValue() {
39691 var selectedOption = options.selectValueMap[selectElement.val()];
39693 if (selectedOption && !selectedOption.disabled) {
39694 removeEmptyOption();
39695 removeUnknownOption();
39696 return options.getViewValueFromOption(selectedOption);
39701 // If we are using `track by` then we must watch the tracked value on the model
39702 // since ngModel only watches for object identity change
39703 // FIXME: When a user selects an option, this watch will fire needlessly
39704 if (ngOptions.trackBy) {
39706 function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
39707 function() { ngModelCtrl.$render(); }
39713 ngModelCtrl.$isEmpty = function(value) {
39714 return !value || value.length === 0;
39718 selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
39719 options.items.forEach(function(option) {
39720 option.element.selected = false;
39724 value.forEach(function(item) {
39725 var option = options.getOptionFromViewValue(item);
39726 if (option) option.element.selected = true;
39732 selectCtrl.readValue = function readNgOptionsMultiple() {
39733 var selectedValues = selectElement.val() || [],
39736 forEach(selectedValues, function(value) {
39737 var option = options.selectValueMap[value];
39738 if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
39744 // If we are using `track by` then we must watch these tracked values on the model
39745 // since ngModel only watches for object identity change
39746 if (ngOptions.trackBy) {
39748 scope.$watchCollection(function() {
39749 if (isArray(ngModelCtrl.$viewValue)) {
39750 return ngModelCtrl.$viewValue.map(function(value) {
39751 return ngOptions.getTrackByValue(value);
39755 ngModelCtrl.$render();
39762 if (providedEmptyOption) {
39764 // we need to remove it before calling selectElement.empty() because otherwise IE will
39765 // remove the label from the element. wtf?
39766 emptyOption.remove();
39768 // compile the element since there might be bindings in it
39769 $compile(emptyOption)(scope);
39771 if (emptyOption[0].nodeType === NODE_TYPE_COMMENT) {
39772 // This means the empty option has currently no actual DOM node, probably because
39773 // it has been modified by a transclusion directive.
39775 emptyOptionRendered = false;
39777 // Redefine the registerOption function, which will catch
39778 // options that are added by ngIf etc. (rendering of the node is async because of
39779 // lazy transclusion)
39780 selectCtrl.registerOption = function(optionScope, optionEl) {
39781 if (optionEl.val() === '') {
39782 emptyOptionRendered = true;
39783 emptyOption = optionEl;
39784 emptyOption.removeClass('ng-scope');
39785 // This ensures the new empty option is selected if previously no option was selected
39786 ngModelCtrl.$render();
39788 optionEl.on('$destroy', function() {
39789 emptyOption = undefined;
39790 emptyOptionRendered = false;
39796 emptyOption.removeClass('ng-scope');
39797 emptyOptionRendered = true;
39801 emptyOption = jqLite(optionTemplate.cloneNode(false));
39804 selectElement.empty();
39806 // We need to do this here to ensure that the options object is defined
39807 // when we first hit it in writeNgOptionsValue
39810 // We will re-render the option elements if the option values or labels change
39811 scope.$watchCollection(ngOptions.getWatchables, updateOptions);
39813 // ------------------------------------------------------------------ //
39815 function addOptionElement(option, parent) {
39816 var optionElement = optionTemplate.cloneNode(false);
39817 parent.appendChild(optionElement);
39818 updateOptionElement(option, optionElement);
39822 function updateOptionElement(option, element) {
39823 option.element = element;
39824 element.disabled = option.disabled;
39825 // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
39826 // selects in certain circumstances when multiple selects are next to each other and display
39827 // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
39828 // See https://github.com/angular/angular.js/issues/11314 for more info.
39829 // This is unfortunately untestable with unit / e2e tests
39830 if (option.label !== element.label) {
39831 element.label = option.label;
39832 element.textContent = option.label;
39834 element.value = option.selectValue;
39837 function updateOptions() {
39838 var previousValue = options && selectCtrl.readValue();
39840 // We must remove all current options, but cannot simply set innerHTML = null
39841 // since the providedEmptyOption might have an ngIf on it that inserts comments which we
39843 // Instead, iterate over the current option elements and remove them or their optgroup
39847 for (var i = options.items.length - 1; i >= 0; i--) {
39848 var option = options.items[i];
39849 if (isDefined(option.group)) {
39850 jqLiteRemove(option.element.parentNode);
39852 jqLiteRemove(option.element);
39857 options = ngOptions.getOptions();
39859 var groupElementMap = {};
39861 // Ensure that the empty option is always there if it was explicitly provided
39862 if (providedEmptyOption) {
39863 selectElement.prepend(emptyOption);
39866 options.items.forEach(function addOption(option) {
39869 if (isDefined(option.group)) {
39871 // This option is to live in a group
39872 // See if we have already created this group
39873 groupElement = groupElementMap[option.group];
39875 if (!groupElement) {
39877 groupElement = optGroupTemplate.cloneNode(false);
39878 listFragment.appendChild(groupElement);
39880 // Update the label on the group element
39881 // "null" is special cased because of Safari
39882 groupElement.label = option.group === null ? 'null' : option.group;
39884 // Store it for use later
39885 groupElementMap[option.group] = groupElement;
39888 addOptionElement(option, groupElement);
39892 // This option is not in a group
39893 addOptionElement(option, listFragment);
39897 selectElement[0].appendChild(listFragment);
39899 ngModelCtrl.$render();
39901 // Check to see if the value has changed due to the update to the options
39902 if (!ngModelCtrl.$isEmpty(previousValue)) {
39903 var nextValue = selectCtrl.readValue();
39904 var isNotPrimitive = ngOptions.trackBy || multiple;
39905 if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
39906 ngModelCtrl.$setViewValue(nextValue);
39907 ngModelCtrl.$render();
39917 require: ['select', 'ngModel'],
39919 pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
39920 // Deactivate the SelectController.register method to prevent
39921 // option directives from accidentally registering themselves
39922 // (and unwanted $destroy handlers etc.)
39923 ctrls[0].registerOption = noop;
39925 post: ngOptionsPostLink
39932 * @name ngPluralize
39936 * `ngPluralize` is a directive that displays messages according to en-US localization rules.
39937 * These rules are bundled with angular.js, but can be overridden
39938 * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
39939 * by specifying the mappings between
39940 * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
39941 * and the strings to be displayed.
39943 * # Plural categories and explicit number rules
39945 * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
39946 * in Angular's default en-US locale: "one" and "other".
39948 * While a plural category may match many numbers (for example, in en-US locale, "other" can match
39949 * any number that is not 1), an explicit number rule can only match one number. For example, the
39950 * explicit number rule for "3" matches the number 3. There are examples of plural categories
39951 * and explicit number rules throughout the rest of this documentation.
39953 * # Configuring ngPluralize
39954 * You configure ngPluralize by providing 2 attributes: `count` and `when`.
39955 * You can also provide an optional attribute, `offset`.
39957 * The value of the `count` attribute can be either a string or an {@link guide/expression
39958 * Angular expression}; these are evaluated on the current scope for its bound value.
39960 * The `when` attribute specifies the mappings between plural categories and the actual
39961 * string to be displayed. The value of the attribute should be a JSON object.
39963 * The following example shows how to configure ngPluralize:
39966 * <ng-pluralize count="personCount"
39967 when="{'0': 'Nobody is viewing.',
39968 * 'one': '1 person is viewing.',
39969 * 'other': '{} people are viewing.'}">
39973 * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
39974 * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
39975 * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
39976 * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
39977 * show "a dozen people are viewing".
39979 * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
39980 * into pluralized strings. In the previous example, Angular will replace `{}` with
39981 * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
39982 * for <span ng-non-bindable>{{numberExpression}}</span>.
39984 * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
39985 * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
39987 * # Configuring ngPluralize with offset
39988 * The `offset` attribute allows further customization of pluralized text, which can result in
39989 * a better user experience. For example, instead of the message "4 people are viewing this document",
39990 * you might display "John, Kate and 2 others are viewing this document".
39991 * The offset attribute allows you to offset a number by any desired value.
39992 * Let's take a look at an example:
39995 * <ng-pluralize count="personCount" offset=2
39996 * when="{'0': 'Nobody is viewing.',
39997 * '1': '{{person1}} is viewing.',
39998 * '2': '{{person1}} and {{person2}} are viewing.',
39999 * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
40000 * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
40004 * Notice that we are still using two plural categories(one, other), but we added
40005 * three explicit number rules 0, 1 and 2.
40006 * When one person, perhaps John, views the document, "John is viewing" will be shown.
40007 * When three people view the document, no explicit number rule is found, so
40008 * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
40009 * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
40012 * Note that when you specify offsets, you must provide explicit number rules for
40013 * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
40014 * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
40015 * plural categories "one" and "other".
40017 * @param {string|expression} count The variable to be bound to.
40018 * @param {string} when The mapping between plural category to its corresponding strings.
40019 * @param {number=} offset Offset to deduct from the total number.
40022 <example module="pluralizeExample" name="ng-pluralize">
40023 <file name="index.html">
40025 angular.module('pluralizeExample', [])
40026 .controller('ExampleController', ['$scope', function($scope) {
40027 $scope.person1 = 'Igor';
40028 $scope.person2 = 'Misko';
40029 $scope.personCount = 1;
40032 <div ng-controller="ExampleController">
40033 <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
40034 <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
40035 <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
40037 <!--- Example with simple pluralization rules for en locale --->
40039 <ng-pluralize count="personCount"
40040 when="{'0': 'Nobody is viewing.',
40041 'one': '1 person is viewing.',
40042 'other': '{} people are viewing.'}">
40043 </ng-pluralize><br>
40045 <!--- Example with offset --->
40047 <ng-pluralize count="personCount" offset=2
40048 when="{'0': 'Nobody is viewing.',
40049 '1': '{{person1}} is viewing.',
40050 '2': '{{person1}} and {{person2}} are viewing.',
40051 'one': '{{person1}}, {{person2}} and one other person are viewing.',
40052 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
40056 <file name="protractor.js" type="protractor">
40057 it('should show correct pluralized string', function() {
40058 var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
40059 var withOffset = element.all(by.css('ng-pluralize')).get(1);
40060 var countInput = element(by.model('personCount'));
40062 expect(withoutOffset.getText()).toEqual('1 person is viewing.');
40063 expect(withOffset.getText()).toEqual('Igor is viewing.');
40065 countInput.clear();
40066 countInput.sendKeys('0');
40068 expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
40069 expect(withOffset.getText()).toEqual('Nobody is viewing.');
40071 countInput.clear();
40072 countInput.sendKeys('2');
40074 expect(withoutOffset.getText()).toEqual('2 people are viewing.');
40075 expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
40077 countInput.clear();
40078 countInput.sendKeys('3');
40080 expect(withoutOffset.getText()).toEqual('3 people are viewing.');
40081 expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
40083 countInput.clear();
40084 countInput.sendKeys('4');
40086 expect(withoutOffset.getText()).toEqual('4 people are viewing.');
40087 expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
40089 it('should show data-bound names', function() {
40090 var withOffset = element.all(by.css('ng-pluralize')).get(1);
40091 var personCount = element(by.model('personCount'));
40092 var person1 = element(by.model('person1'));
40093 var person2 = element(by.model('person2'));
40094 personCount.clear();
40095 personCount.sendKeys('4');
40097 person1.sendKeys('Di');
40099 person2.sendKeys('Vojta');
40100 expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
40105 var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
40107 IS_WHEN = /^when(Minus)?(.+)$/;
40110 link: function(scope, element, attr) {
40111 var numberExp = attr.count,
40112 whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
40113 offset = attr.offset || 0,
40114 whens = scope.$eval(whenExp) || {},
40116 startSymbol = $interpolate.startSymbol(),
40117 endSymbol = $interpolate.endSymbol(),
40118 braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
40119 watchRemover = angular.noop,
40122 forEach(attr, function(expression, attributeName) {
40123 var tmpMatch = IS_WHEN.exec(attributeName);
40125 var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
40126 whens[whenKey] = element.attr(attr.$attr[attributeName]);
40129 forEach(whens, function(expression, key) {
40130 whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
40134 scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
40135 var count = parseFloat(newVal);
40136 var countIsNaN = isNumberNaN(count);
40138 if (!countIsNaN && !(count in whens)) {
40139 // If an explicit number rule such as 1, 2, 3... is defined, just use it.
40140 // Otherwise, check it against pluralization rules in $locale service.
40141 count = $locale.pluralCat(count - offset);
40144 // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
40145 // In JS `NaN !== NaN`, so we have to explicitly check.
40146 if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) {
40148 var whenExpFn = whensExpFns[count];
40149 if (isUndefined(whenExpFn)) {
40150 if (newVal != null) {
40151 $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp);
40153 watchRemover = noop;
40154 updateElementText();
40156 watchRemover = scope.$watch(whenExpFn, updateElementText);
40162 function updateElementText(newText) {
40163 element.text(newText || '');
40169 /* exported ngRepeatDirective */
40177 * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
40178 * instance gets its own scope, where the given loop variable is set to the current collection item,
40179 * and `$index` is set to the item index or key.
40181 * Special properties are exposed on the local scope of each template instance, including:
40183 * | Variable | Type | Details |
40184 * |-----------|-----------------|-----------------------------------------------------------------------------|
40185 * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
40186 * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
40187 * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
40188 * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
40189 * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
40190 * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
40192 * <div class="alert alert-info">
40193 * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
40194 * This may be useful when, for instance, nesting ngRepeats.
40198 * # Iterating over object properties
40200 * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
40204 * <div ng-repeat="(key, value) in myObj"> ... </div>
40207 * However, there are a few limitations compared to array iteration:
40209 * - The JavaScript specification does not define the order of keys
40210 * returned for an object, so Angular relies on the order returned by the browser
40211 * when running `for key in myObj`. Browsers generally follow the strategy of providing
40212 * keys in the order in which they were defined, although there are exceptions when keys are deleted
40213 * and reinstated. See the
40214 * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
40216 * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
40217 * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
40219 * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
40220 * objects, and will throw an error if used with one.
40222 * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
40223 * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
40224 * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
40225 * or implement a `$watch` on the object yourself.
40228 * # Tracking and Duplicates
40230 * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
40231 * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM:
40233 * * When an item is added, a new instance of the template is added to the DOM.
40234 * * When an item is removed, its template instance is removed from the DOM.
40235 * * When items are reordered, their respective templates are reordered in the DOM.
40237 * To minimize creation of DOM elements, `ngRepeat` uses a function
40238 * to "keep track" of all items in the collection and their corresponding DOM elements.
40239 * For example, if an item is added to the collection, `ngRepeat` will know that all other items
40240 * already have DOM elements, and will not re-render them.
40242 * The default tracking function (which tracks items by their identity) does not allow
40243 * duplicate items in arrays. This is because when there are duplicates, it is not possible
40244 * to maintain a one-to-one mapping between collection items and DOM elements.
40246 * If you do need to repeat duplicate items, you can substitute the default tracking behavior
40247 * with your own using the `track by` expression.
40249 * For example, you may track items by the index of each item in the collection, using the
40250 * special scope property `$index`:
40252 * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
40257 * You may also use arbitrary expressions in `track by`, including references to custom functions
40260 * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
40265 * <div class="alert alert-success">
40266 * If you are working with objects that have a unique identifier property, you should track
40267 * by this identifier instead of the object instance. Should you reload your data later, `ngRepeat`
40268 * will not have to rebuild the DOM elements for items it has already rendered, even if the
40269 * JavaScript objects in the collection have been substituted for new ones. For large collections,
40270 * this significantly improves rendering performance. If you don't have a unique identifier,
40271 * `track by $index` can also provide a performance boost.
40275 * <div ng-repeat="model in collection track by model.id">
40281 * <div class="alert alert-warning">
40282 * Avoid using `track by $index` when the repeated template contains
40283 * {@link guide/expression#one-time-binding one-time bindings}. In such cases, the `nth` DOM
40284 * element will always be matched with the `nth` item of the array, so the bindings on that element
40285 * will not be updated even when the corresponding item changes, essentially causing the view to get
40286 * out-of-sync with the underlying data.
40289 * When no `track by` expression is provided, it is equivalent to tracking by the built-in
40290 * `$id` function, which tracks items by their identity:
40292 * <div ng-repeat="obj in collection track by $id(obj)">
40298 * <div class="alert alert-warning">
40299 * **Note:** `track by` must always be the last expression:
40302 * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
40308 * # Special repeat start and end points
40309 * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
40310 * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
40311 * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)
40312 * up to and including the ending HTML tag where **ng-repeat-end** is placed.
40314 * The example below makes use of this feature:
40316 * <header ng-repeat-start="item in items">
40317 * Header {{ item }}
40319 * <div class="body">
40322 * <footer ng-repeat-end>
40323 * Footer {{ item }}
40327 * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
40332 * <div class="body">
40341 * <div class="body">
40349 * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
40350 * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
40353 * | Animation | Occurs |
40354 * |----------------------------------|-------------------------------------|
40355 * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
40356 * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
40357 * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
40359 * See the example below for defining CSS animations with ngRepeat.
40364 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
40365 * formats are currently supported:
40367 * * `variable in expression` – where variable is the user defined loop variable and `expression`
40368 * is a scope expression giving the collection to enumerate.
40370 * For example: `album in artist.albums`.
40372 * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
40373 * and `expression` is the scope expression giving the collection to enumerate.
40375 * For example: `(name, age) in {'adam':10, 'amalie':12}`.
40377 * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
40378 * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
40379 * is specified, ng-repeat associates elements by identity. It is an error to have
40380 * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
40381 * mapped to the same DOM element, which is not possible.)
40383 * Note that the tracking expression must come last, after any filters, and the alias expression.
40385 * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
40386 * will be associated by item identity in the array.
40388 * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
40389 * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
40390 * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
40391 * element in the same way in the DOM.
40393 * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
40394 * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
40395 * property is same.
40397 * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
40398 * to items in conjunction with a tracking expression.
40400 * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
40401 * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
40402 * when a filter is active on the repeater, but the filtered result set is empty.
40404 * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
40405 * the items have been processed through the filter.
40407 * Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end
40408 * (and not as operator, inside an expression).
40410 * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
40413 * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
40414 * results by name or by age. New (entering) and removed (leaving) items are animated.
40415 <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true" name="ng-repeat">
40416 <file name="index.html">
40417 <div ng-controller="repeatController">
40418 I have {{friends.length}} friends. They are:
40419 <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
40420 <ul class="example-animate-container">
40421 <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
40422 [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
40424 <li class="animate-repeat" ng-if="results.length === 0">
40425 <strong>No results found...</strong>
40430 <file name="script.js">
40431 angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
40433 {name:'John', age:25, gender:'boy'},
40434 {name:'Jessie', age:30, gender:'girl'},
40435 {name:'Johanna', age:28, gender:'girl'},
40436 {name:'Joy', age:15, gender:'girl'},
40437 {name:'Mary', age:28, gender:'girl'},
40438 {name:'Peter', age:95, gender:'boy'},
40439 {name:'Sebastian', age:50, gender:'boy'},
40440 {name:'Erika', age:27, gender:'girl'},
40441 {name:'Patrick', age:40, gender:'boy'},
40442 {name:'Samantha', age:60, gender:'girl'}
40446 <file name="animations.css">
40447 .example-animate-container {
40449 border:1px solid black;
40458 box-sizing:border-box;
40461 .animate-repeat.ng-move,
40462 .animate-repeat.ng-enter,
40463 .animate-repeat.ng-leave {
40464 transition:all linear 0.5s;
40467 .animate-repeat.ng-leave.ng-leave-active,
40468 .animate-repeat.ng-move,
40469 .animate-repeat.ng-enter {
40474 .animate-repeat.ng-leave,
40475 .animate-repeat.ng-move.ng-move-active,
40476 .animate-repeat.ng-enter.ng-enter-active {
40481 <file name="protractor.js" type="protractor">
40482 var friends = element.all(by.repeater('friend in friends'));
40484 it('should render initial data set', function() {
40485 expect(friends.count()).toBe(10);
40486 expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
40487 expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
40488 expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
40489 expect(element(by.binding('friends.length')).getText())
40490 .toMatch("I have 10 friends. They are:");
40493 it('should update repeater when filter predicate changes', function() {
40494 expect(friends.count()).toBe(10);
40496 element(by.model('q')).sendKeys('ma');
40498 expect(friends.count()).toBe(2);
40499 expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
40500 expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
40505 var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
40506 var NG_REMOVED = '$$NG_REMOVED';
40507 var ngRepeatMinErr = minErr('ngRepeat');
40509 var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
40510 // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
40511 scope[valueIdentifier] = value;
40512 if (keyIdentifier) scope[keyIdentifier] = key;
40513 scope.$index = index;
40514 scope.$first = (index === 0);
40515 scope.$last = (index === (arrayLength - 1));
40516 scope.$middle = !(scope.$first || scope.$last);
40517 // eslint-disable-next-line no-bitwise
40518 scope.$odd = !(scope.$even = (index & 1) === 0);
40521 var getBlockStart = function(block) {
40522 return block.clone[0];
40525 var getBlockEnd = function(block) {
40526 return block.clone[block.clone.length - 1];
40532 multiElement: true,
40533 transclude: 'element',
40537 compile: function ngRepeatCompile($element, $attr) {
40538 var expression = $attr.ngRepeat;
40539 var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
40541 var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
40544 throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.',
40548 var lhs = match[1];
40549 var rhs = match[2];
40550 var aliasAs = match[3];
40551 var trackByExp = match[4];
40553 match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/);
40556 throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.',
40559 var valueIdentifier = match[3] || match[1];
40560 var keyIdentifier = match[2];
40562 if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
40563 /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
40564 throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.',
40568 var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
40569 var hashFnLocals = {$id: hashKey};
40572 trackByExpGetter = $parse(trackByExp);
40574 trackByIdArrayFn = function(key, value) {
40575 return hashKey(value);
40577 trackByIdObjFn = function(key) {
40582 return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
40584 if (trackByExpGetter) {
40585 trackByIdExpFn = function(key, value, index) {
40586 // assign key, value, and $index to the locals so that they can be used in hash functions
40587 if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
40588 hashFnLocals[valueIdentifier] = value;
40589 hashFnLocals.$index = index;
40590 return trackByExpGetter($scope, hashFnLocals);
40594 // Store a list of elements from previous run. This is a hash where key is the item from the
40595 // iterator, and the value is objects with following properties.
40596 // - scope: bound scope
40597 // - element: previous element.
40598 // - index: position
40600 // We are using no-proto object so that we don't need to guard against inherited props via
40602 var lastBlockMap = createMap();
40605 $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
40607 previousNode = $element[0], // node that cloned nodes should be inserted after
40608 // initialized to the comment node anchor
40610 // Same as lastBlockMap but it has the current state. It will become the
40611 // lastBlockMap on the next iteration.
40612 nextBlockMap = createMap(),
40614 key, value, // key/value of iteration
40618 block, // last object information {scope, element, id}
40623 $scope[aliasAs] = collection;
40626 if (isArrayLike(collection)) {
40627 collectionKeys = collection;
40628 trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
40630 trackByIdFn = trackByIdExpFn || trackByIdObjFn;
40631 // if object, extract keys, in enumeration order, unsorted
40632 collectionKeys = [];
40633 for (var itemKey in collection) {
40634 if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
40635 collectionKeys.push(itemKey);
40640 collectionLength = collectionKeys.length;
40641 nextBlockOrder = new Array(collectionLength);
40643 // locate existing items
40644 for (index = 0; index < collectionLength; index++) {
40645 key = (collection === collectionKeys) ? index : collectionKeys[index];
40646 value = collection[key];
40647 trackById = trackByIdFn(key, value, index);
40648 if (lastBlockMap[trackById]) {
40649 // found previously seen block
40650 block = lastBlockMap[trackById];
40651 delete lastBlockMap[trackById];
40652 nextBlockMap[trackById] = block;
40653 nextBlockOrder[index] = block;
40654 } else if (nextBlockMap[trackById]) {
40655 // if collision detected. restore lastBlockMap and throw an error
40656 forEach(nextBlockOrder, function(block) {
40657 if (block && block.scope) lastBlockMap[block.id] = block;
40659 throw ngRepeatMinErr('dupes',
40660 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}',
40661 expression, trackById, value);
40663 // new never before seen block
40664 nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
40665 nextBlockMap[trackById] = true;
40669 // remove leftover items
40670 for (var blockKey in lastBlockMap) {
40671 block = lastBlockMap[blockKey];
40672 elementsToRemove = getBlockNodes(block.clone);
40673 $animate.leave(elementsToRemove);
40674 if (elementsToRemove[0].parentNode) {
40675 // if the element was not removed yet because of pending animation, mark it as deleted
40676 // so that we can ignore it later
40677 for (index = 0, length = elementsToRemove.length; index < length; index++) {
40678 elementsToRemove[index][NG_REMOVED] = true;
40681 block.scope.$destroy();
40684 // we are not using forEach for perf reasons (trying to avoid #call)
40685 for (index = 0; index < collectionLength; index++) {
40686 key = (collection === collectionKeys) ? index : collectionKeys[index];
40687 value = collection[key];
40688 block = nextBlockOrder[index];
40691 // if we have already seen this object, then we need to reuse the
40692 // associated scope/element
40694 nextNode = previousNode;
40696 // skip nodes that are already pending removal via leave animation
40698 nextNode = nextNode.nextSibling;
40699 } while (nextNode && nextNode[NG_REMOVED]);
40701 if (getBlockStart(block) !== nextNode) {
40702 // existing item which got moved
40703 $animate.move(getBlockNodes(block.clone), null, previousNode);
40705 previousNode = getBlockEnd(block);
40706 updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
40708 // new item which we don't know about
40709 $transclude(function ngRepeatTransclude(clone, scope) {
40710 block.scope = scope;
40711 // http://jsperf.com/clone-vs-createcomment
40712 var endNode = ngRepeatEndComment.cloneNode(false);
40713 clone[clone.length++] = endNode;
40715 $animate.enter(clone, null, previousNode);
40716 previousNode = endNode;
40717 // Note: We only need the first/last node of the cloned nodes.
40718 // However, we need to keep the reference to the jqlite wrapper as it might be changed later
40719 // by a directive with templateUrl when its template arrives.
40720 block.clone = clone;
40721 nextBlockMap[block.id] = block;
40722 updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
40726 lastBlockMap = nextBlockMap;
40733 var NG_HIDE_CLASS = 'ng-hide';
40734 var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
40741 * The `ngShow` directive shows or hides the given HTML element based on the expression provided to
40742 * the `ngShow` attribute.
40744 * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
40745 * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
40746 * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
40747 * {@link ng.directive:ngCsp ngCsp}).
40750 * <!-- when $scope.myValue is truthy (element is visible) -->
40751 * <div ng-show="myValue"></div>
40753 * <!-- when $scope.myValue is falsy (element is hidden) -->
40754 * <div ng-show="myValue" class="ng-hide"></div>
40757 * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added
40758 * to the class attribute on the element causing it to become hidden. When truthy, the `.ng-hide`
40759 * CSS class is removed from the element causing the element not to appear hidden.
40761 * ## Why is `!important` used?
40763 * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
40764 * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
40765 * simple as changing the display style on a HTML list item would make hidden elements appear
40766 * visible. This also becomes a bigger issue when dealing with CSS frameworks.
40768 * By using `!important`, the show and hide behavior will work as expected despite any clash between
40769 * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
40770 * developer chooses to override the styling to change how to hide an element then it is just a
40771 * matter of using `!important` in their own CSS code.
40773 * ### Overriding `.ng-hide`
40775 * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
40776 * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
40777 * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
40778 * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
40781 * .ng-hide:not(.ng-hide-animate) {
40782 * /* These are just alternative ways of hiding an element */
40783 * display: block!important;
40784 * position: absolute;
40790 * By default you don't need to override anything in CSS and the animations will work around the
40793 * ## A note about animations with `ngShow`
40795 * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
40796 * directive expression is true and false. This system works like the animation system present with
40797 * `ngClass` except that you must also include the `!important` flag to override the display
40798 * property so that the elements are not actually hidden during the animation.
40801 * /* A working example can be found at the bottom of this page. */
40802 * .my-element.ng-hide-add, .my-element.ng-hide-remove {
40803 * transition: all 0.5s linear;
40806 * .my-element.ng-hide-add { ... }
40807 * .my-element.ng-hide-add.ng-hide-add-active { ... }
40808 * .my-element.ng-hide-remove { ... }
40809 * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
40812 * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
40813 * to block during animation states - ngAnimate will automatically handle the style toggling for you.
40816 * | Animation | Occurs |
40817 * |-----------------------------------------------------|---------------------------------------------------------------------------------------------------------------|
40818 * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden. |
40819 * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngShow` expression evaluates to a truthy value and just before contents are set to visible. |
40822 * @param {expression} ngShow If the {@link guide/expression expression} is truthy/falsy then the
40823 * element is shown/hidden respectively.
40826 * A simple example, animating the element's opacity:
40828 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-simple">
40829 <file name="index.html">
40830 Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
40831 <div class="check-element animate-show-hide" ng-show="checked">
40832 I show up when your checkbox is checked.
40835 <file name="animations.css">
40836 .animate-show-hide.ng-hide {
40840 .animate-show-hide.ng-hide-add,
40841 .animate-show-hide.ng-hide-remove {
40842 transition: all linear 0.5s;
40846 border: 1px solid black;
40851 <file name="protractor.js" type="protractor">
40852 it('should check ngShow', function() {
40853 var checkbox = element(by.model('checked'));
40854 var checkElem = element(by.css('.check-element'));
40856 expect(checkElem.isDisplayed()).toBe(false);
40858 expect(checkElem.isDisplayed()).toBe(true);
40865 * A more complex example, featuring different show/hide animations:
40867 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-complex">
40868 <file name="index.html">
40869 Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
40870 <div class="check-element funky-show-hide" ng-show="checked">
40871 I show up when your checkbox is checked.
40874 <file name="animations.css">
40877 perspective: 1000px;
40880 .funky-show-hide.ng-hide-add {
40881 transform: rotateZ(0);
40882 transform-origin: right;
40883 transition: all 0.5s ease-in-out;
40886 .funky-show-hide.ng-hide-add.ng-hide-add-active {
40887 transform: rotateZ(-135deg);
40890 .funky-show-hide.ng-hide-remove {
40891 transform: rotateY(90deg);
40892 transform-origin: left;
40893 transition: all 0.5s ease;
40896 .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
40897 transform: rotateY(0);
40901 border: 1px solid black;
40906 <file name="protractor.js" type="protractor">
40907 it('should check ngShow', function() {
40908 var checkbox = element(by.model('checked'));
40909 var checkElem = element(by.css('.check-element'));
40911 expect(checkElem.isDisplayed()).toBe(false);
40913 expect(checkElem.isDisplayed()).toBe(true);
40918 var ngShowDirective = ['$animate', function($animate) {
40921 multiElement: true,
40922 link: function(scope, element, attr) {
40923 scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
40924 // we're adding a temporary, animation-specific class for ng-hide since this way
40925 // we can control when the element is actually displayed on screen without having
40926 // to have a global/greedy CSS selector that breaks when other animations are run.
40927 // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
40928 $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
40929 tempClasses: NG_HIDE_IN_PROGRESS_CLASS
40943 * The `ngHide` directive shows or hides the given HTML element based on the expression provided to
40944 * the `ngHide` attribute.
40946 * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
40947 * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
40948 * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
40949 * {@link ng.directive:ngCsp ngCsp}).
40952 * <!-- when $scope.myValue is truthy (element is hidden) -->
40953 * <div ng-hide="myValue" class="ng-hide"></div>
40955 * <!-- when $scope.myValue is falsy (element is visible) -->
40956 * <div ng-hide="myValue"></div>
40959 * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added
40960 * to the class attribute on the element causing it to become hidden. When falsy, the `.ng-hide`
40961 * CSS class is removed from the element causing the element not to appear hidden.
40963 * ## Why is `!important` used?
40965 * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
40966 * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
40967 * simple as changing the display style on a HTML list item would make hidden elements appear
40968 * visible. This also becomes a bigger issue when dealing with CSS frameworks.
40970 * By using `!important`, the show and hide behavior will work as expected despite any clash between
40971 * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
40972 * developer chooses to override the styling to change how to hide an element then it is just a
40973 * matter of using `!important` in their own CSS code.
40975 * ### Overriding `.ng-hide`
40977 * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
40978 * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
40979 * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
40980 * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
40983 * .ng-hide:not(.ng-hide-animate) {
40984 * /* These are just alternative ways of hiding an element */
40985 * display: block!important;
40986 * position: absolute;
40992 * By default you don't need to override in CSS anything and the animations will work around the
40995 * ## A note about animations with `ngHide`
40997 * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
40998 * directive expression is true and false. This system works like the animation system present with
40999 * `ngClass` except that you must also include the `!important` flag to override the display
41000 * property so that the elements are not actually hidden during the animation.
41003 * /* A working example can be found at the bottom of this page. */
41004 * .my-element.ng-hide-add, .my-element.ng-hide-remove {
41005 * transition: all 0.5s linear;
41008 * .my-element.ng-hide-add { ... }
41009 * .my-element.ng-hide-add.ng-hide-add-active { ... }
41010 * .my-element.ng-hide-remove { ... }
41011 * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
41014 * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
41015 * to block during animation states - ngAnimate will automatically handle the style toggling for you.
41018 * | Animation | Occurs |
41019 * |-----------------------------------------------------|------------------------------------------------------------------------------------------------------------|
41020 * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden. |
41021 * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible. |
41025 * @param {expression} ngHide If the {@link guide/expression expression} is truthy/falsy then the
41026 * element is hidden/shown respectively.
41029 * A simple example, animating the element's opacity:
41031 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-simple">
41032 <file name="index.html">
41033 Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
41034 <div class="check-element animate-show-hide" ng-hide="checked">
41035 I hide when your checkbox is checked.
41038 <file name="animations.css">
41039 .animate-show-hide.ng-hide {
41043 .animate-show-hide.ng-hide-add,
41044 .animate-show-hide.ng-hide-remove {
41045 transition: all linear 0.5s;
41049 border: 1px solid black;
41054 <file name="protractor.js" type="protractor">
41055 it('should check ngHide', function() {
41056 var checkbox = element(by.model('checked'));
41057 var checkElem = element(by.css('.check-element'));
41059 expect(checkElem.isDisplayed()).toBe(true);
41061 expect(checkElem.isDisplayed()).toBe(false);
41068 * A more complex example, featuring different show/hide animations:
41070 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-complex">
41071 <file name="index.html">
41072 Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
41073 <div class="check-element funky-show-hide" ng-hide="checked">
41074 I hide when your checkbox is checked.
41077 <file name="animations.css">
41080 perspective: 1000px;
41083 .funky-show-hide.ng-hide-add {
41084 transform: rotateZ(0);
41085 transform-origin: right;
41086 transition: all 0.5s ease-in-out;
41089 .funky-show-hide.ng-hide-add.ng-hide-add-active {
41090 transform: rotateZ(-135deg);
41093 .funky-show-hide.ng-hide-remove {
41094 transform: rotateY(90deg);
41095 transform-origin: left;
41096 transition: all 0.5s ease;
41099 .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
41100 transform: rotateY(0);
41104 border: 1px solid black;
41109 <file name="protractor.js" type="protractor">
41110 it('should check ngHide', function() {
41111 var checkbox = element(by.model('checked'));
41112 var checkElem = element(by.css('.check-element'));
41114 expect(checkElem.isDisplayed()).toBe(true);
41116 expect(checkElem.isDisplayed()).toBe(false);
41121 var ngHideDirective = ['$animate', function($animate) {
41124 multiElement: true,
41125 link: function(scope, element, attr) {
41126 scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
41127 // The comment inside of the ngShowDirective explains why we add and
41128 // remove a temporary class for the show/hide animation
41129 $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
41130 tempClasses: NG_HIDE_IN_PROGRESS_CLASS
41143 * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
41146 * You should not use {@link guide/interpolation interpolation} in the value of the `style`
41147 * attribute, when using the `ngStyle` directive on the same element.
41148 * See {@link guide/interpolation#known-issues here} for more info.
41151 * @param {expression} ngStyle
41153 * {@link guide/expression Expression} which evals to an
41154 * object whose keys are CSS style names and values are corresponding values for those CSS
41157 * Since some CSS style names are not valid keys for an object, they must be quoted.
41158 * See the 'background-color' style in the example below.
41161 <example name="ng-style">
41162 <file name="index.html">
41163 <input type="button" value="set color" ng-click="myStyle={color:'red'}">
41164 <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
41165 <input type="button" value="clear" ng-click="myStyle={}">
41167 <span ng-style="myStyle">Sample Text</span>
41168 <pre>myStyle={{myStyle}}</pre>
41170 <file name="style.css">
41175 <file name="protractor.js" type="protractor">
41176 var colorSpan = element(by.css('span'));
41178 it('should check ng-style', function() {
41179 expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
41180 element(by.css('input[value=\'set color\']')).click();
41181 expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
41182 element(by.css('input[value=clear]')).click();
41183 expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
41188 var ngStyleDirective = ngDirective(function(scope, element, attr) {
41189 scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
41190 if (oldStyles && (newStyles !== oldStyles)) {
41191 forEach(oldStyles, function(val, style) { element.css(style, '');});
41193 if (newStyles) element.css(newStyles);
41203 * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
41204 * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
41205 * as specified in the template.
41207 * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
41208 * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
41209 * matches the value obtained from the evaluated expression. In other words, you define a container element
41210 * (where you place the directive), place an expression on the **`on="..."` attribute**
41211 * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
41212 * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
41213 * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
41214 * attribute is displayed.
41216 * <div class="alert alert-info">
41217 * Be aware that the attribute values to match against cannot be expressions. They are interpreted
41218 * as literal string values to match against.
41219 * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
41220 * value of the expression `$scope.someVal`.
41224 * | Animation | Occurs |
41225 * |----------------------------------|-------------------------------------|
41226 * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
41227 * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
41232 * <ANY ng-switch="expression">
41233 * <ANY ng-switch-when="matchValue1">...</ANY>
41234 * <ANY ng-switch-when="matchValue2">...</ANY>
41235 * <ANY ng-switch-default>...</ANY>
41242 * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
41243 * On child elements add:
41245 * * `ngSwitchWhen`: the case statement to match against. If match then this
41246 * case will be displayed. If the same match appears multiple times, all the
41247 * elements will be displayed. It is possible to associate multiple values to
41248 * the same `ngSwitchWhen` by defining the optional attribute
41249 * `ngSwitchWhenSeparator`. The separator will be used to split the value of
41250 * the `ngSwitchWhen` attribute into multiple tokens, and the element will show
41251 * if any of the `ngSwitch` evaluates to any of these tokens.
41252 * * `ngSwitchDefault`: the default case when no other case match. If there
41253 * are multiple default cases, all of them will be displayed when no other
41258 <example module="switchExample" deps="angular-animate.js" animations="true" name="ng-switch">
41259 <file name="index.html">
41260 <div ng-controller="ExampleController">
41261 <select ng-model="selection" ng-options="item for item in items">
41263 <code>selection={{selection}}</code>
41265 <div class="animate-switch-container"
41266 ng-switch on="selection">
41267 <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
41268 <div class="animate-switch" ng-switch-when="home">Home Span</div>
41269 <div class="animate-switch" ng-switch-default>default</div>
41273 <file name="script.js">
41274 angular.module('switchExample', ['ngAnimate'])
41275 .controller('ExampleController', ['$scope', function($scope) {
41276 $scope.items = ['settings', 'home', 'options', 'other'];
41277 $scope.selection = $scope.items[0];
41280 <file name="animations.css">
41281 .animate-switch-container {
41284 border:1px solid black;
41293 .animate-switch.ng-animate {
41294 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
41303 .animate-switch.ng-leave.ng-leave-active,
41304 .animate-switch.ng-enter {
41307 .animate-switch.ng-leave,
41308 .animate-switch.ng-enter.ng-enter-active {
41312 <file name="protractor.js" type="protractor">
41313 var switchElem = element(by.css('[ng-switch]'));
41314 var select = element(by.model('selection'));
41316 it('should start in settings', function() {
41317 expect(switchElem.getText()).toMatch(/Settings Div/);
41319 it('should change to home', function() {
41320 select.all(by.css('option')).get(1).click();
41321 expect(switchElem.getText()).toMatch(/Home Span/);
41323 it('should change to settings via "options"', function() {
41324 select.all(by.css('option')).get(2).click();
41325 expect(switchElem.getText()).toMatch(/Settings Div/);
41327 it('should select default', function() {
41328 select.all(by.css('option')).get(3).click();
41329 expect(switchElem.getText()).toMatch(/default/);
41334 var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
41336 require: 'ngSwitch',
41338 // asks for $scope to fool the BC controller module
41339 controller: ['$scope', function NgSwitchController() {
41342 link: function(scope, element, attr, ngSwitchController) {
41343 var watchExpr = attr.ngSwitch || attr.on,
41344 selectedTranscludes = [],
41345 selectedElements = [],
41346 previousLeaveAnimations = [],
41347 selectedScopes = [];
41349 var spliceFactory = function(array, index) {
41350 return function(response) {
41351 if (response !== false) array.splice(index, 1);
41355 scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
41358 // Start with the last, in case the array is modified during the loop
41359 while (previousLeaveAnimations.length) {
41360 $animate.cancel(previousLeaveAnimations.pop());
41363 for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
41364 var selected = getBlockNodes(selectedElements[i].clone);
41365 selectedScopes[i].$destroy();
41366 var runner = previousLeaveAnimations[i] = $animate.leave(selected);
41367 runner.done(spliceFactory(previousLeaveAnimations, i));
41370 selectedElements.length = 0;
41371 selectedScopes.length = 0;
41373 if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
41374 forEach(selectedTranscludes, function(selectedTransclude) {
41375 selectedTransclude.transclude(function(caseElement, selectedScope) {
41376 selectedScopes.push(selectedScope);
41377 var anchor = selectedTransclude.element;
41378 caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
41379 var block = { clone: caseElement };
41381 selectedElements.push(block);
41382 $animate.enter(caseElement, anchor.parent(), anchor);
41391 var ngSwitchWhenDirective = ngDirective({
41392 transclude: 'element',
41394 require: '^ngSwitch',
41395 multiElement: true,
41396 link: function(scope, element, attrs, ctrl, $transclude) {
41398 var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(
41399 // Filter duplicate cases
41400 function(element, index, array) { return array[index - 1] !== element; }
41403 forEach(cases, function(whenCase) {
41404 ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);
41405 ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });
41410 var ngSwitchDefaultDirective = ngDirective({
41411 transclude: 'element',
41413 require: '^ngSwitch',
41414 multiElement: true,
41415 link: function(scope, element, attr, ctrl, $transclude) {
41416 ctrl.cases['?'] = (ctrl.cases['?'] || []);
41417 ctrl.cases['?'].push({ transclude: $transclude, element: element });
41423 * @name ngTransclude
41427 * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
41429 * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
41430 * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
41432 * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
41433 * content of this element will be removed before the transcluded content is inserted.
41434 * If the transcluded content is empty, the existing content is left intact. This lets you provide fallback content in the case
41435 * that no transcluded content is provided.
41439 * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
41440 * or its value is the same as the name of the attribute then the default slot is used.
41443 * ### Basic transclusion
41444 * This example demonstrates basic transclusion of content into a component directive.
41445 * <example name="simpleTranscludeExample" module="transcludeExample">
41446 * <file name="index.html">
41448 * angular.module('transcludeExample', [])
41449 * .directive('pane', function(){
41452 * transclude: true,
41453 * scope: { title:'@' },
41454 * template: '<div style="border: 1px solid black;">' +
41455 * '<div style="background-color: gray">{{title}}</div>' +
41456 * '<ng-transclude></ng-transclude>' +
41460 * .controller('ExampleController', ['$scope', function($scope) {
41461 * $scope.title = 'Lorem Ipsum';
41462 * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
41465 * <div ng-controller="ExampleController">
41466 * <input ng-model="title" aria-label="title"> <br/>
41467 * <textarea ng-model="text" aria-label="text"></textarea> <br/>
41468 * <pane title="{{title}}">{{text}}</pane>
41471 * <file name="protractor.js" type="protractor">
41472 * it('should have transcluded', function() {
41473 * var titleElement = element(by.model('title'));
41474 * titleElement.clear();
41475 * titleElement.sendKeys('TITLE');
41476 * var textElement = element(by.model('text'));
41477 * textElement.clear();
41478 * textElement.sendKeys('TEXT');
41479 * expect(element(by.binding('title')).getText()).toEqual('TITLE');
41480 * expect(element(by.binding('text')).getText()).toEqual('TEXT');
41486 * ### Transclude fallback content
41487 * This example shows how to use `NgTransclude` with fallback content, that
41488 * is displayed if no transcluded content is provided.
41490 * <example module="transcludeFallbackContentExample" name="ng-transclude">
41491 * <file name="index.html">
41493 * angular.module('transcludeFallbackContentExample', [])
41494 * .directive('myButton', function(){
41497 * transclude: true,
41499 * template: '<button style="cursor: pointer;">' +
41500 * '<ng-transclude>' +
41501 * '<b style="color: red;">Button1</b>' +
41502 * '</ng-transclude>' +
41507 * <!-- fallback button content -->
41508 * <my-button id="fallback"></my-button>
41509 * <!-- modified button content -->
41510 * <my-button id="modified">
41511 * <i style="color: green;">Button2</i>
41514 * <file name="protractor.js" type="protractor">
41515 * it('should have different transclude element content', function() {
41516 * expect(element(by.id('fallback')).getText()).toBe('Button1');
41517 * expect(element(by.id('modified')).getText()).toBe('Button2');
41523 * ### Multi-slot transclusion
41524 * This example demonstrates using multi-slot transclusion in a component directive.
41525 * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
41526 * <file name="index.html">
41528 * .title, .footer {
41529 * background-color: gray
41532 * <div ng-controller="ExampleController">
41533 * <input ng-model="title" aria-label="title"> <br/>
41534 * <textarea ng-model="text" aria-label="text"></textarea> <br/>
41536 * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
41537 * <pane-body><p>{{text}}</p></pane-body>
41541 * <file name="app.js">
41542 * angular.module('multiSlotTranscludeExample', [])
41543 * .directive('pane', function() {
41547 * 'title': '?paneTitle',
41548 * 'body': 'paneBody',
41549 * 'footer': '?paneFooter'
41551 * template: '<div style="border: 1px solid black;">' +
41552 * '<div class="title" ng-transclude="title">Fallback Title</div>' +
41553 * '<div ng-transclude="body"></div>' +
41554 * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
41558 * .controller('ExampleController', ['$scope', function($scope) {
41559 * $scope.title = 'Lorem Ipsum';
41560 * $scope.link = 'https://google.com';
41561 * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
41564 * <file name="protractor.js" type="protractor">
41565 * it('should have transcluded the title and the body', function() {
41566 * var titleElement = element(by.model('title'));
41567 * titleElement.clear();
41568 * titleElement.sendKeys('TITLE');
41569 * var textElement = element(by.model('text'));
41570 * textElement.clear();
41571 * textElement.sendKeys('TEXT');
41572 * expect(element(by.css('.title')).getText()).toEqual('TITLE');
41573 * expect(element(by.binding('text')).getText()).toEqual('TEXT');
41574 * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
41579 var ngTranscludeMinErr = minErr('ngTransclude');
41580 var ngTranscludeDirective = ['$compile', function($compile) {
41584 compile: function ngTranscludeCompile(tElement) {
41586 // Remove and cache any original content to act as a fallback
41587 var fallbackLinkFn = $compile(tElement.contents());
41590 return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {
41592 if (!$transclude) {
41593 throw ngTranscludeMinErr('orphan',
41594 'Illegal use of ngTransclude directive in the template! ' +
41595 'No parent directive that requires a transclusion found. ' +
41597 startingTag($element));
41601 // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default
41602 if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
41603 $attrs.ngTransclude = '';
41605 var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
41607 // If the slot is required and no transclusion content is provided then this call will throw an error
41608 $transclude(ngTranscludeCloneAttachFn, null, slotName);
41610 // If the slot is optional and no transclusion content is provided then use the fallback content
41611 if (slotName && !$transclude.isSlotFilled(slotName)) {
41612 useFallbackContent();
41615 function ngTranscludeCloneAttachFn(clone, transcludedScope) {
41616 if (clone.length) {
41617 $element.append(clone);
41619 useFallbackContent();
41620 // There is nothing linked against the transcluded scope since no content was available,
41621 // so it should be safe to clean up the generated scope.
41622 transcludedScope.$destroy();
41626 function useFallbackContent() {
41627 // Since this is the fallback content rather than the transcluded content,
41628 // we link against the scope of this directive rather than the transcluded scope
41629 fallbackLinkFn($scope, function(clone) {
41630 $element.append(clone);
41644 * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
41645 * template can be used by {@link ng.directive:ngInclude `ngInclude`},
41646 * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
41647 * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
41648 * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
41650 * @param {string} type Must be set to `'text/ng-template'`.
41651 * @param {string} id Cache name of the template.
41654 <example name="script-tag">
41655 <file name="index.html">
41656 <script type="text/ng-template" id="/tpl.html">
41657 Content of the template.
41660 <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
41661 <div id="tpl-content" ng-include src="currentTpl"></div>
41663 <file name="protractor.js" type="protractor">
41664 it('should load template defined inside script tag', function() {
41665 element(by.css('#tpl-link')).click();
41666 expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
41671 var scriptDirective = ['$templateCache', function($templateCache) {
41675 compile: function(element, attr) {
41676 if (attr.type === 'text/ng-template') {
41677 var templateUrl = attr.id,
41678 text = element[0].text;
41680 $templateCache.put(templateUrl, text);
41686 /* exported selectDirective, optionDirective */
41688 var noopNgModelController = { $setViewValue: noop, $render: noop };
41690 function chromeHack(optionElement) {
41691 // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
41692 // Adding an <option selected="selected"> element to a <select required="required"> should
41693 // automatically select the new element
41694 if (optionElement[0].hasAttribute('selected')) {
41695 optionElement[0].selected = true;
41701 * @name select.SelectController
41703 * The controller for the `<select>` directive. This provides support for reading
41704 * and writing the selected value(s) of the control and also coordinates dynamically
41705 * added `<option>` elements, perhaps by an `ngRepeat` directive.
41707 var SelectController =
41708 ['$element', '$scope', /** @this */ function($element, $scope) {
41711 optionsMap = new HashMap();
41713 // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
41714 self.ngModelCtrl = noopNgModelController;
41716 // The "unknown" option is one that is prepended to the list if the viewValue
41717 // does not match any of the options. When it is rendered the value of the unknown
41718 // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
41720 // We can't just jqLite('<option>') since jqLite is not smart enough
41721 // to create it in <select> and IE barfs otherwise.
41722 self.unknownOption = jqLite(window.document.createElement('option'));
41723 self.renderUnknownOption = function(val) {
41724 var unknownVal = '? ' + hashKey(val) + ' ?';
41725 self.unknownOption.val(unknownVal);
41726 $element.prepend(self.unknownOption);
41727 $element.val(unknownVal);
41730 $scope.$on('$destroy', function() {
41731 // disable unknown option so that we don't do work when the whole select is being destroyed
41732 self.renderUnknownOption = noop;
41735 self.removeUnknownOption = function() {
41736 if (self.unknownOption.parent()) self.unknownOption.remove();
41740 // Read the value of the select control, the implementation of this changes depending
41741 // upon whether the select can have multiple values and whether ngOptions is at work.
41742 self.readValue = function readSingleValue() {
41743 self.removeUnknownOption();
41744 return $element.val();
41748 // Write the value to the select control, the implementation of this changes depending
41749 // upon whether the select can have multiple values and whether ngOptions is at work.
41750 self.writeValue = function writeSingleValue(value) {
41751 if (self.hasOption(value)) {
41752 self.removeUnknownOption();
41753 $element.val(value);
41754 if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
41756 if (value == null && self.emptyOption) {
41757 self.removeUnknownOption();
41760 self.renderUnknownOption(value);
41766 // Tell the select control that an option, with the given value, has been added
41767 self.addOption = function(value, element) {
41768 // Skip comment nodes, as they only pollute the `optionsMap`
41769 if (element[0].nodeType === NODE_TYPE_COMMENT) return;
41771 assertNotHasOwnProperty(value, '"option value"');
41772 if (value === '') {
41773 self.emptyOption = element;
41775 var count = optionsMap.get(value) || 0;
41776 optionsMap.put(value, count + 1);
41777 self.ngModelCtrl.$render();
41778 chromeHack(element);
41781 // Tell the select control that an option, with the given value, has been removed
41782 self.removeOption = function(value) {
41783 var count = optionsMap.get(value);
41786 optionsMap.remove(value);
41787 if (value === '') {
41788 self.emptyOption = undefined;
41791 optionsMap.put(value, count - 1);
41796 // Check whether the select control has an option matching the given value
41797 self.hasOption = function(value) {
41798 return !!optionsMap.get(value);
41802 self.registerOption = function(optionScope, optionElement, optionAttrs, hasDynamicValueAttr, interpolateTextFn) {
41804 if (hasDynamicValueAttr) {
41805 // either "value" is interpolated directly, or set by ngValue
41807 optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
41808 if (isDefined(oldVal)) {
41809 self.removeOption(oldVal);
41812 self.addOption(newVal, optionElement);
41814 } else if (interpolateTextFn) {
41815 // The text content is interpolated
41816 optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
41817 optionAttrs.$set('value', newVal);
41818 if (oldVal !== newVal) {
41819 self.removeOption(oldVal);
41821 self.addOption(newVal, optionElement);
41824 // The value attribute is static
41825 self.addOption(optionAttrs.value, optionElement);
41828 optionElement.on('$destroy', function() {
41829 self.removeOption(optionAttrs.value);
41830 self.ngModelCtrl.$render();
41841 * HTML `SELECT` element with angular data-binding.
41843 * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
41844 * between the scope and the `<select>` control (including setting default values).
41845 * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
41846 * {@link ngOptions `ngOptions`} directives.
41848 * When an item in the `<select>` menu is selected, the value of the selected option will be bound
41849 * to the model identified by the `ngModel` directive. With static or repeated options, this is
41850 * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
41851 * For dynamic options, use interpolation inside the `value` attribute or the `textContent`. Using
41852 * {@link ngValue ngValue} is also possible (as it sets the `value` attribute), and will take
41853 * precedence over `value` and `textContent`.
41855 * <div class="alert alert-warning">
41856 * Note that the value of a `select` directive used without `ngOptions` is always a string.
41857 * When the model needs to be bound to a non-string value, you must either explicitly convert it
41858 * using a directive (see example below) or use `ngOptions` to specify the set of options.
41859 * This is because an option element can only be bound to string values at present.
41862 * If the viewValue of `ngModel` does not match any of the options, then the control
41863 * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
41865 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
41866 * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
41867 * option. See example below for demonstration.
41869 * <div class="alert alert-info">
41870 * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
41871 * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
41872 * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
41873 * comprehension expression, and additionally in reducing memory and increasing speed by not creating
41874 * a new scope for each repeated instance.
41878 * @param {string} ngModel Assignable angular expression to data-bind to.
41879 * @param {string=} name Property name of the form under which the control is published.
41880 * @param {string=} multiple Allows multiple options to be selected. The selected values will be
41881 * bound to the model as an array.
41882 * @param {string=} required Sets `required` validation error key if the value is not entered.
41883 * @param {string=} ngRequired Adds required attribute and required validation constraint to
41884 * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
41885 * when you want to data-bind to the required attribute.
41886 * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
41887 * interaction with the select element.
41888 * @param {string=} ngOptions sets the options that the select is populated with and defines what is
41889 * set on the model on selection. See {@link ngOptions `ngOptions`}.
41892 * ### Simple `select` elements with static options
41894 * <example name="static-select" module="staticSelect">
41895 * <file name="index.html">
41896 * <div ng-controller="ExampleController">
41897 * <form name="myForm">
41898 * <label for="singleSelect"> Single select: </label><br>
41899 * <select name="singleSelect" ng-model="data.singleSelect">
41900 * <option value="option-1">Option 1</option>
41901 * <option value="option-2">Option 2</option>
41904 * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
41905 * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
41906 * <option value="">---Please select---</option> <!-- not selected / blank option -->
41907 * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
41908 * <option value="option-2">Option 2</option>
41910 * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
41911 * <tt>singleSelect = {{data.singleSelect}}</tt>
41914 * <label for="multipleSelect"> Multiple select: </label><br>
41915 * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
41916 * <option value="option-1">Option 1</option>
41917 * <option value="option-2">Option 2</option>
41918 * <option value="option-3">Option 3</option>
41920 * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
41924 * <file name="app.js">
41925 * angular.module('staticSelect', [])
41926 * .controller('ExampleController', ['$scope', function($scope) {
41928 * singleSelect: null,
41929 * multipleSelect: [],
41930 * option1: 'option-1'
41933 * $scope.forceUnknownOption = function() {
41934 * $scope.data.singleSelect = 'nonsense';
41940 * ### Using `ngRepeat` to generate `select` options
41941 * <example name="ngrepeat-select" module="ngrepeatSelect">
41942 * <file name="index.html">
41943 * <div ng-controller="ExampleController">
41944 * <form name="myForm">
41945 * <label for="repeatSelect"> Repeat select: </label>
41946 * <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
41947 * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
41951 * <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
41954 * <file name="app.js">
41955 * angular.module('ngrepeatSelect', [])
41956 * .controller('ExampleController', ['$scope', function($scope) {
41958 * repeatSelect: null,
41959 * availableOptions: [
41960 * {id: '1', name: 'Option A'},
41961 * {id: '2', name: 'Option B'},
41962 * {id: '3', name: 'Option C'}
41970 * ### Using `select` with `ngOptions` and setting a default value
41971 * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
41973 * <example name="select-with-default-values" module="defaultValueSelect">
41974 * <file name="index.html">
41975 * <div ng-controller="ExampleController">
41976 * <form name="myForm">
41977 * <label for="mySelect">Make a choice:</label>
41978 * <select name="mySelect" id="mySelect"
41979 * ng-options="option.name for option in data.availableOptions track by option.id"
41980 * ng-model="data.selectedOption"></select>
41983 * <tt>option = {{data.selectedOption}}</tt><br/>
41986 * <file name="app.js">
41987 * angular.module('defaultValueSelect', [])
41988 * .controller('ExampleController', ['$scope', function($scope) {
41990 * availableOptions: [
41991 * {id: '1', name: 'Option A'},
41992 * {id: '2', name: 'Option B'},
41993 * {id: '3', name: 'Option C'}
41995 * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
42002 * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
42004 * <example name="select-with-non-string-options" module="nonStringSelect">
42005 * <file name="index.html">
42006 * <select ng-model="model.id" convert-to-number>
42007 * <option value="0">Zero</option>
42008 * <option value="1">One</option>
42009 * <option value="2">Two</option>
42013 * <file name="app.js">
42014 * angular.module('nonStringSelect', [])
42015 * .run(function($rootScope) {
42016 * $rootScope.model = { id: 2 };
42018 * .directive('convertToNumber', function() {
42020 * require: 'ngModel',
42021 * link: function(scope, element, attrs, ngModel) {
42022 * ngModel.$parsers.push(function(val) {
42023 * return parseInt(val, 10);
42025 * ngModel.$formatters.push(function(val) {
42032 * <file name="protractor.js" type="protractor">
42033 * it('should initialize to model', function() {
42034 * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
42040 var selectDirective = function() {
42044 require: ['select', '?ngModel'],
42045 controller: SelectController,
42048 pre: selectPreLink,
42049 post: selectPostLink
42053 function selectPreLink(scope, element, attr, ctrls) {
42055 // if ngModel is not defined, we don't need to do anything
42056 var ngModelCtrl = ctrls[1];
42057 if (!ngModelCtrl) return;
42059 var selectCtrl = ctrls[0];
42061 selectCtrl.ngModelCtrl = ngModelCtrl;
42063 // When the selected item(s) changes we delegate getting the value of the select control
42064 // to the `readValue` method, which can be changed if the select can have multiple
42065 // selected values or if the options are being generated by `ngOptions`
42066 element.on('change', function() {
42067 scope.$apply(function() {
42068 ngModelCtrl.$setViewValue(selectCtrl.readValue());
42072 // If the select allows multiple values then we need to modify how we read and write
42073 // values from and to the control; also what it means for the value to be empty and
42074 // we have to add an extra watch since ngModel doesn't work well with arrays - it
42075 // doesn't trigger rendering if only an item in the array changes.
42076 if (attr.multiple) {
42078 // Read value now needs to check each option to see if it is selected
42079 selectCtrl.readValue = function readMultipleValue() {
42081 forEach(element.find('option'), function(option) {
42082 if (option.selected) {
42083 array.push(option.value);
42089 // Write value now needs to set the selected property of each matching option
42090 selectCtrl.writeValue = function writeMultipleValue(value) {
42091 var items = new HashMap(value);
42092 forEach(element.find('option'), function(option) {
42093 option.selected = isDefined(items.get(option.value));
42097 // we have to do it on each watch since ngModel watches reference, but
42098 // we need to work of an array, so we need to see if anything was inserted/removed
42099 var lastView, lastViewRef = NaN;
42100 scope.$watch(function selectMultipleWatch() {
42101 if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
42102 lastView = shallowCopy(ngModelCtrl.$viewValue);
42103 ngModelCtrl.$render();
42105 lastViewRef = ngModelCtrl.$viewValue;
42108 // If we are a multiple select then value is now a collection
42109 // so the meaning of $isEmpty changes
42110 ngModelCtrl.$isEmpty = function(value) {
42111 return !value || value.length === 0;
42117 function selectPostLink(scope, element, attrs, ctrls) {
42118 // if ngModel is not defined, we don't need to do anything
42119 var ngModelCtrl = ctrls[1];
42120 if (!ngModelCtrl) return;
42122 var selectCtrl = ctrls[0];
42124 // We delegate rendering to the `writeValue` method, which can be changed
42125 // if the select can have multiple selected values or if the options are being
42126 // generated by `ngOptions`.
42127 // This must be done in the postLink fn to prevent $render to be called before
42128 // all nodes have been linked correctly.
42129 ngModelCtrl.$render = function() {
42130 selectCtrl.writeValue(ngModelCtrl.$viewValue);
42136 // The option directive is purely designed to communicate the existence (or lack of)
42137 // of dynamically created (and destroyed) option elements to their containing select
42138 // directive via its controller.
42139 var optionDirective = ['$interpolate', function($interpolate) {
42143 compile: function(element, attr) {
42144 var hasDynamicValueAttr, interpolateTextFn;
42146 if (isDefined(attr.ngValue)) {
42147 // If ngValue is defined, then the value attr will be set to the result of the expression,
42148 // and the selectCtrl must set up an observer
42149 hasDynamicValueAttr = true;
42150 } else if (isDefined(attr.value)) {
42151 // If the value attr contains an interpolation, the selectCtrl must set up an observer
42152 hasDynamicValueAttr = $interpolate(attr.value, true);
42154 // If the value attribute is not defined then we fall back to the
42155 // text content of the option element, which may be interpolated
42156 interpolateTextFn = $interpolate(element.text(), true);
42157 if (!interpolateTextFn) {
42158 attr.$set('value', element.text());
42162 return function(scope, element, attr) {
42163 // This is an optimization over using ^^ since we don't want to have to search
42164 // all the way to the root of the DOM for every single option element
42165 var selectCtrlName = '$selectController',
42166 parent = element.parent(),
42167 selectCtrl = parent.data(selectCtrlName) ||
42168 parent.parent().data(selectCtrlName); // in case we are in optgroup
42171 selectCtrl.registerOption(scope, element, attr, hasDynamicValueAttr, interpolateTextFn);
42185 * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
42186 * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
42187 * applied to custom controls.
42189 * The directive sets the `required` attribute on the element if the Angular expression inside
42190 * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
42191 * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
42194 * The validator will set the `required` error key to true if the `required` attribute is set and
42195 * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
42196 * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
42197 * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
42198 * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
42201 * <example name="ngRequiredDirective" module="ngRequiredExample">
42202 * <file name="index.html">
42204 * angular.module('ngRequiredExample', [])
42205 * .controller('ExampleController', ['$scope', function($scope) {
42206 * $scope.required = true;
42209 * <div ng-controller="ExampleController">
42210 * <form name="form">
42211 * <label for="required">Toggle required: </label>
42212 * <input type="checkbox" ng-model="required" id="required" />
42214 * <label for="input">This input must be filled if `required` is true: </label>
42215 * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
42217 * required error set? = <code>{{form.input.$error.required}}</code><br>
42218 * model = <code>{{model}}</code>
42222 * <file name="protractor.js" type="protractor">
42223 var required = element(by.binding('form.input.$error.required'));
42224 var model = element(by.binding('model'));
42225 var input = element(by.id('input'));
42227 it('should set the required error', function() {
42228 expect(required.getText()).toContain('true');
42230 input.sendKeys('123');
42231 expect(required.getText()).not.toContain('true');
42232 expect(model.getText()).toContain('123');
42237 var requiredDirective = function() {
42240 require: '?ngModel',
42241 link: function(scope, elm, attr, ctrl) {
42243 attr.required = true; // force truthy in case we are on non input element
42245 ctrl.$validators.required = function(modelValue, viewValue) {
42246 return !attr.required || !ctrl.$isEmpty(viewValue);
42249 attr.$observe('required', function() {
42262 * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
42263 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
42265 * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
42266 * does not match a RegExp which is obtained by evaluating the Angular expression given in the
42267 * `ngPattern` attribute value:
42268 * * If the expression evaluates to a RegExp object, then this is used directly.
42269 * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
42270 * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
42272 * <div class="alert alert-info">
42273 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
42274 * start at the index of the last search's match, thus not taking the whole input value into
42278 * <div class="alert alert-info">
42279 * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
42283 * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
42287 * The `ngPattern` attribute must be an expression, while the `pattern` value must be
42294 * <example name="ngPatternDirective" module="ngPatternExample">
42295 * <file name="index.html">
42297 * angular.module('ngPatternExample', [])
42298 * .controller('ExampleController', ['$scope', function($scope) {
42299 * $scope.regex = '\\d+';
42302 * <div ng-controller="ExampleController">
42303 * <form name="form">
42304 * <label for="regex">Set a pattern (regex string): </label>
42305 * <input type="text" ng-model="regex" id="regex" />
42307 * <label for="input">This input is restricted by the current pattern: </label>
42308 * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
42310 * input valid? = <code>{{form.input.$valid}}</code><br>
42311 * model = <code>{{model}}</code>
42315 * <file name="protractor.js" type="protractor">
42316 var model = element(by.binding('model'));
42317 var input = element(by.id('input'));
42319 it('should validate the input with the default pattern', function() {
42320 input.sendKeys('aaa');
42321 expect(model.getText()).not.toContain('aaa');
42323 input.clear().then(function() {
42324 input.sendKeys('123');
42325 expect(model.getText()).toContain('123');
42331 var patternDirective = function() {
42334 require: '?ngModel',
42335 link: function(scope, elm, attr, ctrl) {
42338 var regexp, patternExp = attr.ngPattern || attr.pattern;
42339 attr.$observe('pattern', function(regex) {
42340 if (isString(regex) && regex.length > 0) {
42341 regex = new RegExp('^' + regex + '$');
42344 if (regex && !regex.test) {
42345 throw minErr('ngPattern')('noregexp',
42346 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
42347 regex, startingTag(elm));
42350 regexp = regex || undefined;
42354 ctrl.$validators.pattern = function(modelValue, viewValue) {
42355 // HTML5 pattern constraint validates the input value, so we validate the viewValue
42356 return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
42364 * @name ngMaxlength
42368 * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
42369 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
42371 * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
42372 * is longer than the integer obtained by evaluating the Angular expression given in the
42373 * `ngMaxlength` attribute value.
42375 * <div class="alert alert-info">
42376 * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
42380 * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
42381 * validation is not available.
42384 * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
42391 * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
42392 * <file name="index.html">
42394 * angular.module('ngMaxlengthExample', [])
42395 * .controller('ExampleController', ['$scope', function($scope) {
42396 * $scope.maxlength = 5;
42399 * <div ng-controller="ExampleController">
42400 * <form name="form">
42401 * <label for="maxlength">Set a maxlength: </label>
42402 * <input type="number" ng-model="maxlength" id="maxlength" />
42404 * <label for="input">This input is restricted by the current maxlength: </label>
42405 * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
42407 * input valid? = <code>{{form.input.$valid}}</code><br>
42408 * model = <code>{{model}}</code>
42412 * <file name="protractor.js" type="protractor">
42413 var model = element(by.binding('model'));
42414 var input = element(by.id('input'));
42416 it('should validate the input with the default maxlength', function() {
42417 input.sendKeys('abcdef');
42418 expect(model.getText()).not.toContain('abcdef');
42420 input.clear().then(function() {
42421 input.sendKeys('abcde');
42422 expect(model.getText()).toContain('abcde');
42428 var maxlengthDirective = function() {
42431 require: '?ngModel',
42432 link: function(scope, elm, attr, ctrl) {
42435 var maxlength = -1;
42436 attr.$observe('maxlength', function(value) {
42437 var intVal = toInt(value);
42438 maxlength = isNumberNaN(intVal) ? -1 : intVal;
42441 ctrl.$validators.maxlength = function(modelValue, viewValue) {
42442 return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
42450 * @name ngMinlength
42454 * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
42455 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
42457 * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
42458 * is shorter than the integer obtained by evaluating the Angular expression given in the
42459 * `ngMinlength` attribute value.
42461 * <div class="alert alert-info">
42462 * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
42466 * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
42467 * validation is not available.
42470 * The `ngMinlength` value must be an expression, while the `minlength` value must be
42477 * <example name="ngMinlengthDirective" module="ngMinlengthExample">
42478 * <file name="index.html">
42480 * angular.module('ngMinlengthExample', [])
42481 * .controller('ExampleController', ['$scope', function($scope) {
42482 * $scope.minlength = 3;
42485 * <div ng-controller="ExampleController">
42486 * <form name="form">
42487 * <label for="minlength">Set a minlength: </label>
42488 * <input type="number" ng-model="minlength" id="minlength" />
42490 * <label for="input">This input is restricted by the current minlength: </label>
42491 * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
42493 * input valid? = <code>{{form.input.$valid}}</code><br>
42494 * model = <code>{{model}}</code>
42498 * <file name="protractor.js" type="protractor">
42499 var model = element(by.binding('model'));
42500 var input = element(by.id('input'));
42502 it('should validate the input with the default minlength', function() {
42503 input.sendKeys('ab');
42504 expect(model.getText()).not.toContain('ab');
42506 input.sendKeys('abc');
42507 expect(model.getText()).toContain('abc');
42512 var minlengthDirective = function() {
42515 require: '?ngModel',
42516 link: function(scope, elm, attr, ctrl) {
42520 attr.$observe('minlength', function(value) {
42521 minlength = toInt(value) || 0;
42524 ctrl.$validators.minlength = function(modelValue, viewValue) {
42525 return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
42531 if (window.angular.bootstrap) {
42532 //AngularJS is already loaded, so we can return here...
42533 if (window.console) {
42534 console.log('WARNING: Tried to load angular more than once.');
42539 //try to bind to jquery now so that one can write jqLite(document).ready()
42540 //but we will rebind on bootstrap again.
42543 publishExternalAPI(angular);
42545 angular.module("ngLocale", [], ["$provide", function($provide) {
42546 var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
42547 function getDecimals(n) {
42549 var i = n.indexOf('.');
42550 return (i == -1) ? 0 : n.length - i - 1;
42553 function getVF(n, opt_precision) {
42554 var v = opt_precision;
42556 if (undefined === v) {
42557 v = Math.min(getDecimals(n), 3);
42560 var base = Math.pow(10, v);
42561 var f = ((n * base) | 0) % base;
42562 return {v: v, f: f};
42565 $provide.value("$locale", {
42566 "DATETIME_FORMATS": {
42588 "FIRSTDAYOFWEEK": 6,
42626 "STANDALONEMONTH": [
42644 "fullDate": "EEEE, MMMM d, y",
42645 "longDate": "MMMM d, y",
42646 "medium": "MMM d, y h:mm:ss a",
42647 "mediumDate": "MMM d, y",
42648 "mediumTime": "h:mm:ss a",
42649 "short": "M/d/yy h:mm a",
42650 "shortDate": "M/d/yy",
42651 "shortTime": "h:mm a"
42653 "NUMBER_FORMATS": {
42654 "CURRENCY_SYM": "$",
42655 "DECIMAL_SEP": ".",
42675 "negPre": "-\u00a4",
42677 "posPre": "\u00a4",
42683 "localeID": "en_US",
42684 "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
42689 * Setup file for the Scenario.
42690 * Must be first in the compilation/bootstrap list.
42693 // Public namespace
42694 angular.scenario = angular.scenario || {};
42697 * Expose jQuery (e.g. for custom dsl extensions).
42699 angular.scenario.jQuery = _jQuery;
42702 * Defines a new output format.
42704 * @param {string} name the name of the new output format
42705 * @param {function()} fn function(context, runner) that generates the output
42707 angular.scenario.output = angular.scenario.output || function(name, fn) {
42708 angular.scenario.output[name] = fn;
42712 * Defines a new DSL statement. If your factory function returns a Future
42713 * it's returned, otherwise the result is assumed to be a map of functions
42714 * for chaining. Chained functions are subject to the same rules.
42716 * Note: All functions on the chain are bound to the chain scope so values
42717 * set on "this" in your statement function are available in the chained
42720 * @param {string} name The name of the statement
42721 * @param {function()} fn Factory function(), return a function for
42724 angular.scenario.dsl = angular.scenario.dsl || function(name, fn) {
42725 angular.scenario.dsl[name] = function() {
42726 // The dsl binds `this` for us when calling chained functions
42728 function executeStatement(statement, args) {
42729 var result = statement.apply(this, args);
42730 if (angular.isFunction(result) || result instanceof angular.scenario.Future) {
42734 var chain = angular.extend({}, result);
42735 angular.forEach(chain, function(value, name) {
42736 if (angular.isFunction(value)) {
42737 chain[name] = function() {
42738 return executeStatement.call(self, value, arguments);
42741 chain[name] = value;
42746 var statement = fn.apply(this, arguments);
42747 return /** @this */ function() {
42748 return executeStatement.call(this, statement, arguments);
42754 * Defines a new matcher for use with the expects() statement. The value
42755 * this.actual (like in Jasmine) is available in your matcher to compare
42756 * against. Your function should return a boolean. The future is automatically
42759 * @param {string} name The name of the matcher
42760 * @param {function()} fn The matching function(expected).
42762 angular.scenario.matcher = angular.scenario.matcher || function(name, fn) {
42763 angular.scenario.matcher[name] = function(expected) {
42764 var description = this.future.name +
42765 (this.inverse ? ' not ' : ' ') + name +
42766 ' ' + angular.toJson(expected);
42768 this.addFuture('expect ' + description,
42771 self.actual = self.future.value;
42772 if ((self.inverse && fn.call(self, expected)) ||
42773 (!self.inverse && !fn.call(self, expected))) {
42774 error = 'expected ' + description +
42775 ' but was ' + angular.toJson(self.actual);
42783 * Initialize the scenario runner and run !
42785 * Access global window and document object
42786 * Access $runner through closure
42788 * @param {Object=} config Config options
42790 angular.scenario.setUpAndRun = function(config) {
42791 var href = window.location.href;
42792 var body = _jQuery(window.document.body);
42794 var objModel = new angular.scenario.ObjectModel($runner);
42796 if (config && config.scenario_output) {
42797 output = config.scenario_output.split(',');
42800 angular.forEach(angular.scenario.output, function(fn, name) {
42801 if (!output.length || output.indexOf(name) !== -1) {
42802 var context = body.append('<div></div>').find('div:last');
42803 context.attr('id', name);
42804 fn.call({}, context, $runner, objModel);
42808 if (!/^http/.test(href) && !/^https/.test(href)) {
42809 body.append('<p id="system-error"></p>');
42810 body.find('#system-error').text(
42811 'Scenario runner must be run using http or https. The protocol ' +
42812 href.split(':')[0] + ':// is not supported.'
42817 var appFrame = body.append('<div id="application"></div>').find('#application');
42818 var application = new angular.scenario.Application(appFrame);
42820 $runner.on('RunnerEnd', function() {
42821 appFrame.css('display', 'none');
42822 appFrame.find('iframe').attr('src', 'about:blank');
42825 $runner.on('RunnerError', function(error) {
42826 if (window.console) {
42827 console.log(formatException(error));
42829 // Do something for IE
42830 // eslint-disable-next-line no-alert
42835 $runner.run(application);
42839 * Iterates through list with iterator function that must call the
42840 * continueFunction to continue iterating.
42842 * @param {Array} list list to iterate over
42843 * @param {function()} iterator Callback function(value, continueFunction)
42844 * @param {function()} done Callback function(error, result) called when
42845 * iteration finishes or an error occurs.
42847 function asyncForEach(list, iterator, done) {
42849 function loop(error, index) {
42850 if (index && index > i) {
42853 if (error || i >= list.length) {
42857 iterator(list[i++], loop);
42867 * Formats an exception into a string with the stack trace, but limits
42868 * to a specific line length.
42870 * @param {Object} error The exception to format, can be anything throwable
42871 * @param {Number=} [maxStackLines=5] max lines of the stack trace to include
42874 function formatException(error, maxStackLines) {
42875 maxStackLines = maxStackLines || 5;
42876 var message = error.toString();
42878 var stack = error.stack.split('\n');
42879 if (stack[0].indexOf(message) === -1) {
42881 stack.unshift(error.message);
42883 message = stack.slice(0, maxStackLines).join('\n');
42889 * Returns a function that gets the file name and line number from a
42890 * location in the stack if available based on the call site.
42892 * Note: this returns another function because accessing .stack is very
42893 * expensive in Chrome.
42895 * @param {Number} offset Number of stack lines to skip
42897 function callerFile(offset) {
42898 var error = new Error();
42900 return function() {
42901 var line = (error.stack || '').split('\n')[offset];
42903 // Clean up the stack trace line
42905 if (line.indexOf('@') !== -1) {
42907 line = line.substring(line.indexOf('@') + 1);
42910 line = line.substring(line.indexOf('(') + 1).replace(')', '');
42920 * Don't use the jQuery trigger method since it works incorrectly.
42922 * jQuery notifies listeners and then changes the state of a checkbox and
42923 * does not create a real browser event. A real click changes the state of
42924 * the checkbox and then notifies listeners.
42926 * To work around this we instead use our own handler that fires a real event.
42929 // We need a handle to the original trigger function for input tests.
42930 var parentTrigger = fn._originalTrigger = fn.trigger;
42931 fn.trigger = function(type) {
42932 if (/(click|change|keydown|blur|input|mousedown|mouseup)/.test(type)) {
42933 var processDefaults = [];
42934 this.each(function(index, node) {
42935 processDefaults.push(browserTrigger(node, type));
42938 // this is not compatible with jQuery - we return an array of returned values,
42939 // so that scenario runner know whether JS code has preventDefault() of the event or not...
42940 return processDefaults;
42942 return parentTrigger.apply(this, arguments);
42947 * Finds all bindings with the substring match of name and returns an
42948 * array of their values.
42950 * @param {string} bindExp The name to match
42951 * @return {Array.<string>} String of binding values
42953 _jQuery.fn.bindings = function(windowJquery, bindExp) {
42954 var result = [], match,
42955 bindSelector = '.ng-binding:visible';
42956 if (angular.isString(bindExp)) {
42957 bindExp = bindExp.replace(/\s/g, '');
42958 match = function(actualExp) {
42960 actualExp = actualExp.replace(/\s/g, '');
42961 if (actualExp === bindExp) return true;
42962 if (actualExp.indexOf(bindExp) === 0) {
42963 return actualExp.charAt(bindExp.length) === '|';
42967 } else if (bindExp) {
42968 match = function(actualExp) {
42969 return actualExp && bindExp.exec(actualExp);
42972 match = function(actualExp) {
42973 return !!actualExp;
42976 var selection = this.find(bindSelector);
42977 if (this.is(bindSelector)) {
42978 selection = selection.add(this);
42981 function push(value) {
42982 if (angular.isUndefined(value)) {
42984 } else if (typeof value !== 'string') {
42985 value = angular.toJson(value);
42987 result.push('' + value);
42990 selection.each(/* @this Node */ function() {
42991 var element = windowJquery(this),
42993 if ((bindings = element.data('$binding'))) {
42994 for (var expressions = [], binding, j = 0, jj = bindings.length; j < jj; j++) {
42995 binding = bindings[j];
42997 if (binding.expressions) {
42998 expressions = binding.expressions;
43000 expressions = [binding];
43002 for (var scope, expression, i = 0, ii = expressions.length; i < ii; i++) {
43003 expression = expressions[i];
43004 if (match(expression)) {
43005 scope = scope || element.scope();
43006 push(scope.$eval(expression));
43017 * Triggers a browser event. Attempts to choose the right event if one is
43020 * @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement
43021 * @param {string} eventType Optional event type
43022 * @param {Object=} eventData An optional object which contains additional event data (such as x,y
43023 * coordinates, keys, etc...) that are passed into the event when triggered
43025 window.browserTrigger = function browserTrigger(element, eventType, eventData) {
43026 if (element && !element.nodeName) element = element[0];
43027 if (!element) return;
43029 eventData = eventData || {};
43030 var relatedTarget = eventData.relatedTarget || element;
43031 var keys = eventData.keys;
43032 var x = eventData.x;
43033 var y = eventData.y;
43035 var inputType = (element.type) ? element.type.toLowerCase() : null,
43036 nodeName = element.nodeName.toLowerCase();
43040 'textarea': 'change',
43041 'hidden': 'change',
43042 'password': 'change',
43047 'checkbox': 'click',
43049 'select-one': 'change',
43050 'select-multiple': 'change',
43051 '_default_': 'click'
43052 }[inputType || '_default_'];
43055 if (nodeName === 'option') {
43056 element.parentNode.value = element.value;
43057 element = element.parentNode;
43058 eventType = 'change';
43062 function pressed(key) {
43063 return keys.indexOf(key) !== -1;
43067 if (/transitionend/.test(eventType)) {
43068 if (window.WebKitTransitionEvent) {
43069 evnt = new window.WebKitTransitionEvent(eventType, eventData);
43070 evnt.initEvent(eventType, false, true);
43073 evnt = new window.TransitionEvent(eventType, eventData);
43075 evnt = window.document.createEvent('TransitionEvent');
43076 evnt.initTransitionEvent(eventType, null, null, null, eventData.elapsedTime || 0);
43079 } else if (/animationend/.test(eventType)) {
43080 if (window.WebKitAnimationEvent) {
43081 evnt = new window.WebKitAnimationEvent(eventType, eventData);
43082 evnt.initEvent(eventType, false, true);
43085 evnt = new window.AnimationEvent(eventType, eventData);
43087 evnt = window.document.createEvent('AnimationEvent');
43088 evnt.initAnimationEvent(eventType, null, null, null, eventData.elapsedTime || 0);
43091 } else if (/touch/.test(eventType) && supportsTouchEvents()) {
43092 evnt = createTouchEvent(element, eventType, x, y);
43093 } else if (/key/.test(eventType)) {
43094 evnt = window.document.createEvent('Events');
43095 evnt.initEvent(eventType, eventData.bubbles, eventData.cancelable);
43096 evnt.view = window;
43097 evnt.ctrlKey = pressed('ctrl');
43098 evnt.altKey = pressed('alt');
43099 evnt.shiftKey = pressed('shift');
43100 evnt.metaKey = pressed('meta');
43101 evnt.keyCode = eventData.keyCode;
43102 evnt.charCode = eventData.charCode;
43103 evnt.which = eventData.which;
43105 evnt = window.document.createEvent('MouseEvents');
43108 evnt.initMouseEvent(eventType, true, true, window, 0, x, y, x, y, pressed('ctrl'),
43109 pressed('alt'), pressed('shift'), pressed('meta'), 0, relatedTarget);
43112 /* we're unable to change the timeStamp value directly so this
43113 * is only here to allow for testing where the timeStamp value is
43115 evnt.$manualTimeStamp = eventData.timeStamp;
43119 var originalPreventDefault = evnt.preventDefault,
43120 appWindow = element.ownerDocument.defaultView,
43121 fakeProcessDefault = true,
43122 finalProcessDefault,
43123 angular = appWindow.angular || {};
43125 // igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208
43126 angular['ff-684208-preventDefault'] = false;
43127 evnt.preventDefault = function() {
43128 fakeProcessDefault = false;
43129 return originalPreventDefault.apply(evnt, arguments);
43132 if (!eventData.bubbles || supportsEventBubblingInDetachedTree() || isAttachedToDocument(element)) {
43133 element.dispatchEvent(evnt);
43135 triggerForPath(element, evnt);
43138 finalProcessDefault = !(angular['ff-684208-preventDefault'] || !fakeProcessDefault);
43140 delete angular['ff-684208-preventDefault'];
43142 return finalProcessDefault;
43145 function supportsTouchEvents() {
43146 if ('_cached' in supportsTouchEvents) {
43147 return supportsTouchEvents._cached;
43149 if (!window.document.createTouch || !window.document.createTouchList) {
43150 supportsTouchEvents._cached = false;
43154 window.document.createEvent('TouchEvent');
43156 supportsTouchEvents._cached = false;
43159 supportsTouchEvents._cached = true;
43163 function createTouchEvent(element, eventType, x, y) {
43164 var evnt = new window.Event(eventType);
43168 var touch = window.document.createTouch(window, element, Date.now(), x, y, x, y);
43169 var touches = window.document.createTouchList(touch);
43171 evnt.touches = touches;
43176 function supportsEventBubblingInDetachedTree() {
43177 if ('_cached' in supportsEventBubblingInDetachedTree) {
43178 return supportsEventBubblingInDetachedTree._cached;
43180 supportsEventBubblingInDetachedTree._cached = false;
43181 var doc = window.document;
43183 var parent = doc.createElement('div'),
43184 child = parent.cloneNode();
43185 parent.appendChild(child);
43186 parent.addEventListener('e', function() {
43187 supportsEventBubblingInDetachedTree._cached = true;
43189 var evnt = window.document.createEvent('Events');
43190 evnt.initEvent('e', true, true);
43191 child.dispatchEvent(evnt);
43193 return supportsEventBubblingInDetachedTree._cached;
43196 function triggerForPath(element, evnt) {
43199 var _stopPropagation = evnt.stopPropagation;
43200 evnt.stopPropagation = function() {
43202 _stopPropagation.apply(evnt, arguments);
43204 patchEventTargetForBubbling(evnt, element);
43206 element.dispatchEvent(evnt);
43207 // eslint-disable-next-line no-unmodified-loop-condition
43208 } while (!stop && (element = element.parentNode));
43211 function patchEventTargetForBubbling(event, target) {
43212 event._target = target;
43213 Object.defineProperty(event, 'target', {get: function() { return this._target;}});
43216 function isAttachedToDocument(element) {
43217 while ((element = element.parentNode)) {
43218 if (element === window) {
43227 * Represents the application currently being tested and abstracts usage
43228 * of iframes or separate windows.
43230 * @param {Object} context jQuery wrapper around HTML context.
43232 angular.scenario.Application = function(context) {
43233 this.context = context;
43235 '<h2>Current URL: <a href="about:blank">None</a></h2>' +
43236 '<div id="test-frames"></div>'
43241 * Gets the jQuery collection of frames. Don't use this directly because
43242 * frames may go stale.
43245 * @return {Object} jQuery collection
43247 angular.scenario.Application.prototype.getFrame_ = function() {
43248 return this.context.find('#test-frames iframe:last');
43252 * Gets the window of the test runner frame. Always favor executeAction()
43253 * instead of this method since it prevents you from getting a stale window.
43256 * @return {Object} the window of the frame
43258 angular.scenario.Application.prototype.getWindow_ = function() {
43259 var contentWindow = this.getFrame_().prop('contentWindow');
43260 if (!contentWindow) {
43261 throw new Error('Frame window is not accessible.');
43263 return contentWindow;
43267 * Changes the location of the frame.
43269 * @param {string} url The URL. If it begins with a # then only the
43270 * hash of the page is changed.
43271 * @param {function()} loadFn function($window, $document) Called when frame loads.
43272 * @param {function()} errorFn function(error) Called if any error when loading.
43274 angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) {
43276 var frame = self.getFrame_();
43277 //TODO(esprehn): Refactor to use rethrow()
43278 errorFn = errorFn || function(e) { throw e; };
43279 if (url === 'about:blank') {
43280 errorFn('Sandbox Error: Navigating to about:blank is not allowed.');
43281 } else if (url.charAt(0) === '#') {
43282 url = frame.attr('src').split('#')[0] + url;
43283 frame.attr('src', url);
43284 self.executeAction(loadFn);
43287 self.context.find('#test-frames').append('<iframe>');
43288 frame = self.getFrame_();
43290 frame.on('load', function() {
43293 var $window = self.getWindow_();
43295 if (!$window.angular) {
43296 self.executeAction(loadFn);
43300 if (!$window.angular.resumeBootstrap) {
43301 $window.angular.resumeDeferredBootstrap = resumeDeferredBootstrap;
43303 resumeDeferredBootstrap();
43310 function resumeDeferredBootstrap() {
43311 // Disable animations
43312 var $injector = $window.angular.resumeBootstrap([['$provide', function($provide) {
43313 return ['$animate', function($animate) {
43314 $animate.enabled(false);
43317 self.rootElement = $injector.get('$rootElement')[0];
43318 self.executeAction(loadFn);
43320 }).attr('src', url);
43322 // for IE compatibility set the name *after* setting the frame url
43323 frame[0].contentWindow.name = 'NG_DEFER_BOOTSTRAP!';
43325 self.context.find('> h2 a').attr('href', url).text(url);
43329 * Executes a function in the context of the tested application. Will wait
43330 * for all pending angular xhr requests before executing.
43332 * @param {function()} action The callback to execute. function($window, $document)
43333 * $document is a jQuery wrapped document.
43335 angular.scenario.Application.prototype.executeAction = function(action) {
43337 var $window = this.getWindow_();
43338 if (!$window.document) {
43339 throw new Error('Sandbox Error: Application document not accessible.');
43341 if (!$window.angular) {
43342 return action.call(this, $window, _jQuery($window.document));
43345 if (this.rootElement) {
43346 executeWithElement(this.rootElement);
43348 angularInit($window.document, angular.bind(this, executeWithElement));
43351 function executeWithElement(element) {
43352 var $injector = $window.angular.element(element).injector();
43353 var $element = _jQuery(element);
43355 $element.injector = function() {
43359 $injector.invoke(function($browser) {
43360 $browser.notifyWhenNoOutstandingRequests(function() {
43361 action.call(self, $window, $element);
43368 * The representation of define blocks. Don't used directly, instead use
43369 * define() in your tests.
43371 * @param {string} descName Name of the block
43372 * @param {Object} parent describe or undefined if the root.
43374 angular.scenario.Describe = function(descName, parent) {
43375 this.only = parent && parent.only;
43376 this.beforeEachFns = [];
43377 this.afterEachFns = [];
43379 this.children = [];
43380 this.name = descName;
43381 this.parent = parent;
43382 this.id = angular.scenario.Describe.id++;
43385 * Calls all before functions.
43387 var beforeEachFns = this.beforeEachFns;
43388 this.setupBefore = function() {
43389 if (parent) parent.setupBefore.call(this);
43390 angular.forEach(beforeEachFns, /** @this */ function(fn) { fn.call(this); }, this);
43394 * Calls all after functions.
43396 var afterEachFns = this.afterEachFns;
43397 this.setupAfter = function() {
43398 angular.forEach(afterEachFns, /** @this */ function(fn) { fn.call(this); }, this);
43399 if (parent) parent.setupAfter.call(this);
43403 // Shared Unique ID generator for every describe block
43404 angular.scenario.Describe.id = 0;
43406 // Shared Unique ID generator for every it (spec)
43407 angular.scenario.Describe.specId = 0;
43410 * Defines a block to execute before each it or nested describe.
43412 * @param {function()} body Body of the block.
43414 angular.scenario.Describe.prototype.beforeEach = function(body) {
43415 this.beforeEachFns.push(body);
43419 * Defines a block to execute after each it or nested describe.
43421 * @param {function()} body Body of the block.
43423 angular.scenario.Describe.prototype.afterEach = function(body) {
43424 this.afterEachFns.push(body);
43428 * Creates a new describe block that's a child of this one.
43430 * @param {string} name Name of the block. Appended to the parent block's name.
43431 * @param {function()} body Body of the block.
43433 angular.scenario.Describe.prototype.describe = function(name, body) {
43434 var child = new angular.scenario.Describe(name, this);
43435 this.children.push(child);
43440 * Same as describe() but makes ddescribe blocks the only to run.
43442 * @param {string} name Name of the test.
43443 * @param {function()} body Body of the block.
43445 angular.scenario.Describe.prototype.ddescribe = function(name, body) {
43446 var child = new angular.scenario.Describe(name, this);
43448 this.children.push(child);
43453 * Use to disable a describe block.
43455 angular.scenario.Describe.prototype.xdescribe = angular.noop;
43460 * @param {string} name Name of the test.
43461 * @param {function()} body Body of the block.
43463 angular.scenario.Describe.prototype.it = function(name, body) {
43465 id: angular.scenario.Describe.specId++,
43469 before: this.setupBefore,
43471 after: this.setupAfter
43476 * Same as it() but makes iit tests the only test to run.
43478 * @param {string} name Name of the test.
43479 * @param {function()} body Body of the block.
43481 angular.scenario.Describe.prototype.iit = function(name, body) {
43482 this.it.apply(this, arguments);
43483 this.its[this.its.length - 1].only = true;
43487 * Use to disable a test block.
43489 angular.scenario.Describe.prototype.xit = angular.noop;
43492 * Gets an array of functions representing all the tests (recursively).
43493 * that can be executed with SpecRunner's.
43495 * @return {Array<Object>} Array of it blocks {
43496 * definition : Object // parent Describe
43504 angular.scenario.Describe.prototype.getSpecs = function() {
43505 var specs = arguments[0] || [];
43506 angular.forEach(this.children, function(child) {
43507 child.getSpecs(specs);
43509 angular.forEach(this.its, function(it) {
43513 angular.forEach(specs, function(it) {
43518 return (only.length && only) || specs;
43522 * A future action in a spec.
43524 * @param {string} name name of the future action
43525 * @param {function()} behavior future callback(error, result)
43526 * @param {function()} line Optional. function that returns the file/line number.
43528 angular.scenario.Future = function(name, behavior, line) {
43530 this.behavior = behavior;
43531 this.fulfilled = false;
43532 this.value = undefined;
43533 this.parser = angular.identity;
43534 this.line = line || function() { return ''; };
43538 * Executes the behavior of the closure.
43540 * @param {function()} doneFn Callback function(error, result)
43542 angular.scenario.Future.prototype.execute = function(doneFn) {
43544 this.behavior(function(error, result) {
43545 self.fulfilled = true;
43548 result = self.parser(result);
43553 self.value = error || result;
43554 doneFn(error, result);
43559 * Configures the future to convert its final with a function fn(value)
43561 * @param {function()} fn function(value) that returns the parsed value
43563 angular.scenario.Future.prototype.parsedWith = function(fn) {
43569 * Configures the future to parse its final value from JSON
43572 angular.scenario.Future.prototype.fromJson = function() {
43573 return this.parsedWith(angular.fromJson);
43577 * Configures the future to convert its final value from objects
43580 angular.scenario.Future.prototype.toJson = function() {
43581 return this.parsedWith(angular.toJson);
43585 * Maintains an object tree from the runner events.
43587 * @param {Object} runner The scenario Runner instance to connect to.
43589 * TODO(esprehn): Every output type creates one of these, but we probably
43590 * want one global shared instance. Need to handle events better too
43591 * so the HTML output doesn't need to do spec model.getSpec(spec.id)
43594 * TODO(vojta) refactor on, emit methods (from all objects) - use inheritance
43596 angular.scenario.ObjectModel = function(runner) {
43600 this.listeners = [];
43606 runner.on('SpecBegin', function(spec) {
43607 var block = self.value,
43610 angular.forEach(self.getDefinitionPath(spec), function(def) {
43611 if (!block.children[def.name]) {
43612 block.children[def.name] = {
43619 block = block.children[def.name];
43620 definitions.push(def.name);
43623 var it = self.specMap[spec.id] =
43624 block.specs[spec.name] =
43625 new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions);
43627 // forward the event
43628 self.emit('SpecBegin', it);
43631 runner.on('SpecError', function(spec, error) {
43632 var it = self.getSpec(spec.id);
43633 it.status = 'error';
43636 // forward the event
43637 self.emit('SpecError', it, error);
43640 runner.on('SpecEnd', function(spec) {
43641 var it = self.getSpec(spec.id);
43644 // forward the event
43645 self.emit('SpecEnd', it);
43648 runner.on('StepBegin', function(spec, step) {
43649 var it = self.getSpec(spec.id);
43650 step = new angular.scenario.ObjectModel.Step(step.name);
43651 it.steps.push(step);
43653 // forward the event
43654 self.emit('StepBegin', it, step);
43657 runner.on('StepEnd', function(spec) {
43658 var it = self.getSpec(spec.id);
43659 var step = it.getLastStep();
43660 if (step.name !== step.name) {
43661 throw new Error('Events fired in the wrong order. Step names don\'t match.');
43665 // forward the event
43666 self.emit('StepEnd', it, step);
43669 runner.on('StepFailure', function(spec, step, error) {
43670 var it = self.getSpec(spec.id),
43671 modelStep = it.getLastStep();
43673 modelStep.setErrorStatus('failure', error, step.line());
43674 it.setStatusFromStep(modelStep);
43676 // forward the event
43677 self.emit('StepFailure', it, modelStep, error);
43680 runner.on('StepError', function(spec, step, error) {
43681 var it = self.getSpec(spec.id),
43682 modelStep = it.getLastStep();
43684 modelStep.setErrorStatus('error', error, step.line());
43685 it.setStatusFromStep(modelStep);
43687 // forward the event
43688 self.emit('StepError', it, modelStep, error);
43691 runner.on('RunnerBegin', function() {
43692 self.emit('RunnerBegin');
43694 runner.on('RunnerEnd', function() {
43695 self.emit('RunnerEnd');
43698 function complete(item) {
43699 item.endTime = Date.now();
43700 item.duration = item.endTime - item.startTime;
43701 item.status = item.status || 'success';
43706 * Adds a listener for an event.
43708 * @param {string} eventName Name of the event to add a handler for
43709 * @param {function()} listener Function that will be called when event is fired
43711 angular.scenario.ObjectModel.prototype.on = function(eventName, listener) {
43712 eventName = eventName.toLowerCase();
43713 this.listeners[eventName] = this.listeners[eventName] || [];
43714 this.listeners[eventName].push(listener);
43718 * Emits an event which notifies listeners and passes extra
43721 * @param {string} eventName Name of the event to fire.
43723 angular.scenario.ObjectModel.prototype.emit = function(eventName) {
43725 args = Array.prototype.slice.call(arguments, 1);
43727 eventName = eventName.toLowerCase();
43729 if (this.listeners[eventName]) {
43730 angular.forEach(this.listeners[eventName], function(listener) {
43731 listener.apply(self, args);
43737 * Computes the path of definition describe blocks that wrap around
43740 * @param spec Spec to compute the path for.
43741 * @return {Array<Describe>} The describe block path
43743 angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) {
43745 var currentDefinition = spec.definition;
43746 while (currentDefinition && currentDefinition.name) {
43747 path.unshift(currentDefinition);
43748 currentDefinition = currentDefinition.parent;
43754 * Gets a spec by id.
43756 * @param {string} id The id of the spec to get the object for.
43757 * @return {Object} the Spec instance
43759 angular.scenario.ObjectModel.prototype.getSpec = function(id) {
43760 return this.specMap[id];
43764 * A single it block.
43766 * @param {string} id Id of the spec
43767 * @param {string} name Name of the spec
43768 * @param {Array<string>=} definitionNames List of all describe block names that wrap this spec
43770 angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) {
43773 this.startTime = Date.now();
43775 this.fullDefinitionName = (definitionNames || []).join(' ');
43779 * Adds a new step to the Spec.
43781 * @param {string} name Name of the step (really name of the future)
43782 * @return {Object} the added step
43784 angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) {
43785 var step = new angular.scenario.ObjectModel.Step(name);
43786 this.steps.push(step);
43791 * Gets the most recent step.
43793 * @return {Object} the step
43795 angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() {
43796 return this.steps[this.steps.length - 1];
43800 * Set status of the Spec from given Step
43802 * @param {angular.scenario.ObjectModel.Step} step
43804 angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) {
43805 if (!this.status || step.status === 'error') {
43806 this.status = step.status;
43807 this.error = step.error;
43808 this.line = step.line;
43813 * A single step inside a Spec.
43815 * @param {string} name Name of the step
43817 angular.scenario.ObjectModel.Step = function(name) {
43819 this.startTime = Date.now();
43823 * Helper method for setting all error status related properties
43825 * @param {string} status
43826 * @param {string} error
43827 * @param {string} line
43829 angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) {
43830 this.status = status;
43831 this.error = error;
43836 * Runner for scenarios
43838 * Has to be initialized before any test is loaded,
43839 * because it publishes the API into window (global space).
43841 angular.scenario.Runner = function($window) {
43842 this.listeners = [];
43843 this.$window = $window;
43844 this.rootDescribe = new angular.scenario.Describe();
43845 this.currentDescribe = this.rootDescribe;
43850 describe: this.describe,
43851 ddescribe: this.ddescribe,
43852 xdescribe: angular.noop,
43853 beforeEach: this.beforeEach,
43854 afterEach: this.afterEach
43856 angular.forEach(this.api, angular.bind(this, /** @this */ function(fn, key) {
43857 this.$window[key] = angular.bind(this, fn);
43862 * Emits an event which notifies listeners and passes extra
43865 * @param {string} eventName Name of the event to fire.
43867 angular.scenario.Runner.prototype.emit = function(eventName) {
43869 var args = Array.prototype.slice.call(arguments, 1);
43870 eventName = eventName.toLowerCase();
43871 if (!this.listeners[eventName]) {
43874 angular.forEach(this.listeners[eventName], function(listener) {
43875 listener.apply(self, args);
43880 * Adds a listener for an event.
43882 * @param {string} eventName The name of the event to add a handler for
43883 * @param {string} listener The fn(...) that takes the extra arguments from emit()
43885 angular.scenario.Runner.prototype.on = function(eventName, listener) {
43886 eventName = eventName.toLowerCase();
43887 this.listeners[eventName] = this.listeners[eventName] || [];
43888 this.listeners[eventName].push(listener);
43892 * Defines a describe block of a spec.
43896 * @param {string} name Name of the block
43897 * @param {function()} body Body of the block
43899 angular.scenario.Runner.prototype.describe = function(name, body) {
43901 this.currentDescribe.describe(name, /** @this */ function() {
43902 var parentDescribe = self.currentDescribe;
43903 self.currentDescribe = this;
43907 self.currentDescribe = parentDescribe;
43913 * Same as describe, but makes ddescribe the only blocks to run.
43917 * @param {string} name Name of the block
43918 * @param {function()} body Body of the block
43920 angular.scenario.Runner.prototype.ddescribe = function(name, body) {
43922 this.currentDescribe.ddescribe(name, /** @this */ function() {
43923 var parentDescribe = self.currentDescribe;
43924 self.currentDescribe = this;
43928 self.currentDescribe = parentDescribe;
43934 * Defines a test in a describe block of a spec.
43938 * @param {string} name Name of the block
43939 * @param {function()} body Body of the block
43941 angular.scenario.Runner.prototype.it = function(name, body) {
43942 this.currentDescribe.it(name, body);
43946 * Same as it, but makes iit tests the only tests to run.
43950 * @param {string} name Name of the block
43951 * @param {function()} body Body of the block
43953 angular.scenario.Runner.prototype.iit = function(name, body) {
43954 this.currentDescribe.iit(name, body);
43958 * Defines a function to be called before each it block in the describe
43959 * (and before all nested describes).
43963 * @param {function()} Callback to execute
43965 angular.scenario.Runner.prototype.beforeEach = function(body) {
43966 this.currentDescribe.beforeEach(body);
43970 * Defines a function to be called after each it block in the describe
43971 * (and before all nested describes).
43975 * @param {function()} Callback to execute
43977 angular.scenario.Runner.prototype.afterEach = function(body) {
43978 this.currentDescribe.afterEach(body);
43982 * Creates a new spec runner.
43985 * @param {Object} scope parent scope
43987 angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) {
43988 var child = scope.$new();
43989 var Cls = angular.scenario.SpecRunner;
43991 // Export all the methods to child scope manually as now we don't mess controllers with scopes
43992 // TODO(vojta): refactor scenario runner so that these objects are not tightly coupled as current
43993 for (var name in Cls.prototype) {
43994 child[name] = angular.bind(child, Cls.prototype[name]);
44002 * Runs all the loaded tests with the specified runner class on the
44003 * provided application.
44005 * @param {angular.scenario.Application} application App to remote control.
44007 angular.scenario.Runner.prototype.run = function(application) {
44009 var $root = angular.injector(['ng']).get('$rootScope');
44010 angular.extend($root, this);
44011 angular.forEach(angular.scenario.Runner.prototype, function(fn, name) {
44012 $root[name] = angular.bind(self, fn);
44014 $root.application = application;
44015 $root.emit('RunnerBegin');
44016 asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) {
44018 var runner = self.createSpecRunner_($root);
44019 angular.forEach(angular.scenario.dsl, function(fn, key) {
44020 dslCache[key] = fn.call($root);
44022 angular.forEach(angular.scenario.dsl, function(fn, key) {
44023 self.$window[key] = function() {
44024 var line = callerFile(3);
44025 var scope = runner.$new();
44027 // Make the dsl accessible on the current chain
44029 angular.forEach(dslCache, function(fn, key) {
44030 scope.dsl[key] = function() {
44031 return dslCache[key].apply(scope, arguments);
44035 // Make these methods work on the current chain
44036 scope.addFuture = function() {
44037 Array.prototype.push.call(arguments, line);
44038 return angular.scenario.SpecRunner.
44039 prototype.addFuture.apply(scope, arguments);
44041 scope.addFutureAction = function() {
44042 Array.prototype.push.call(arguments, line);
44043 return angular.scenario.SpecRunner.
44044 prototype.addFutureAction.apply(scope, arguments);
44047 return scope.dsl[key].apply(scope, arguments);
44050 runner.run(spec, /** @this */ function() {
44052 specDone.apply(this, arguments);
44057 self.emit('RunnerError', error);
44059 self.emit('RunnerEnd');
44064 * This class is the "this" of the it/beforeEach/afterEach method.
44065 * Responsibilities:
44066 * - "this" for it/beforeEach/afterEach
44067 * - keep state for single it/beforeEach/afterEach execution
44068 * - keep track of all of the futures to execute
44069 * - run single spec (execute each future)
44071 angular.scenario.SpecRunner = function() {
44073 this.afterIndex = 0;
44077 * Executes a spec which is an it block with associated before/after functions
44078 * based on the describe nesting.
44080 * @param {Object} spec A spec object
44081 * @param {function()} specDone function that is called when the spec finishes,
44082 * of the form `Function(error, index)`
44084 angular.scenario.SpecRunner.prototype.run = function(spec, specDone) {
44088 this.emit('SpecBegin', spec);
44091 spec.before.call(this);
44092 spec.body.call(this);
44093 this.afterIndex = this.futures.length;
44094 spec.after.call(this);
44096 this.emit('SpecError', spec, e);
44097 this.emit('SpecEnd', spec);
44102 var handleError = function(error, done) {
44107 done(null, self.afterIndex);
44112 function(future, futureDone) {
44113 self.step = future;
44114 self.emit('StepBegin', spec, future);
44116 future.execute(function(error) {
44118 self.emit('StepFailure', spec, future, error);
44119 self.emit('StepEnd', spec, future);
44120 return handleError(error, futureDone);
44122 self.emit('StepEnd', spec, future);
44123 self.$window.setTimeout(function() { futureDone(); }, 0);
44126 self.emit('StepError', spec, future, e);
44127 self.emit('StepEnd', spec, future);
44128 handleError(e, futureDone);
44133 self.emit('SpecError', spec, e);
44135 self.emit('SpecEnd', spec);
44136 // Call done in a timeout so exceptions don't recursively
44137 // call this function
44138 self.$window.setTimeout(function() { specDone(); }, 0);
44144 * Adds a new future action.
44146 * Note: Do not pass line manually. It happens automatically.
44148 * @param {string} name Name of the future
44149 * @param {function()} behavior Behavior of the future
44150 * @param {function()} line fn() that returns file/line number
44152 angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) {
44153 var future = new angular.scenario.Future(name, angular.bind(this, behavior), line);
44154 this.futures.push(future);
44159 * Adds a new future action to be executed on the application window.
44161 * Note: Do not pass line manually. It happens automatically.
44163 * @param {string} name Name of the future
44164 * @param {function()} behavior Behavior of the future
44165 * @param {function()} line fn() that returns file/line number
44167 angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) {
44169 var NG = /\[ng\\:/;
44170 return this.addFuture(name, /** @this */ function(done) {
44171 this.application.executeAction(function($window, $document) {
44173 //TODO(esprehn): Refactor this so it doesn't need to be in here.
44174 $document.elements = function(selector) {
44175 var args = Array.prototype.slice.call(arguments, 1);
44176 selector = (self.selector || '') + ' ' + (selector || '');
44177 selector = _jQuery.trim(selector) || '*';
44178 angular.forEach(args, function(value, index) {
44179 selector = selector.replace('$' + (index + 1), value);
44181 var result = $document.find(selector);
44182 if (selector.match(NG)) {
44183 angular.forEach(['[ng-','[data-ng-','[x-ng-'], function(value, index) {
44184 result = result.add(selector.replace(NG, value), $document);
44187 if (!result.length) {
44188 // eslint-disable-next-line no-throw-literal
44191 message: 'Selector ' + selector + ' did not match any elements.'
44199 behavior.call(self, $window, $document, done);
44201 if (e.type && e.type === 'selector') {
44211 /* eslint-disable no-invalid-this */
44214 * Shared DSL statements that are useful to all scenarios.
44219 * pause() pauses until you call resume() in the console
44221 angular.scenario.dsl('pause', function() {
44222 return function() {
44223 return this.addFuture('pausing for you to resume', function(done) {
44224 this.emit('InteractivePause', this.spec, this.step);
44225 this.$window.resume = function() { done(); };
44232 * sleep(seconds) pauses the test for specified number of seconds
44234 angular.scenario.dsl('sleep', function() {
44235 return function(time) {
44236 return this.addFuture('sleep for ' + time + ' seconds', function(done) {
44237 this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000);
44244 * browser().navigateTo(url) Loads the url into the frame
44245 * browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to
44246 * browser().reload() refresh the page (reload the same URL)
44247 * browser().window.href() window.location.href
44248 * browser().window.path() window.location.pathname
44249 * browser().window.search() window.location.search
44250 * browser().window.hash() window.location.hash without # prefix
44251 * browser().location().url() see ng.$location#url
44252 * browser().location().path() see ng.$location#path
44253 * browser().location().search() see ng.$location#search
44254 * browser().location().hash() see ng.$location#hash
44256 angular.scenario.dsl('browser', function() {
44259 chain.navigateTo = function(url, delegate) {
44260 var application = this.application;
44261 return this.addFuture('browser navigate to \'' + url + '\'', function(done) {
44263 url = delegate.call(this, url);
44265 application.navigateTo(url, function() {
44271 chain.reload = function() {
44272 var application = this.application;
44273 return this.addFutureAction('browser reload', function($window, $document, done) {
44274 var href = $window.location.href;
44275 application.navigateTo(href, function() {
44281 chain.window = function() {
44284 api.href = function() {
44285 return this.addFutureAction('window.location.href', function($window, $document, done) {
44286 done(null, $window.location.href);
44290 api.path = function() {
44291 return this.addFutureAction('window.location.path', function($window, $document, done) {
44292 done(null, $window.location.pathname);
44296 api.search = function() {
44297 return this.addFutureAction('window.location.search', function($window, $document, done) {
44298 done(null, $window.location.search);
44302 api.hash = function() {
44303 return this.addFutureAction('window.location.hash', function($window, $document, done) {
44304 done(null, $window.location.hash.replace('#', ''));
44311 chain.location = function() {
44314 api.url = function() {
44315 return this.addFutureAction('$location.url()', function($window, $document, done) {
44316 done(null, $document.injector().get('$location').url());
44320 api.path = function() {
44321 return this.addFutureAction('$location.path()', function($window, $document, done) {
44322 done(null, $document.injector().get('$location').path());
44326 api.search = function() {
44327 return this.addFutureAction('$location.search()', function($window, $document, done) {
44328 done(null, $document.injector().get('$location').search());
44332 api.hash = function() {
44333 return this.addFutureAction('$location.hash()', function($window, $document, done) {
44334 done(null, $document.injector().get('$location').hash());
44341 return function() {
44348 * expect(future).{matcher} where matcher is one of the matchers defined
44349 * with angular.scenario.matcher
44351 * ex. expect(binding("name")).toEqual("Elliott")
44353 angular.scenario.dsl('expect', function() {
44354 var chain = angular.extend({}, angular.scenario.matcher);
44356 chain.not = function() {
44357 this.inverse = true;
44361 return function(future) {
44362 this.future = future;
44369 * using(selector, label) scopes the next DSL element selection
44372 * using('#foo', "'Foo' text field").input('bar')
44374 angular.scenario.dsl('using', function() {
44375 return function(selector, label) {
44376 this.selector = _jQuery.trim((this.selector || '') + ' ' + selector);
44377 if (angular.isString(label) && label.length) {
44378 this.label = label + ' ( ' + this.selector + ' )';
44380 this.label = this.selector;
44388 * binding(name) returns the value of the first matching binding
44390 angular.scenario.dsl('binding', function() {
44391 return function(name) {
44392 return this.addFutureAction('select binding \'' + name + '\'',
44393 function($window, $document, done) {
44394 var values = $document.elements().bindings($window.angular.element, name);
44395 if (!values.length) {
44396 return done('Binding selector \'' + name + '\' did not match.');
44398 done(null, values[0]);
44405 * input(name).enter(value) enters value in input with specified name
44406 * input(name).check() checks checkbox
44407 * input(name).select(value) selects the radio button with specified name/value
44408 * input(name).val() returns the value of the input.
44410 angular.scenario.dsl('input', function() {
44412 var supportInputEvent = 'oninput' in window.document.createElement('div') && !msie;
44414 chain.enter = function(value, event) {
44415 return this.addFutureAction('input \'' + this.name + '\' enter \'' + value + '\'',
44416 function($window, $document, done) {
44417 var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input');
44419 input.trigger(event || (supportInputEvent ? 'input' : 'change'));
44424 chain.check = function() {
44425 return this.addFutureAction('checkbox \'' + this.name + '\' toggle',
44426 function($window, $document, done) {
44427 var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':checkbox');
44428 input.trigger('click');
44433 chain.select = function(value) {
44434 return this.addFutureAction('radio button \'' + this.name + '\' toggle \'' + value + '\'',
44435 function($window, $document, done) {
44436 var input = $document.
44437 elements('[ng\\:model="$1"][value="$2"]', this.name, value).filter(':radio');
44438 input.trigger('click');
44443 chain.val = function() {
44444 return this.addFutureAction('return input val', function($window, $document, done) {
44445 var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input');
44446 done(null,input.val());
44450 return function(name) {
44459 * repeater('#products table', 'Product List').count() number of rows
44460 * repeater('#products table', 'Product List').row(1) all bindings in row as an array
44461 * repeater('#products table', 'Product List').column('product.name') all values across all rows
44464 angular.scenario.dsl('repeater', function() {
44467 chain.count = function() {
44468 return this.addFutureAction('repeater \'' + this.label + '\' count',
44469 function($window, $document, done) {
44471 done(null, $document.elements().length);
44478 chain.column = function(binding) {
44479 return this.addFutureAction('repeater \'' + this.label + '\' column \'' + binding + '\'',
44480 function($window, $document, done) {
44481 done(null, $document.elements().bindings($window.angular.element, binding));
44485 chain.row = function(index) {
44486 return this.addFutureAction('repeater \'' + this.label + '\' row \'' + index + '\'',
44487 function($window, $document, done) {
44488 var matches = $document.elements().slice(index, index + 1);
44489 if (!matches.length) {
44490 return done('row ' + index + ' out of bounds');
44492 done(null, matches.bindings($window.angular.element));
44496 return function(selector, label) {
44497 this.dsl.using(selector, label);
44504 * select(name).option('value') select one option
44505 * select(name).options('value1', 'value2', ...) select options from a multi select
44507 angular.scenario.dsl('select', function() {
44510 chain.option = function(value) {
44511 return this.addFutureAction('select \'' + this.name + '\' option \'' + value + '\'',
44512 function($window, $document, done) {
44513 var select = $document.elements('select[ng\\:model="$1"]', this.name);
44514 var option = select.find('option[value="' + value + '"]');
44515 if (option.length) {
44518 option = select.find('option').filter(function() {
44519 return _jQuery(this).text() === value;
44521 if (!option.length) {
44522 option = select.find('option:contains("' + value + '")');
44524 if (option.length) {
44525 select.val(option.val());
44527 return done('option \'' + value + '\' not found');
44530 select.trigger('change');
44535 chain.options = function() {
44536 var values = arguments;
44537 return this.addFutureAction('select \'' + this.name + '\' options \'' + values + '\'',
44538 function($window, $document, done) {
44539 var select = $document.elements('select[multiple][ng\\:model="$1"]', this.name);
44540 select.val(values);
44541 select.trigger('change');
44546 return function(name) {
44554 * element(selector, label).count() get the number of elements that match selector
44555 * element(selector, label).click() clicks an element
44556 * element(selector, label).mouseover() mouseover an element
44557 * element(selector, label).mousedown() mousedown an element
44558 * element(selector, label).mouseup() mouseup an element
44559 * element(selector, label).query(fn) executes fn(selectedElements, done)
44560 * element(selector, label).{method}() gets the value (as defined by jQuery, ex. val)
44561 * element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val)
44562 * element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr)
44563 * element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr)
44565 angular.scenario.dsl('element', function() {
44566 var KEY_VALUE_METHODS = ['attr', 'css', 'prop'];
44567 var VALUE_METHODS = [
44568 'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width',
44569 'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset'
44573 chain.count = function() {
44574 return this.addFutureAction('element \'' + this.label + '\' count',
44575 function($window, $document, done) {
44577 done(null, $document.elements().length);
44584 chain.click = function() {
44585 return this.addFutureAction('element \'' + this.label + '\' click',
44586 function($window, $document, done) {
44587 var elements = $document.elements();
44588 var href = elements.attr('href');
44589 var eventProcessDefault = elements.trigger('click')[0];
44591 if (href && elements[0].nodeName.toLowerCase() === 'a' && eventProcessDefault) {
44592 this.application.navigateTo(href, function() {
44601 chain.dblclick = function() {
44602 return this.addFutureAction('element \'' + this.label + '\' dblclick',
44603 function($window, $document, done) {
44604 var elements = $document.elements();
44605 var href = elements.attr('href');
44606 var eventProcessDefault = elements.trigger('dblclick')[0];
44608 if (href && elements[0].nodeName.toLowerCase() === 'a' && eventProcessDefault) {
44609 this.application.navigateTo(href, function() {
44618 chain.mouseover = function() {
44619 return this.addFutureAction('element \'' + this.label + '\' mouseover',
44620 function($window, $document, done) {
44621 var elements = $document.elements();
44622 elements.trigger('mouseover');
44627 chain.mousedown = function() {
44628 return this.addFutureAction('element \'' + this.label + '\' mousedown',
44629 function($window, $document, done) {
44630 var elements = $document.elements();
44631 elements.trigger('mousedown');
44636 chain.mouseup = function() {
44637 return this.addFutureAction('element \'' + this.label + '\' mouseup',
44638 function($window, $document, done) {
44639 var elements = $document.elements();
44640 elements.trigger('mouseup');
44645 chain.query = function(fn) {
44646 return this.addFutureAction('element ' + this.label + ' custom query',
44647 function($window, $document, done) {
44648 fn.call(this, $document.elements(), done);
44652 angular.forEach(KEY_VALUE_METHODS, function(methodName) {
44653 chain[methodName] = function(name, value) {
44654 var args = arguments,
44655 futureName = (args.length === 1)
44656 ? 'element \'' + this.label + '\' get ' + methodName + ' \'' + name + '\''
44657 : 'element \'' + this.label + '\' set ' + methodName + ' \'' + name + '\' to \'' +
44660 return this.addFutureAction(futureName, function($window, $document, done) {
44661 var element = $document.elements();
44662 done(null, element[methodName].apply(element, args));
44667 angular.forEach(VALUE_METHODS, function(methodName) {
44668 chain[methodName] = function(value) {
44669 var args = arguments,
44670 futureName = (args.length === 0)
44671 ? 'element \'' + this.label + '\' ' + methodName
44672 : 'element \'' + this.label + '\' set ' + methodName + ' to \'' + value + '\'';
44674 return this.addFutureAction(futureName, function($window, $document, done) {
44675 var element = $document.elements();
44676 done(null, element[methodName].apply(element, args));
44681 return function(selector, label) {
44682 this.dsl.using(selector, label);
44688 * Matchers for implementing specs. Follows the Jasmine spec conventions.
44691 angular.scenario.matcher('toEqual', /** @this */ function(expected) {
44692 return angular.equals(this.actual, expected);
44695 angular.scenario.matcher('toBe', /** @this */ function(expected) {
44696 return this.actual === expected;
44699 angular.scenario.matcher('toBeDefined', /** @this */ function() {
44700 return angular.isDefined(this.actual);
44703 angular.scenario.matcher('toBeTruthy', /** @this */ function() {
44704 return this.actual;
44707 angular.scenario.matcher('toBeFalsy', /** @this */ function() {
44708 return !this.actual;
44711 angular.scenario.matcher('toMatch', /** @this */ function(expected) {
44712 return new RegExp(expected).test(this.actual);
44715 angular.scenario.matcher('toBeNull', /** @this */ function() {
44716 return this.actual === null;
44719 angular.scenario.matcher('toContain', /** @this */ function(expected) {
44720 return includes(this.actual, expected);
44723 angular.scenario.matcher('toBeLessThan', /** @this */ function(expected) {
44724 return this.actual < expected;
44727 angular.scenario.matcher('toBeGreaterThan', /** @this */ function(expected) {
44728 return this.actual > expected;
44732 * User Interface for the Scenario Runner.
44734 * TODO(esprehn): This should be refactored now that ObjectModel exists
44735 * to use angular bindings for the UI.
44737 angular.scenario.output('html', function(context, runner, model) {
44738 var specUiMap = {},
44739 lastStepUiMap = {};
44742 '<div id="header">' +
44743 ' <h1><span class="angular">AngularJS</span>: Scenario Test Runner</h1>' +
44744 ' <ul id="status-legend" class="status-display">' +
44745 ' <li class="status-error">0 Errors</li>' +
44746 ' <li class="status-failure">0 Failures</li>' +
44747 ' <li class="status-success">0 Passed</li>' +
44750 '<div id="specs">' +
44751 ' <div class="test-children"></div>' +
44755 runner.on('InteractivePause', function(spec) {
44756 var ui = lastStepUiMap[spec.id];
44757 ui.find('.test-title').
44758 html('paused... <a href="javascript:resume()">resume</a> when ready.');
44761 runner.on('SpecBegin', function(spec) {
44762 var ui = findContext(spec);
44763 ui.find('> .tests').append(
44764 '<li class="status-pending test-it"></li>'
44766 ui = ui.find('> .tests li:last');
44768 '<div class="test-info">' +
44769 ' <p class="test-title">' +
44770 ' <span class="timer-result"></span>' +
44771 ' <span class="test-name"></span>' +
44774 '<div class="scrollpane">' +
44775 ' <ol class="test-actions"></ol>' +
44778 ui.find('> .test-info .test-name').text(spec.name);
44779 ui.find('> .test-info').click(function() {
44780 var scrollpane = ui.find('> .scrollpane');
44781 var actions = scrollpane.find('> .test-actions');
44782 var name = context.find('> .test-info .test-name');
44783 if (actions.find(':visible').length) {
44785 name.removeClass('open').addClass('closed');
44788 scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
44789 name.removeClass('closed').addClass('open');
44793 specUiMap[spec.id] = ui;
44796 runner.on('SpecError', function(spec, error) {
44797 var ui = specUiMap[spec.id];
44798 ui.append('<pre></pre>');
44799 ui.find('> pre').text(formatException(error));
44802 runner.on('SpecEnd', function(spec) {
44803 var ui = specUiMap[spec.id];
44804 spec = model.getSpec(spec.id);
44805 ui.removeClass('status-pending');
44806 ui.addClass('status-' + spec.status);
44807 ui.find('> .test-info .timer-result').text(spec.duration + 'ms');
44808 if (spec.status === 'success') {
44809 ui.find('> .test-info .test-name').addClass('closed');
44810 ui.find('> .scrollpane .test-actions').hide();
44812 updateTotals(spec.status);
44815 runner.on('StepBegin', function(spec, step) {
44816 var ui = specUiMap[spec.id];
44817 spec = model.getSpec(spec.id);
44818 step = spec.getLastStep();
44819 ui.find('> .scrollpane .test-actions').append('<li class="status-pending"></li>');
44820 var stepUi = lastStepUiMap[spec.id] = ui.find('> .scrollpane .test-actions li:last');
44822 '<div class="timer-result"></div>' +
44823 '<div class="test-title"></div>'
44825 stepUi.find('> .test-title').text(step.name);
44826 var scrollpane = stepUi.parents('.scrollpane');
44827 scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
44830 runner.on('StepFailure', function(spec, step, error) {
44831 var ui = lastStepUiMap[spec.id];
44832 addError(ui, step.line, error);
44835 runner.on('StepError', function(spec, step, error) {
44836 var ui = lastStepUiMap[spec.id];
44837 addError(ui, step.line, error);
44840 runner.on('StepEnd', function(spec, step) {
44841 var stepUi = lastStepUiMap[spec.id];
44842 spec = model.getSpec(spec.id);
44843 step = spec.getLastStep();
44844 stepUi.find('.timer-result').text(step.duration + 'ms');
44845 stepUi.removeClass('status-pending');
44846 stepUi.addClass('status-' + step.status);
44847 var scrollpane = specUiMap[spec.id].find('> .scrollpane');
44848 scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
44852 * Finds the context of a spec block defined by the passed definition.
44854 * @param {Object} The definition created by the Describe object.
44856 function findContext(spec) {
44857 var currentContext = context.find('#specs');
44858 angular.forEach(model.getDefinitionPath(spec), function(defn) {
44859 var id = 'describe-' + defn.id;
44860 if (!context.find('#' + id).length) {
44861 currentContext.find('> .test-children').append(
44862 '<div class="test-describe" id="' + id + '">' +
44864 ' <div class="test-children"></div>' +
44865 ' <ul class="tests"></ul>' +
44868 context.find('#' + id).find('> h2').text('describe: ' + defn.name);
44870 currentContext = context.find('#' + id);
44872 return context.find('#describe-' + spec.definition.id);
44876 * Updates the test counter for the status.
44878 * @param {string} the status.
44880 function updateTotals(status) {
44881 var legend = context.find('#status-legend .status-' + status);
44882 var parts = legend.text().split(' ');
44883 var value = (parts[0] * 1) + 1;
44884 legend.text(value + ' ' + parts[1]);
44888 * Add an error to a step.
44890 * @param {Object} The JQuery wrapped context
44891 * @param {function()} fn() that should return the file/line number of the error
44892 * @param {Object} the error.
44894 function addError(context, line, error) {
44895 context.find('.test-title').append('<pre></pre>');
44896 var message = _jQuery.trim(line() + '\n\n' + formatException(error));
44897 context.find('.test-title pre:last').text(message);
44902 * Generates JSON output into a context.
44904 angular.scenario.output('json', function(context, runner, model) {
44905 model.on('RunnerEnd', function() {
44906 context.text(angular.toJson(model.value));
44911 * Generates XML output into a context.
44913 angular.scenario.output('xml', function(context, runner, model) {
44914 var $ = function(args) {
44915 // eslint-disable-next-line new-cap
44916 return new context.init(args);
44918 model.on('RunnerEnd', function() {
44919 var scenario = $('<scenario></scenario>');
44920 context.append(scenario);
44921 serializeXml(scenario, model.value);
44925 * Convert the tree into XML.
44927 * @param {Object} context jQuery context to add the XML to.
44928 * @param {Object} tree node to serialize
44930 function serializeXml(context, tree) {
44931 angular.forEach(tree.children, function(child) {
44932 var describeContext = $('<describe></describe>');
44933 describeContext.attr('id', child.id);
44934 describeContext.attr('name', child.name);
44935 context.append(describeContext);
44936 serializeXml(describeContext, child);
44938 var its = $('<its></its>');
44939 context.append(its);
44940 angular.forEach(tree.specs, function(spec) {
44941 var it = $('<it></it>');
44942 it.attr('id', spec.id);
44943 it.attr('name', spec.name);
44944 it.attr('duration', spec.duration);
44945 it.attr('status', spec.status);
44947 angular.forEach(spec.steps, function(step) {
44948 var stepContext = $('<step></step>');
44949 stepContext.attr('name', step.name);
44950 stepContext.attr('duration', step.duration);
44951 stepContext.attr('status', step.status);
44952 it.append(stepContext);
44954 var error = $('<error></error>');
44955 stepContext.append(error);
44956 error.text(formatException(step.error));
44964 * Creates a global value $result with the result of the runner.
44966 angular.scenario.output('object', function(context, runner, model) {
44967 runner.$window.$result = model.value;
44971 publishExternalAPI(angular);
44973 var $runner = new angular.scenario.Runner(window),
44974 scripts = window.document.getElementsByTagName('script'),
44975 script = scripts[scripts.length - 1],
44978 angular.forEach(script.attributes, function(attr) {
44979 var match = attr.name.match(/ng[:\-](.*)/);
44981 config[match[1]] = attr.value || true;
44985 if (config.autotest) {
44986 JQLite(window.document).ready(function() {
44987 angular.scenario.setUpAndRun(config);
44993 !window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";\n\n[ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],\n.ng-cloak, .x-ng-cloak,\n.ng-hide:not(.ng-hide-animate) {\n display: none !important;\n}\n\nng\\:form {\n display: block;\n}\n\n.ng-animate-shim {\n visibility:hidden;\n}\n\n.ng-anchor {\n position:absolute;\n}\n</style>');
44994 !window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>');