Initial OpenECOMP Portal commit
[portal.git] / ecomp-portal-FE / client / bower_components / angular-scenario / angular-scenario.js
1 /*eslint-disable no-unused-vars*/
2 /*!
3  * jQuery JavaScript Library v3.1.0
4  * https://jquery.com/
5  *
6  * Includes Sizzle.js
7  * https://sizzlejs.com/
8  *
9  * Copyright jQuery Foundation and other contributors
10  * Released under the MIT license
11  * https://jquery.org/license
12  *
13  * Date: 2016-07-07T21:44Z
14  */
15 ( function( global, factory ) {
16
17 if ( typeof module === "object" && typeof module.exports === "object" ) {
18
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 ) :
28                         function( w ) {
29                                 if ( !w.document ) {
30                                         throw new Error( "jQuery requires a window with a document" );
31                                 }
32                                 return factory( w );
33                         };
34         } else {
35                 factory( global );
36         }
37
38 // Pass this if window is not defined yet
39 } )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
40
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.
45
46 var arr = [];
47
48 var document = window.document;
49
50 var getProto = Object.getPrototypeOf;
51
52 var slice = arr.slice;
53
54 var concat = arr.concat;
55
56 var push = arr.push;
57
58 var indexOf = arr.indexOf;
59
60 var class2type = {};
61
62 var toString = class2type.toString;
63
64 var hasOwn = class2type.hasOwnProperty;
65
66 var fnToString = hasOwn.toString;
67
68 var ObjectFunctionString = fnToString.call( Object );
69
70 var support = {};
71
72
73
74         function DOMEval( code, doc ) {
75                 doc = doc || document;
76
77                 var script = doc.createElement( "script" );
78
79                 script.text = code;
80                 doc.head.appendChild( script ).parentNode.removeChild( script );
81         }
82 /* global Symbol */
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
85
86
87
88 var
89         version = "3.1.0",
90
91         // Define a local copy of jQuery
92         jQuery = function( selector, context ) {
93
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 );
97         },
98
99         // Support: Android <=4.0 only
100         // Make sure we trim BOM and NBSP
101         rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
102
103         // Matches dashed string for camelizing
104         rmsPrefix = /^-ms-/,
105         rdashAlpha = /-([a-z])/g,
106
107         // Used by jQuery.camelCase as callback to replace()
108         fcamelCase = function( all, letter ) {
109                 return letter.toUpperCase();
110         };
111
112 jQuery.fn = jQuery.prototype = {
113
114         // The current version of jQuery being used
115         jquery: version,
116
117         constructor: jQuery,
118
119         // The default length of a jQuery object is 0
120         length: 0,
121
122         toArray: function() {
123                 return slice.call( this );
124         },
125
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 ) {
129                 return num != null ?
130
131                         // Return just the one element from the set
132                         ( num < 0 ? this[ num + this.length ] : this[ num ] ) :
133
134                         // Return all the elements in a clean array
135                         slice.call( this );
136         },
137
138         // Take an array of elements and push it onto the stack
139         // (returning the new matched element set)
140         pushStack: function( elems ) {
141
142                 // Build a new jQuery matched element set
143                 var ret = jQuery.merge( this.constructor(), elems );
144
145                 // Add the old object onto the stack (as a reference)
146                 ret.prevObject = this;
147
148                 // Return the newly-formed element set
149                 return ret;
150         },
151
152         // Execute a callback for every element in the matched set.
153         each: function( callback ) {
154                 return jQuery.each( this, callback );
155         },
156
157         map: function( callback ) {
158                 return this.pushStack( jQuery.map( this, function( elem, i ) {
159                         return callback.call( elem, i, elem );
160                 } ) );
161         },
162
163         slice: function() {
164                 return this.pushStack( slice.apply( this, arguments ) );
165         },
166
167         first: function() {
168                 return this.eq( 0 );
169         },
170
171         last: function() {
172                 return this.eq( -1 );
173         },
174
175         eq: function( i ) {
176                 var len = this.length,
177                         j = +i + ( i < 0 ? len : 0 );
178                 return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
179         },
180
181         end: function() {
182                 return this.prevObject || this.constructor();
183         },
184
185         // For internal use only.
186         // Behaves like an Array's method, not like a jQuery method.
187         push: push,
188         sort: arr.sort,
189         splice: arr.splice
190 };
191
192 jQuery.extend = jQuery.fn.extend = function() {
193         var options, name, src, copy, copyIsArray, clone,
194                 target = arguments[ 0 ] || {},
195                 i = 1,
196                 length = arguments.length,
197                 deep = false;
198
199         // Handle a deep copy situation
200         if ( typeof target === "boolean" ) {
201                 deep = target;
202
203                 // Skip the boolean and the target
204                 target = arguments[ i ] || {};
205                 i++;
206         }
207
208         // Handle case when target is a string or something (possible in deep copy)
209         if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
210                 target = {};
211         }
212
213         // Extend jQuery itself if only one argument is passed
214         if ( i === length ) {
215                 target = this;
216                 i--;
217         }
218
219         for ( ; i < length; i++ ) {
220
221                 // Only deal with non-null/undefined values
222                 if ( ( options = arguments[ i ] ) != null ) {
223
224                         // Extend the base object
225                         for ( name in options ) {
226                                 src = target[ name ];
227                                 copy = options[ name ];
228
229                                 // Prevent never-ending loop
230                                 if ( target === copy ) {
231                                         continue;
232                                 }
233
234                                 // Recurse if we're merging plain objects or arrays
235                                 if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
236                                         ( copyIsArray = jQuery.isArray( copy ) ) ) ) {
237
238                                         if ( copyIsArray ) {
239                                                 copyIsArray = false;
240                                                 clone = src && jQuery.isArray( src ) ? src : [];
241
242                                         } else {
243                                                 clone = src && jQuery.isPlainObject( src ) ? src : {};
244                                         }
245
246                                         // Never move original objects, clone them
247                                         target[ name ] = jQuery.extend( deep, clone, copy );
248
249                                 // Don't bring in undefined values
250                                 } else if ( copy !== undefined ) {
251                                         target[ name ] = copy;
252                                 }
253                         }
254                 }
255         }
256
257         // Return the modified object
258         return target;
259 };
260
261 jQuery.extend( {
262
263         // Unique for each copy of jQuery on the page
264         expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
265
266         // Assume jQuery is ready without the ready module
267         isReady: true,
268
269         error: function( msg ) {
270                 throw new Error( msg );
271         },
272
273         noop: function() {},
274
275         isFunction: function( obj ) {
276                 return jQuery.type( obj ) === "function";
277         },
278
279         isArray: Array.isArray,
280
281         isWindow: function( obj ) {
282                 return obj != null && obj === obj.window;
283         },
284
285         isNumeric: function( obj ) {
286
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" ) &&
292
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 ) );
297         },
298
299         isPlainObject: function( obj ) {
300                 var proto, Ctor;
301
302                 // Detect obvious negatives
303                 // Use toString instead of jQuery.type to catch host objects
304                 if ( !obj || toString.call( obj ) !== "[object Object]" ) {
305                         return false;
306                 }
307
308                 proto = getProto( obj );
309
310                 // Objects with no prototype (e.g., `Object.create( null )`) are plain
311                 if ( !proto ) {
312                         return true;
313                 }
314
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;
318         },
319
320         isEmptyObject: function( obj ) {
321
322                 /* eslint-disable no-unused-vars */
323                 // See https://github.com/eslint/eslint/issues/6125
324                 var name;
325
326                 for ( name in obj ) {
327                         return false;
328                 }
329                 return true;
330         },
331
332         type: function( obj ) {
333                 if ( obj == null ) {
334                         return obj + "";
335                 }
336
337                 // Support: Android <=2.3 only (functionish RegExp)
338                 return typeof obj === "object" || typeof obj === "function" ?
339                         class2type[ toString.call( obj ) ] || "object" :
340                         typeof obj;
341         },
342
343         // Evaluates a script in a global context
344         globalEval: function( code ) {
345                 DOMEval( code );
346         },
347
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 );
353         },
354
355         nodeName: function( elem, name ) {
356                 return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
357         },
358
359         each: function( obj, callback ) {
360                 var length, i = 0;
361
362                 if ( isArrayLike( obj ) ) {
363                         length = obj.length;
364                         for ( ; i < length; i++ ) {
365                                 if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
366                                         break;
367                                 }
368                         }
369                 } else {
370                         for ( i in obj ) {
371                                 if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
372                                         break;
373                                 }
374                         }
375                 }
376
377                 return obj;
378         },
379
380         // Support: Android <=4.0 only
381         trim: function( text ) {
382                 return text == null ?
383                         "" :
384                         ( text + "" ).replace( rtrim, "" );
385         },
386
387         // results is for internal usage only
388         makeArray: function( arr, results ) {
389                 var ret = results || [];
390
391                 if ( arr != null ) {
392                         if ( isArrayLike( Object( arr ) ) ) {
393                                 jQuery.merge( ret,
394                                         typeof arr === "string" ?
395                                         [ arr ] : arr
396                                 );
397                         } else {
398                                 push.call( ret, arr );
399                         }
400                 }
401
402                 return ret;
403         },
404
405         inArray: function( elem, arr, i ) {
406                 return arr == null ? -1 : indexOf.call( arr, elem, i );
407         },
408
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,
413                         j = 0,
414                         i = first.length;
415
416                 for ( ; j < len; j++ ) {
417                         first[ i++ ] = second[ j ];
418                 }
419
420                 first.length = i;
421
422                 return first;
423         },
424
425         grep: function( elems, callback, invert ) {
426                 var callbackInverse,
427                         matches = [],
428                         i = 0,
429                         length = elems.length,
430                         callbackExpect = !invert;
431
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 ] );
438                         }
439                 }
440
441                 return matches;
442         },
443
444         // arg is for internal usage only
445         map: function( elems, callback, arg ) {
446                 var length, value,
447                         i = 0,
448                         ret = [];
449
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 );
455
456                                 if ( value != null ) {
457                                         ret.push( value );
458                                 }
459                         }
460
461                 // Go through every key on the object,
462                 } else {
463                         for ( i in elems ) {
464                                 value = callback( elems[ i ], i, arg );
465
466                                 if ( value != null ) {
467                                         ret.push( value );
468                                 }
469                         }
470                 }
471
472                 // Flatten any nested arrays
473                 return concat.apply( [], ret );
474         },
475
476         // A global GUID counter for objects
477         guid: 1,
478
479         // Bind a function to a context, optionally partially applying any
480         // arguments.
481         proxy: function( fn, context ) {
482                 var tmp, args, proxy;
483
484                 if ( typeof context === "string" ) {
485                         tmp = fn[ context ];
486                         context = fn;
487                         fn = tmp;
488                 }
489
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 ) ) {
493                         return undefined;
494                 }
495
496                 // Simulated bind
497                 args = slice.call( arguments, 2 );
498                 proxy = function() {
499                         return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
500                 };
501
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++;
504
505                 return proxy;
506         },
507
508         now: Date.now,
509
510         // jQuery.support is not used in Core but other projects attach their
511         // properties to it so it needs to exist.
512         support: support
513 } );
514
515 if ( typeof Symbol === "function" ) {
516         jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
517 }
518
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();
523 } );
524
525 function isArrayLike( obj ) {
526
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 );
533
534         if ( type === "function" || jQuery.isWindow( obj ) ) {
535                 return false;
536         }
537
538         return type === "array" || length === 0 ||
539                 typeof length === "number" && length > 0 && ( length - 1 ) in obj;
540 }
541 var Sizzle =
542 /*!
543  * Sizzle CSS Selector Engine v2.3.0
544  * https://sizzlejs.com/
545  *
546  * Copyright jQuery Foundation and other contributors
547  * Released under the MIT license
548  * http://jquery.org/license
549  *
550  * Date: 2016-01-04
551  */
552 (function( window ) {'use strict';
553
554 var i,
555         support,
556         Expr,
557         getText,
558         isXML,
559         tokenize,
560         compile,
561         select,
562         outermostContext,
563         sortInput,
564         hasDuplicate,
565
566         // Local document vars
567         setDocument,
568         document,
569         docElem,
570         documentIsHTML,
571         rbuggyQSA,
572         rbuggyMatches,
573         matches,
574         contains,
575
576         // Instance-specific data
577         expando = "sizzle" + 1 * new Date(),
578         preferredDoc = window.document,
579         dirruns = 0,
580         done = 0,
581         classCache = createCache(),
582         tokenCache = createCache(),
583         compilerCache = createCache(),
584         sortOrder = function( a, b ) {
585                 if ( a === b ) {
586                         hasDuplicate = true;
587                 }
588                 return 0;
589         },
590
591         // Instance methods
592         hasOwn = ({}).hasOwnProperty,
593         arr = [],
594         pop = arr.pop,
595         push_native = arr.push,
596         push = arr.push,
597         slice = arr.slice,
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 ) {
601                 var i = 0,
602                         len = list.length;
603                 for ( ; i < len; i++ ) {
604                         if ( list[i] === elem ) {
605                                 return i;
606                         }
607                 }
608                 return -1;
609         },
610
611         booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
612
613         // Regular expressions
614
615         // http://www.w3.org/TR/css3-selectors/#whitespace
616         whitespace = "[\\x20\\t\\r\\n\\f]",
617
618         // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
619         identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",
620
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 +
627                 "*\\]",
628
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)
636                 ".*" +
637                 ")\\)|)",
638
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" ),
642
643         rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
644         rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
645
646         rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
647
648         rpseudo = new RegExp( pseudos ),
649         ridentifier = new RegExp( "^" + identifier + "$" ),
650
651         matchExpr = {
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" )
665         },
666
667         rinputs = /^(?:input|select|textarea|button)$/i,
668         rheader = /^h\d$/i,
669
670         rnative = /^[^{]+\{\s*\[native \w/,
671
672         // Easily-parseable/retrievable ID or TAG or CLASS selectors
673         rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
674
675         rsibling = /[+~]/,
676
677         // CSS escapes
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 ?
686                         escaped :
687                         high < 0 ?
688                                 // BMP codepoint
689                                 String.fromCharCode( high + 0x10000 ) :
690                                 // Supplemental Plane codepoint (surrogate pair)
691                                 String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
692         },
693
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 ) {
698                 if ( asCodePoint ) {
699
700                         // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
701                         if ( ch === "\0" ) {
702                                 return "\uFFFD";
703                         }
704
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 ) + " ";
707                 }
708
709                 // Other potentially-special ASCII characters get backslash-escaped
710                 return "\\" + ch;
711         },
712
713         // Used for iframes
714         // See setDocument()
715         // Removing the function wrapper causes a "Permission Denied"
716         // error in IE
717         unloadHandler = function() {
718                 setDocument();
719         },
720
721         disabledAncestor = addCombinator(
722                 function( elem ) {
723                         return elem.disabled === true;
724                 },
725                 { dir: "parentNode", next: "legend" }
726         );
727
728 // Optimize for push.apply( _, NodeList )
729 try {
730         push.apply(
731                 (arr = slice.call( preferredDoc.childNodes )),
732                 preferredDoc.childNodes
733         );
734         // Support: Android<4.0
735         // Detect silently failing push.apply
736         arr[ preferredDoc.childNodes.length ].nodeType;
737 } catch ( e ) {
738         push = { apply: arr.length ?
739
740                 // Leverage slice if possible
741                 function( target, els ) {
742                         push_native.apply( target, slice.call(els) );
743                 } :
744
745                 // Support: IE<9
746                 // Otherwise append directly
747                 function( target, els ) {
748                         var j = target.length,
749                                 i = 0;
750                         // Can't trust NodeList.length
751                         while ( (target[j++] = els[i++]) ) {}
752                         target.length = j - 1;
753                 }
754         };
755 }
756
757 function Sizzle( selector, context, results, seed ) {
758         var m, i, elem, nid, match, groups, newSelector,
759                 newContext = context && context.ownerDocument,
760
761                 // nodeType defaults to 9, since context defaults to document
762                 nodeType = context ? context.nodeType : 9;
763
764         results = results || [];
765
766         // Return early from calls with invalid selector or context
767         if ( typeof selector !== "string" || !selector ||
768                 nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
769
770                 return results;
771         }
772
773         // Try to shortcut find operations (as opposed to filters) in HTML documents
774         if ( !seed ) {
775
776                 if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
777                         setDocument( context );
778                 }
779                 context = context || document;
780
781                 if ( documentIsHTML ) {
782
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 )) ) {
786
787                                 // ID selector
788                                 if ( (m = match[1]) ) {
789
790                                         // Document context
791                                         if ( nodeType === 9 ) {
792                                                 if ( (elem = context.getElementById( m )) ) {
793
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 );
799                                                                 return results;
800                                                         }
801                                                 } else {
802                                                         return results;
803                                                 }
804
805                                         // Element context
806                                         } else {
807
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 ) &&
813                                                         elem.id === m ) {
814
815                                                         results.push( elem );
816                                                         return results;
817                                                 }
818                                         }
819
820                                 // Type selector
821                                 } else if ( match[2] ) {
822                                         push.apply( results, context.getElementsByTagName( selector ) );
823                                         return results;
824
825                                 // Class selector
826                                 } else if ( (m = match[3]) && support.getElementsByClassName &&
827                                         context.getElementsByClassName ) {
828
829                                         push.apply( results, context.getElementsByClassName( m ) );
830                                         return results;
831                                 }
832                         }
833
834                         // Take advantage of querySelectorAll
835                         if ( support.qsa &&
836                                 !compilerCache[ selector + " " ] &&
837                                 (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
838
839                                 if ( nodeType !== 1 ) {
840                                         newContext = context;
841                                         newSelector = selector;
842
843                                 // qSA looks outside Element context, which is not what we want
844                                 // Thanks to Andrew Dupont for this workaround technique
845                                 // Support: IE <=8
846                                 // Exclude object elements
847                                 } else if ( context.nodeName.toLowerCase() !== "object" ) {
848
849                                         // Capture the context ID, setting it first if necessary
850                                         if ( (nid = context.getAttribute( "id" )) ) {
851                                                 nid = nid.replace( rcssescape, fcssescape );
852                                         } else {
853                                                 context.setAttribute( "id", (nid = expando) );
854                                         }
855
856                                         // Prefix every selector in the list
857                                         groups = tokenize( selector );
858                                         i = groups.length;
859                                         while ( i-- ) {
860                                                 groups[i] = "#" + nid + " " + toSelector( groups[i] );
861                                         }
862                                         newSelector = groups.join( "," );
863
864                                         // Expand context for sibling selectors
865                                         newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
866                                                 context;
867                                 }
868
869                                 if ( newSelector ) {
870                                         try {
871                                                 push.apply( results,
872                                                         newContext.querySelectorAll( newSelector )
873                                                 );
874                                                 return results;
875                                         } catch ( qsaError ) {
876                                         } finally {
877                                                 if ( nid === expando ) {
878                                                         context.removeAttribute( "id" );
879                                                 }
880                                         }
881                                 }
882                         }
883                 }
884         }
885
886         // All others
887         return select( selector.replace( rtrim, "$1" ), context, results, seed );
888 }
889
890 /**
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
895  */
896 function createCache() {
897         var keys = [];
898
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() ];
904                 }
905                 return (cache[ key + " " ] = value);
906         }
907         return cache;
908 }
909
910 /**
911  * Mark a function for special use by Sizzle
912  * @param {Function} fn The function to mark
913  */
914 function markFunction( fn ) {
915         fn[ expando ] = true;
916         return fn;
917 }
918
919 /**
920  * Support testing using an element
921  * @param {Function} fn Passed the created element and returns a boolean result
922  */
923 function assert( fn ) {
924         var el = document.createElement("fieldset");
925
926         try {
927                 return !!fn( el );
928         } catch (e) {
929                 return false;
930         } finally {
931                 // Remove from its parent by default
932                 if ( el.parentNode ) {
933                         el.parentNode.removeChild( el );
934                 }
935                 // release memory in IE
936                 el = null;
937         }
938 }
939
940 /**
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
944  */
945 function addHandle( attrs, handler ) {
946         var arr = attrs.split("|"),
947                 i = arr.length;
948
949         while ( i-- ) {
950                 Expr.attrHandle[ arr[i] ] = handler;
951         }
952 }
953
954 /**
955  * Checks document order of two siblings
956  * @param {Element} a
957  * @param {Element} b
958  * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
959  */
960 function siblingCheck( a, b ) {
961         var cur = b && a,
962                 diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
963                         a.sourceIndex - b.sourceIndex;
964
965         // Use IE sourceIndex if available on both nodes
966         if ( diff ) {
967                 return diff;
968         }
969
970         // Check if b follows a
971         if ( cur ) {
972                 while ( (cur = cur.nextSibling) ) {
973                         if ( cur === b ) {
974                                 return -1;
975                         }
976                 }
977         }
978
979         return a ? 1 : -1;
980 }
981
982 /**
983  * Returns a function to use in pseudos for input types
984  * @param {String} type
985  */
986 function createInputPseudo( type ) {
987         return function( elem ) {
988                 var name = elem.nodeName.toLowerCase();
989                 return name === "input" && elem.type === type;
990         };
991 }
992
993 /**
994  * Returns a function to use in pseudos for buttons
995  * @param {String} type
996  */
997 function createButtonPseudo( type ) {
998         return function( elem ) {
999                 var name = elem.nodeName.toLowerCase();
1000                 return (name === "input" || name === "button") && elem.type === type;
1001         };
1002 }
1003
1004 /**
1005  * Returns a function to use in pseudos for :enabled/:disabled
1006  * @param {Boolean} disabled true for :disabled; false for :enabled
1007  */
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 ) {
1013
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 ||
1017
1018                         // Check non-disabled form elements for fieldset[disabled] ancestors
1019                         "form" in elem && elem.disabled === false && (
1020                                 // Support: IE6-11+
1021                                 // Ancestry is covered for us
1022                                 elem.isDisabled === disabled ||
1023
1024                                 // Otherwise, assume any non-<option> under fieldset[disabled] is disabled
1025                                 /* jshint -W018 */
1026                                 elem.isDisabled !== !disabled &&
1027                                         ("label" in elem || !disabledAncestor( elem )) !== disabled
1028                         );
1029         };
1030 }
1031
1032 /**
1033  * Returns a function to use in pseudos for positionals
1034  * @param {Function} fn
1035  */
1036 function createPositionalPseudo( fn ) {
1037         return markFunction(function( argument ) {
1038                 argument = +argument;
1039                 return markFunction(function( seed, matches ) {
1040                         var j,
1041                                 matchIndexes = fn( [], seed.length, argument ),
1042                                 i = matchIndexes.length;
1043
1044                         // Match elements found at the specified indexes
1045                         while ( i-- ) {
1046                                 if ( seed[ (j = matchIndexes[i]) ] ) {
1047                                         seed[j] = !(matches[j] = seed[j]);
1048                                 }
1049                         }
1050                 });
1051         });
1052 }
1053
1054 /**
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
1058  */
1059 function testContext( context ) {
1060         return context && typeof context.getElementsByTagName !== "undefined" && context;
1061 }
1062
1063 // Expose support vars for convenience
1064 support = Sizzle.support = {};
1065
1066 /**
1067  * Detects XML nodes
1068  * @param {Element|Object} elem An element or a document
1069  * @returns {Boolean} True iff elem is a non-HTML XML node
1070  */
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;
1076 };
1077
1078 /**
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
1082  */
1083 setDocument = Sizzle.setDocument = function( node ) {
1084         var hasCompare, subWindow,
1085                 doc = node ? node.ownerDocument || node : preferredDoc;
1086
1087         // Return early if doc is invalid or already selected
1088         if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
1089                 return document;
1090         }
1091
1092         // Update global variables
1093         document = doc;
1094         docElem = document.documentElement;
1095         documentIsHTML = !isXML( document );
1096
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 ) {
1101
1102                 // Support: IE 11, Edge
1103                 if ( subWindow.addEventListener ) {
1104                         subWindow.addEventListener( "unload", unloadHandler, false );
1105
1106                 // Support: IE 9 - 10 only
1107                 } else if ( subWindow.attachEvent ) {
1108                         subWindow.attachEvent( "onunload", unloadHandler );
1109                 }
1110         }
1111
1112         /* Attributes
1113         ---------------------------------------------------------------------- */
1114
1115         // Support: IE<8
1116         // Verify that getAttribute really returns attributes and not properties
1117         // (excepting IE8 booleans)
1118         support.attributes = assert(function( el ) {
1119                 el.className = "i";
1120                 return !el.getAttribute("className");
1121         });
1122
1123         /* getElement(s)By*
1124         ---------------------------------------------------------------------- */
1125
1126         // Check if getElementsByTagName("*") returns only elements
1127         support.getElementsByTagName = assert(function( el ) {
1128                 el.appendChild( document.createComment("") );
1129                 return !el.getElementsByTagName("*").length;
1130         });
1131
1132         // Support: IE<9
1133         support.getElementsByClassName = rnative.test( document.getElementsByClassName );
1134
1135         // Support: IE<10
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;
1142         });
1143
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 ] : [];
1150                         }
1151                 };
1152                 Expr.filter["ID"] = function( id ) {
1153                         var attrId = id.replace( runescape, funescape );
1154                         return function( elem ) {
1155                                 return elem.getAttribute("id") === attrId;
1156                         };
1157                 };
1158         } else {
1159                 // Support: IE6/7
1160                 // getElementById is not reliable as a find shortcut
1161                 delete Expr.find["ID"];
1162
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;
1169                         };
1170                 };
1171         }
1172
1173         // Tag
1174         Expr.find["TAG"] = support.getElementsByTagName ?
1175                 function( tag, context ) {
1176                         if ( typeof context.getElementsByTagName !== "undefined" ) {
1177                                 return context.getElementsByTagName( tag );
1178
1179                         // DocumentFragment nodes don't have gEBTN
1180                         } else if ( support.qsa ) {
1181                                 return context.querySelectorAll( tag );
1182                         }
1183                 } :
1184
1185                 function( tag, context ) {
1186                         var elem,
1187                                 tmp = [],
1188                                 i = 0,
1189                                 // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
1190                                 results = context.getElementsByTagName( tag );
1191
1192                         // Filter out possible comments
1193                         if ( tag === "*" ) {
1194                                 while ( (elem = results[i++]) ) {
1195                                         if ( elem.nodeType === 1 ) {
1196                                                 tmp.push( elem );
1197                                         }
1198                                 }
1199
1200                                 return tmp;
1201                         }
1202                         return results;
1203                 };
1204
1205         // Class
1206         Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
1207                 if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
1208                         return context.getElementsByClassName( className );
1209                 }
1210         };
1211
1212         /* QSA/matchesSelector
1213         ---------------------------------------------------------------------- */
1214
1215         // QSA and matchesSelector support
1216
1217         // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
1218         rbuggyMatches = [];
1219
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
1225         rbuggyQSA = [];
1226
1227         if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
1228                 // Build QSA regex
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>";
1239
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 + "*(?:''|\"\")" );
1246                         }
1247
1248                         // Support: IE8
1249                         // Boolean attributes and "value" are not treated correctly
1250                         if ( !el.querySelectorAll("[selected]").length ) {
1251                                 rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
1252                         }
1253
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("~=");
1257                         }
1258
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");
1264                         }
1265
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(".#.+[+~]");
1271                         }
1272                 });
1273
1274                 assert(function( el ) {
1275                         el.innerHTML = "<a href='' disabled='disabled'></a>" +
1276                                 "<select disabled='disabled'><option/></select>";
1277
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" );
1283
1284                         // Support: IE8
1285                         // Enforce case-sensitivity of name attribute
1286                         if ( el.querySelectorAll("[name=d]").length ) {
1287                                 rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
1288                         }
1289
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" );
1294                         }
1295
1296                         // Support: IE9-11+
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" );
1301                         }
1302
1303                         // Opera 10-11 does not throw on post-comma invalid pseudos
1304                         el.querySelectorAll("*,:x");
1305                         rbuggyQSA.push(",.*:");
1306                 });
1307         }
1308
1309         if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
1310                 docElem.webkitMatchesSelector ||
1311                 docElem.mozMatchesSelector ||
1312                 docElem.oMatchesSelector ||
1313                 docElem.msMatchesSelector) )) ) {
1314
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, "*" );
1319
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 );
1324                 });
1325         }
1326
1327         rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
1328         rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
1329
1330         /* Contains
1331         ---------------------------------------------------------------------- */
1332         hasCompare = rnative.test( docElem.compareDocumentPosition );
1333
1334         // Element contains another
1335         // Purposefully self-exclusive
1336         // As in, an element does not contain itself
1337         contains = hasCompare || rnative.test( docElem.contains ) ?
1338                 function( a, b ) {
1339                         var adown = a.nodeType === 9 ? a.documentElement : a,
1340                                 bup = b && b.parentNode;
1341                         return a === bup || !!( bup && bup.nodeType === 1 && (
1342                                 adown.contains ?
1343                                         adown.contains( bup ) :
1344                                         a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
1345                         ));
1346                 } :
1347                 function( a, b ) {
1348                         if ( b ) {
1349                                 while ( (b = b.parentNode) ) {
1350                                         if ( b === a ) {
1351                                                 return true;
1352                                         }
1353                                 }
1354                         }
1355                         return false;
1356                 };
1357
1358         /* Sorting
1359         ---------------------------------------------------------------------- */
1360
1361         // Document order sorting
1362         sortOrder = hasCompare ?
1363         function( a, b ) {
1364
1365                 // Flag for duplicate removal
1366                 if ( a === b ) {
1367                         hasDuplicate = true;
1368                         return 0;
1369                 }
1370
1371                 // Sort on method existence if only one input has compareDocumentPosition
1372                 var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
1373                 if ( compare ) {
1374                         return compare;
1375                 }
1376
1377                 // Calculate position if both inputs belong to the same document
1378                 compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
1379                         a.compareDocumentPosition( b ) :
1380
1381                         // Otherwise we know they are disconnected
1382                         1;
1383
1384                 // Disconnected nodes
1385                 if ( compare & 1 ||
1386                         (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
1387
1388                         // Choose the first element that is related to our preferred document
1389                         if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
1390                                 return -1;
1391                         }
1392                         if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
1393                                 return 1;
1394                         }
1395
1396                         // Maintain original order
1397                         return sortInput ?
1398                                 ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
1399                                 0;
1400                 }
1401
1402                 return compare & 4 ? -1 : 1;
1403         } :
1404         function( a, b ) {
1405                 // Exit early if the nodes are identical
1406                 if ( a === b ) {
1407                         hasDuplicate = true;
1408                         return 0;
1409                 }
1410
1411                 var cur,
1412                         i = 0,
1413                         aup = a.parentNode,
1414                         bup = b.parentNode,
1415                         ap = [ a ],
1416                         bp = [ b ];
1417
1418                 // Parentless nodes are either documents or disconnected
1419                 if ( !aup || !bup ) {
1420                         return a === document ? -1 :
1421                                 b === document ? 1 :
1422                                 aup ? -1 :
1423                                 bup ? 1 :
1424                                 sortInput ?
1425                                 ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
1426                                 0;
1427
1428                 // If the nodes are siblings, we can do a quick check
1429                 } else if ( aup === bup ) {
1430                         return siblingCheck( a, b );
1431                 }
1432
1433                 // Otherwise we need full lists of their ancestors for comparison
1434                 cur = a;
1435                 while ( (cur = cur.parentNode) ) {
1436                         ap.unshift( cur );
1437                 }
1438                 cur = b;
1439                 while ( (cur = cur.parentNode) ) {
1440                         bp.unshift( cur );
1441                 }
1442
1443                 // Walk down the tree looking for a discrepancy
1444                 while ( ap[i] === bp[i] ) {
1445                         i++;
1446                 }
1447
1448                 return i ?
1449                         // Do a sibling check if the nodes have a common ancestor
1450                         siblingCheck( ap[i], bp[i] ) :
1451
1452                         // Otherwise nodes in our document sort first
1453                         ap[i] === preferredDoc ? -1 :
1454                         bp[i] === preferredDoc ? 1 :
1455                         0;
1456         };
1457
1458         return document;
1459 };
1460
1461 Sizzle.matches = function( expr, elements ) {
1462         return Sizzle( expr, null, null, elements );
1463 };
1464
1465 Sizzle.matchesSelector = function( elem, expr ) {
1466         // Set document vars if needed
1467         if ( ( elem.ownerDocument || elem ) !== document ) {
1468                 setDocument( elem );
1469         }
1470
1471         // Make sure that attribute selectors are quoted
1472         expr = expr.replace( rattributeQuotes, "='$1']" );
1473
1474         if ( support.matchesSelector && documentIsHTML &&
1475                 !compilerCache[ expr + " " ] &&
1476                 ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
1477                 ( !rbuggyQSA     || !rbuggyQSA.test( expr ) ) ) {
1478
1479                 try {
1480                         var ret = matches.call( elem, expr );
1481
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
1485                                         // fragment in IE 9
1486                                         elem.document && elem.document.nodeType !== 11 ) {
1487                                 return ret;
1488                         }
1489                 } catch (e) {}
1490         }
1491
1492         return Sizzle( expr, document, null, [ elem ] ).length > 0;
1493 };
1494
1495 Sizzle.contains = function( context, elem ) {
1496         // Set document vars if needed
1497         if ( ( context.ownerDocument || context ) !== document ) {
1498                 setDocument( context );
1499         }
1500         return contains( context, elem );
1501 };
1502
1503 Sizzle.attr = function( elem, name ) {
1504         // Set document vars if needed
1505         if ( ( elem.ownerDocument || elem ) !== document ) {
1506                 setDocument( elem );
1507         }
1508
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 ) :
1513                         undefined;
1514
1515         return val !== undefined ?
1516                 val :
1517                 support.attributes || !documentIsHTML ?
1518                         elem.getAttribute( name ) :
1519                         (val = elem.getAttributeNode(name)) && val.specified ?
1520                                 val.value :
1521                                 null;
1522 };
1523
1524 Sizzle.escape = function( sel ) {
1525         return (sel + "").replace( rcssescape, fcssescape );
1526 };
1527
1528 Sizzle.error = function( msg ) {
1529         throw new Error( "Syntax error, unrecognized expression: " + msg );
1530 };
1531
1532 /**
1533  * Document sorting and removing duplicates
1534  * @param {ArrayLike} results
1535  */
1536 Sizzle.uniqueSort = function( results ) {
1537         var elem,
1538                 duplicates = [],
1539                 j = 0,
1540                 i = 0;
1541
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 );
1546
1547         if ( hasDuplicate ) {
1548                 while ( (elem = results[i++]) ) {
1549                         if ( elem === results[ i ] ) {
1550                                 j = duplicates.push( i );
1551                         }
1552                 }
1553                 while ( j-- ) {
1554                         results.splice( duplicates[ j ], 1 );
1555                 }
1556         }
1557
1558         // Clear input after sorting to release objects
1559         // See https://github.com/jquery/sizzle/pull/225
1560         sortInput = null;
1561
1562         return results;
1563 };
1564
1565 /**
1566  * Utility function for retrieving the text value of an array of DOM nodes
1567  * @param {Array|Element} elem
1568  */
1569 getText = Sizzle.getText = function( elem ) {
1570         var node,
1571                 ret = "",
1572                 i = 0,
1573                 nodeType = elem.nodeType;
1574
1575         if ( !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 );
1580                 }
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;
1586                 } else {
1587                         // Traverse its children
1588                         for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
1589                                 ret += getText( elem );
1590                         }
1591                 }
1592         } else if ( nodeType === 3 || nodeType === 4 ) {
1593                 return elem.nodeValue;
1594         }
1595         // Do not include comment or processing instruction nodes
1596
1597         return ret;
1598 };
1599
1600 Expr = Sizzle.selectors = {
1601
1602         // Can be adjusted by the user
1603         cacheLength: 50,
1604
1605         createPseudo: markFunction,
1606
1607         match: matchExpr,
1608
1609         attrHandle: {},
1610
1611         find: {},
1612
1613         relative: {
1614                 ">": { dir: "parentNode", first: true },
1615                 " ": { dir: "parentNode" },
1616                 "+": { dir: "previousSibling", first: true },
1617                 "~": { dir: "previousSibling" }
1618         },
1619
1620         preFilter: {
1621                 "ATTR": function( match ) {
1622                         match[1] = match[1].replace( runescape, funescape );
1623
1624                         // Move the given value to match[3] whether quoted or unquoted
1625                         match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
1626
1627                         if ( match[2] === "~=" ) {
1628                                 match[3] = " " + match[3] + " ";
1629                         }
1630
1631                         return match.slice( 0, 4 );
1632                 },
1633
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
1641                                 6 x of xn-component
1642                                 7 sign of y-component
1643                                 8 y of y-component
1644                         */
1645                         match[1] = match[1].toLowerCase();
1646
1647                         if ( match[1].slice( 0, 3 ) === "nth" ) {
1648                                 // nth-* requires argument
1649                                 if ( !match[3] ) {
1650                                         Sizzle.error( match[0] );
1651                                 }
1652
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" );
1657
1658                         // other types prohibit arguments
1659                         } else if ( match[3] ) {
1660                                 Sizzle.error( match[0] );
1661                         }
1662
1663                         return match;
1664                 },
1665
1666                 "PSEUDO": function( match ) {
1667                         var excess,
1668                                 unquoted = !match[6] && match[2];
1669
1670                         if ( matchExpr["CHILD"].test( match[0] ) ) {
1671                                 return null;
1672                         }
1673
1674                         // Accept quoted arguments as-is
1675                         if ( match[3] ) {
1676                                 match[2] = match[4] || match[5] || "";
1677
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) ) {
1684
1685                                 // excess is a negative index
1686                                 match[0] = match[0].slice( 0, excess );
1687                                 match[2] = unquoted.slice( 0, excess );
1688                         }
1689
1690                         // Return only captures needed by the pseudo filter method (type and argument)
1691                         return match.slice( 0, 3 );
1692                 }
1693         },
1694
1695         filter: {
1696
1697                 "TAG": function( nodeNameSelector ) {
1698                         var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
1699                         return nodeNameSelector === "*" ?
1700                                 function() { return true; } :
1701                                 function( elem ) {
1702                                         return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
1703                                 };
1704                 },
1705
1706                 "CLASS": function( className ) {
1707                         var pattern = classCache[ className + " " ];
1708
1709                         return pattern ||
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") || "" );
1713                                 });
1714                 },
1715
1716                 "ATTR": function( name, operator, check ) {
1717                         return function( elem ) {
1718                                 var result = Sizzle.attr( elem, name );
1719
1720                                 if ( result == null ) {
1721                                         return operator === "!=";
1722                                 }
1723                                 if ( !operator ) {
1724                                         return true;
1725                                 }
1726
1727                                 result += "";
1728
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 + "-" :
1736                                         false;
1737                         };
1738                 },
1739
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";
1744
1745                         return first === 1 && last === 0 ?
1746
1747                                 // Shortcut for :nth-*(n)
1748                                 function( elem ) {
1749                                         return !!elem.parentNode;
1750                                 } :
1751
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,
1758                                                 diff = false;
1759
1760                                         if ( parent ) {
1761
1762                                                 // :(first|last|only)-(child|of-type)
1763                                                 if ( simple ) {
1764                                                         while ( dir ) {
1765                                                                 node = elem;
1766                                                                 while ( (node = node[ dir ]) ) {
1767                                                                         if ( ofType ?
1768                                                                                 node.nodeName.toLowerCase() === name :
1769                                                                                 node.nodeType === 1 ) {
1770
1771                                                                                 return false;
1772                                                                         }
1773                                                                 }
1774                                                                 // Reverse direction for :only-* (if we haven't yet done so)
1775                                                                 start = dir = type === "only" && !start && "nextSibling";
1776                                                         }
1777                                                         return true;
1778                                                 }
1779
1780                                                 start = [ forward ? parent.firstChild : parent.lastChild ];
1781
1782                                                 // non-xml :nth-child(...) stores cache data on `parent`
1783                                                 if ( forward && useCache ) {
1784
1785                                                         // Seek `elem` from a previously-cached index
1786
1787                                                         // ...in a gzip-friendly way
1788                                                         node = parent;
1789                                                         outerCache = node[ expando ] || (node[ expando ] = {});
1790
1791                                                         // Support: IE <9 only
1792                                                         // Defend against cloned attroperties (jQuery gh-1709)
1793                                                         uniqueCache = outerCache[ node.uniqueID ] ||
1794                                                                 (outerCache[ node.uniqueID ] = {});
1795
1796                                                         cache = uniqueCache[ type ] || [];
1797                                                         nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
1798                                                         diff = nodeIndex && cache[ 2 ];
1799                                                         node = nodeIndex && parent.childNodes[ nodeIndex ];
1800
1801                                                         while ( (node = ++nodeIndex && node && node[ dir ] ||
1802
1803                                                                 // Fallback to seeking `elem` from the start
1804                                                                 (diff = nodeIndex = 0) || start.pop()) ) {
1805
1806                                                                 // When found, cache indexes on `parent` and break
1807                                                                 if ( node.nodeType === 1 && ++diff && node === elem ) {
1808                                                                         uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
1809                                                                         break;
1810                                                                 }
1811                                                         }
1812
1813                                                 } else {
1814                                                         // Use previously-cached element index if available
1815                                                         if ( useCache ) {
1816                                                                 // ...in a gzip-friendly way
1817                                                                 node = elem;
1818                                                                 outerCache = node[ expando ] || (node[ expando ] = {});
1819
1820                                                                 // Support: IE <9 only
1821                                                                 // Defend against cloned attroperties (jQuery gh-1709)
1822                                                                 uniqueCache = outerCache[ node.uniqueID ] ||
1823                                                                         (outerCache[ node.uniqueID ] = {});
1824
1825                                                                 cache = uniqueCache[ type ] || [];
1826                                                                 nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
1827                                                                 diff = nodeIndex;
1828                                                         }
1829
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()) ) {
1836
1837                                                                         if ( ( ofType ?
1838                                                                                 node.nodeName.toLowerCase() === name :
1839                                                                                 node.nodeType === 1 ) &&
1840                                                                                 ++diff ) {
1841
1842                                                                                 // Cache the index of each encountered element
1843                                                                                 if ( useCache ) {
1844                                                                                         outerCache = node[ expando ] || (node[ expando ] = {});
1845
1846                                                                                         // Support: IE <9 only
1847                                                                                         // Defend against cloned attroperties (jQuery gh-1709)
1848                                                                                         uniqueCache = outerCache[ node.uniqueID ] ||
1849                                                                                                 (outerCache[ node.uniqueID ] = {});
1850
1851                                                                                         uniqueCache[ type ] = [ dirruns, diff ];
1852                                                                                 }
1853
1854                                                                                 if ( node === elem ) {
1855                                                                                         break;
1856                                                                                 }
1857                                                                         }
1858                                                                 }
1859                                                         }
1860                                                 }
1861
1862                                                 // Incorporate the offset, then check against cycle size
1863                                                 diff -= last;
1864                                                 return diff === first || ( diff % first === 0 && diff / first >= 0 );
1865                                         }
1866                                 };
1867                 },
1868
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
1874                         var args,
1875                                 fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
1876                                         Sizzle.error( "unsupported pseudo: " + pseudo );
1877
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 );
1883                         }
1884
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 ) {
1890                                                 var idx,
1891                                                         matched = fn( seed, argument ),
1892                                                         i = matched.length;
1893                                                 while ( i-- ) {
1894                                                         idx = indexOf( seed, matched[i] );
1895                                                         seed[ idx ] = !( matches[ idx ] = matched[i] );
1896                                                 }
1897                                         }) :
1898                                         function( elem ) {
1899                                                 return fn( elem, 0, args );
1900                                         };
1901                         }
1902
1903                         return fn;
1904                 }
1905         },
1906
1907         pseudos: {
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
1913                         var input = [],
1914                                 results = [],
1915                                 matcher = compile( selector.replace( rtrim, "$1" ) );
1916
1917                         return matcher[ expando ] ?
1918                                 markFunction(function( seed, matches, context, xml ) {
1919                                         var elem,
1920                                                 unmatched = matcher( seed, null, xml, [] ),
1921                                                 i = seed.length;
1922
1923                                         // Match elements unmatched by `matcher`
1924                                         while ( i-- ) {
1925                                                 if ( (elem = unmatched[i]) ) {
1926                                                         seed[i] = !(matches[i] = elem);
1927                                                 }
1928                                         }
1929                                 }) :
1930                                 function( elem, context, xml ) {
1931                                         input[0] = elem;
1932                                         matcher( input, null, xml, results );
1933                                         // Don't keep the element (issue #299)
1934                                         input[0] = null;
1935                                         return !results.pop();
1936                                 };
1937                 }),
1938
1939                 "has": markFunction(function( selector ) {
1940                         return function( elem ) {
1941                                 return Sizzle( selector, elem ).length > 0;
1942                         };
1943                 }),
1944
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;
1949                         };
1950                 }),
1951
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 );
1963                         }
1964                         lang = lang.replace( runescape, funescape ).toLowerCase();
1965                         return function( elem ) {
1966                                 var elemLang;
1967                                 do {
1968                                         if ( (elemLang = documentIsHTML ?
1969                                                 elem.lang :
1970                                                 elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
1971
1972                                                 elemLang = elemLang.toLowerCase();
1973                                                 return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
1974                                         }
1975                                 } while ( (elem = elem.parentNode) && elem.nodeType === 1 );
1976                                 return false;
1977                         };
1978                 }),
1979
1980                 // Miscellaneous
1981                 "target": function( elem ) {
1982                         var hash = window.location && window.location.hash;
1983                         return hash && hash.slice( 1 ) === elem.id;
1984                 },
1985
1986                 "root": function( elem ) {
1987                         return elem === docElem;
1988                 },
1989
1990                 "focus": function( elem ) {
1991                         return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
1992                 },
1993
1994                 // Boolean properties
1995                 "enabled": createDisabledPseudo( false ),
1996                 "disabled": createDisabledPseudo( true ),
1997
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);
2003                 },
2004
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;
2010                         }
2011
2012                         return elem.selected === true;
2013                 },
2014
2015                 // Contents
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 ) {
2023                                         return false;
2024                                 }
2025                         }
2026                         return true;
2027                 },
2028
2029                 "parent": function( elem ) {
2030                         return !Expr.pseudos["empty"]( elem );
2031                 },
2032
2033                 // Element/input types
2034                 "header": function( elem ) {
2035                         return rheader.test( elem.nodeName );
2036                 },
2037
2038                 "input": function( elem ) {
2039                         return rinputs.test( elem.nodeName );
2040                 },
2041
2042                 "button": function( elem ) {
2043                         var name = elem.nodeName.toLowerCase();
2044                         return name === "input" && elem.type === "button" || name === "button";
2045                 },
2046
2047                 "text": function( elem ) {
2048                         var attr;
2049                         return elem.nodeName.toLowerCase() === "input" &&
2050                                 elem.type === "text" &&
2051
2052                                 // Support: IE<8
2053                                 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
2054                                 ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
2055                 },
2056
2057                 // Position-in-collection
2058                 "first": createPositionalPseudo(function() {
2059                         return [ 0 ];
2060                 }),
2061
2062                 "last": createPositionalPseudo(function( matchIndexes, length ) {
2063                         return [ length - 1 ];
2064                 }),
2065
2066                 "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
2067                         return [ argument < 0 ? argument + length : argument ];
2068                 }),
2069
2070                 "even": createPositionalPseudo(function( matchIndexes, length ) {
2071                         var i = 0;
2072                         for ( ; i < length; i += 2 ) {
2073                                 matchIndexes.push( i );
2074                         }
2075                         return matchIndexes;
2076                 }),
2077
2078                 "odd": createPositionalPseudo(function( matchIndexes, length ) {
2079                         var i = 1;
2080                         for ( ; i < length; i += 2 ) {
2081                                 matchIndexes.push( i );
2082                         }
2083                         return matchIndexes;
2084                 }),
2085
2086                 "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
2087                         var i = argument < 0 ? argument + length : argument;
2088                         for ( ; --i >= 0; ) {
2089                                 matchIndexes.push( i );
2090                         }
2091                         return matchIndexes;
2092                 }),
2093
2094                 "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
2095                         var i = argument < 0 ? argument + length : argument;
2096                         for ( ; ++i < length; ) {
2097                                 matchIndexes.push( i );
2098                         }
2099                         return matchIndexes;
2100                 })
2101         }
2102 };
2103
2104 Expr.pseudos["nth"] = Expr.pseudos["eq"];
2105
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 );
2109 }
2110 for ( i in { submit: true, reset: true } ) {
2111         Expr.pseudos[ i ] = createButtonPseudo( i );
2112 }
2113
2114 // Easy API for creating new setFilters
2115 function setFilters() {}
2116 setFilters.prototype = Expr.filters = Expr.pseudos;
2117 Expr.setFilters = new setFilters();
2118
2119 tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
2120         var matched, match, tokens, type,
2121                 soFar, groups, preFilters,
2122                 cached = tokenCache[ selector + " " ];
2123
2124         if ( cached ) {
2125                 return parseOnly ? 0 : cached.slice( 0 );
2126         }
2127
2128         soFar = selector;
2129         groups = [];
2130         preFilters = Expr.preFilter;
2131
2132         while ( soFar ) {
2133
2134                 // Comma and first run
2135                 if ( !matched || (match = rcomma.exec( soFar )) ) {
2136                         if ( match ) {
2137                                 // Don't consume trailing commas as valid
2138                                 soFar = soFar.slice( match[0].length ) || soFar;
2139                         }
2140                         groups.push( (tokens = []) );
2141                 }
2142
2143                 matched = false;
2144
2145                 // Combinators
2146                 if ( (match = rcombinators.exec( soFar )) ) {
2147                         matched = match.shift();
2148                         tokens.push({
2149                                 value: matched,
2150                                 // Cast descendant combinators to space
2151                                 type: match[0].replace( rtrim, " " )
2152                         });
2153                         soFar = soFar.slice( matched.length );
2154                 }
2155
2156                 // Filters
2157                 for ( type in Expr.filter ) {
2158                         if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
2159                                 (match = preFilters[ type ]( match ))) ) {
2160                                 matched = match.shift();
2161                                 tokens.push({
2162                                         value: matched,
2163                                         type: type,
2164                                         matches: match
2165                                 });
2166                                 soFar = soFar.slice( matched.length );
2167                         }
2168                 }
2169
2170                 if ( !matched ) {
2171                         break;
2172                 }
2173         }
2174
2175         // Return the length of the invalid excess
2176         // if we're just parsing
2177         // Otherwise, throw an error or return tokens
2178         return parseOnly ?
2179                 soFar.length :
2180                 soFar ?
2181                         Sizzle.error( selector ) :
2182                         // Cache the tokens
2183                         tokenCache( selector, groups ).slice( 0 );
2184 };
2185
2186 function toSelector( tokens ) {
2187         var i = 0,
2188                 len = tokens.length,
2189                 selector = "";
2190         for ( ; i < len; i++ ) {
2191                 selector += tokens[i].value;
2192         }
2193         return selector;
2194 }
2195
2196 function addCombinator( matcher, combinator, base ) {
2197         var dir = combinator.dir,
2198                 skip = combinator.next,
2199                 key = skip || dir,
2200                 checkNonElements = base && key === "parentNode",
2201                 doneName = done++;
2202
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 );
2209                                 }
2210                         }
2211                 } :
2212
2213                 // Check against all ancestor/preceding elements
2214                 function( elem, context, xml ) {
2215                         var oldCache, uniqueCache, outerCache,
2216                                 newCache = [ dirruns, doneName ];
2217
2218                         // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
2219                         if ( xml ) {
2220                                 while ( (elem = elem[ dir ]) ) {
2221                                         if ( elem.nodeType === 1 || checkNonElements ) {
2222                                                 if ( matcher( elem, context, xml ) ) {
2223                                                         return true;
2224                                                 }
2225                                         }
2226                                 }
2227                         } else {
2228                                 while ( (elem = elem[ dir ]) ) {
2229                                         if ( elem.nodeType === 1 || checkNonElements ) {
2230                                                 outerCache = elem[ expando ] || (elem[ expando ] = {});
2231
2232                                                 // Support: IE <9 only
2233                                                 // Defend against cloned attroperties (jQuery gh-1709)
2234                                                 uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
2235
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 ) {
2240
2241                                                         // Assign to newCache so results back-propagate to previous elements
2242                                                         return (newCache[ 2 ] = oldCache[ 2 ]);
2243                                                 } else {
2244                                                         // Reuse newcache so results back-propagate to previous elements
2245                                                         uniqueCache[ key ] = newCache;
2246
2247                                                         // A match means we're done; a fail means we have to keep checking
2248                                                         if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
2249                                                                 return true;
2250                                                         }
2251                                                 }
2252                                         }
2253                                 }
2254                         }
2255                 };
2256 }
2257
2258 function elementMatcher( matchers ) {
2259         return matchers.length > 1 ?
2260                 function( elem, context, xml ) {
2261                         var i = matchers.length;
2262                         while ( i-- ) {
2263                                 if ( !matchers[i]( elem, context, xml ) ) {
2264                                         return false;
2265                                 }
2266                         }
2267                         return true;
2268                 } :
2269                 matchers[0];
2270 }
2271
2272 function multipleContexts( selector, contexts, results ) {
2273         var i = 0,
2274                 len = contexts.length;
2275         for ( ; i < len; i++ ) {
2276                 Sizzle( selector, contexts[i], results );
2277         }
2278         return results;
2279 }
2280
2281 function condense( unmatched, map, filter, context, xml ) {
2282         var elem,
2283                 newUnmatched = [],
2284                 i = 0,
2285                 len = unmatched.length,
2286                 mapped = map != null;
2287
2288         for ( ; i < len; i++ ) {
2289                 if ( (elem = unmatched[i]) ) {
2290                         if ( !filter || filter( elem, context, xml ) ) {
2291                                 newUnmatched.push( elem );
2292                                 if ( mapped ) {
2293                                         map.push( i );
2294                                 }
2295                         }
2296                 }
2297         }
2298
2299         return newUnmatched;
2300 }
2301
2302 function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
2303         if ( postFilter && !postFilter[ expando ] ) {
2304                 postFilter = setMatcher( postFilter );
2305         }
2306         if ( postFinder && !postFinder[ expando ] ) {
2307                 postFinder = setMatcher( postFinder, postSelector );
2308         }
2309         return markFunction(function( seed, results, context, xml ) {
2310                 var temp, i, elem,
2311                         preMap = [],
2312                         postMap = [],
2313                         preexisting = results.length,
2314
2315                         // Get initial elements from seed or context
2316                         elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
2317
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 ) :
2321                                 elems,
2322
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 ) ?
2326
2327                                         // ...intermediate processing is necessary
2328                                         [] :
2329
2330                                         // ...otherwise use results directly
2331                                         results :
2332                                 matcherIn;
2333
2334                 // Find primary matches
2335                 if ( matcher ) {
2336                         matcher( matcherIn, matcherOut, context, xml );
2337                 }
2338
2339                 // Apply postFilter
2340                 if ( postFilter ) {
2341                         temp = condense( matcherOut, postMap );
2342                         postFilter( temp, [], context, xml );
2343
2344                         // Un-match failing elements by moving them back to matcherIn
2345                         i = temp.length;
2346                         while ( i-- ) {
2347                                 if ( (elem = temp[i]) ) {
2348                                         matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
2349                                 }
2350                         }
2351                 }
2352
2353                 if ( seed ) {
2354                         if ( postFinder || preFilter ) {
2355                                 if ( postFinder ) {
2356                                         // Get the final matcherOut by condensing this intermediate into postFinder contexts
2357                                         temp = [];
2358                                         i = matcherOut.length;
2359                                         while ( i-- ) {
2360                                                 if ( (elem = matcherOut[i]) ) {
2361                                                         // Restore matcherIn since elem is not yet a final match
2362                                                         temp.push( (matcherIn[i] = elem) );
2363                                                 }
2364                                         }
2365                                         postFinder( null, (matcherOut = []), temp, xml );
2366                                 }
2367
2368                                 // Move matched elements from seed to results to keep them synchronized
2369                                 i = matcherOut.length;
2370                                 while ( i-- ) {
2371                                         if ( (elem = matcherOut[i]) &&
2372                                                 (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
2373
2374                                                 seed[temp] = !(results[temp] = elem);
2375                                         }
2376                                 }
2377                         }
2378
2379                 // Add elements to results, through postFinder if defined
2380                 } else {
2381                         matcherOut = condense(
2382                                 matcherOut === results ?
2383                                         matcherOut.splice( preexisting, matcherOut.length ) :
2384                                         matcherOut
2385                         );
2386                         if ( postFinder ) {
2387                                 postFinder( null, results, matcherOut, xml );
2388                         } else {
2389                                 push.apply( results, matcherOut );
2390                         }
2391                 }
2392         });
2393 }
2394
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,
2401
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;
2416                         return ret;
2417                 } ];
2418
2419         for ( ; i < len; i++ ) {
2420                 if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
2421                         matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
2422                 } else {
2423                         matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
2424
2425                         // Return special upon seeing a positional matcher
2426                         if ( matcher[ expando ] ) {
2427                                 // Find the next relative operator (if any) for proper handling
2428                                 j = ++i;
2429                                 for ( ; j < len; j++ ) {
2430                                         if ( Expr.relative[ tokens[j].type ] ) {
2431                                                 break;
2432                                         }
2433                                 }
2434                                 return setMatcher(
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" ),
2440                                         matcher,
2441                                         i < j && matcherFromTokens( tokens.slice( i, j ) ),
2442                                         j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
2443                                         j < len && toSelector( tokens )
2444                                 );
2445                         }
2446                         matchers.push( matcher );
2447                 }
2448         }
2449
2450         return elementMatcher( matchers );
2451 }
2452
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,
2458                                 matchedCount = 0,
2459                                 i = "0",
2460                                 unmatched = seed && [],
2461                                 setMatched = [],
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),
2467                                 len = elems.length;
2468
2469                         if ( outermost ) {
2470                                 outermostContext = context === document || context || outermost;
2471                         }
2472
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 ) {
2478                                         j = 0;
2479                                         if ( !context && elem.ownerDocument !== document ) {
2480                                                 setDocument( elem );
2481                                                 xml = !documentIsHTML;
2482                                         }
2483                                         while ( (matcher = elementMatchers[j++]) ) {
2484                                                 if ( matcher( elem, context || document, xml) ) {
2485                                                         results.push( elem );
2486                                                         break;
2487                                                 }
2488                                         }
2489                                         if ( outermost ) {
2490                                                 dirruns = dirrunsUnique;
2491                                         }
2492                                 }
2493
2494                                 // Track unmatched elements for set filters
2495                                 if ( bySet ) {
2496                                         // They will have gone through all possible matchers
2497                                         if ( (elem = !matcher && elem) ) {
2498                                                 matchedCount--;
2499                                         }
2500
2501                                         // Lengthen the array for every element, matched or not
2502                                         if ( seed ) {
2503                                                 unmatched.push( elem );
2504                                         }
2505                                 }
2506                         }
2507
2508                         // `i` is now the count of elements visited above, and adding it to `matchedCount`
2509                         // makes the latter nonnegative.
2510                         matchedCount += i;
2511
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 ) {
2520                                 j = 0;
2521                                 while ( (matcher = setMatchers[j++]) ) {
2522                                         matcher( unmatched, setMatched, context, xml );
2523                                 }
2524
2525                                 if ( seed ) {
2526                                         // Reintegrate element matches to eliminate the need for sorting
2527                                         if ( matchedCount > 0 ) {
2528                                                 while ( i-- ) {
2529                                                         if ( !(unmatched[i] || setMatched[i]) ) {
2530                                                                 setMatched[i] = pop.call( results );
2531                                                         }
2532                                                 }
2533                                         }
2534
2535                                         // Discard index placeholder values to get only actual matches
2536                                         setMatched = condense( setMatched );
2537                                 }
2538
2539                                 // Add matches to results
2540                                 push.apply( results, setMatched );
2541
2542                                 // Seedless set matches succeeding multiple successful matchers stipulate sorting
2543                                 if ( outermost && !seed && setMatched.length > 0 &&
2544                                         ( matchedCount + setMatchers.length ) > 1 ) {
2545
2546                                         Sizzle.uniqueSort( results );
2547                                 }
2548                         }
2549
2550                         // Override manipulation of globals by nested matchers
2551                         if ( outermost ) {
2552                                 dirruns = dirrunsUnique;
2553                                 outermostContext = contextBackup;
2554                         }
2555
2556                         return unmatched;
2557                 };
2558
2559         return bySet ?
2560                 markFunction( superMatcher ) :
2561                 superMatcher;
2562 }
2563
2564 compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
2565         var i,
2566                 setMatchers = [],
2567                 elementMatchers = [],
2568                 cached = compilerCache[ selector + " " ];
2569
2570         if ( !cached ) {
2571                 // Generate a function of recursive functions that can be used to check each element
2572                 if ( !match ) {
2573                         match = tokenize( selector );
2574                 }
2575                 i = match.length;
2576                 while ( i-- ) {
2577                         cached = matcherFromTokens( match[i] );
2578                         if ( cached[ expando ] ) {
2579                                 setMatchers.push( cached );
2580                         } else {
2581                                 elementMatchers.push( cached );
2582                         }
2583                 }
2584
2585                 // Cache the compiled function
2586                 cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
2587
2588                 // Save selector and tokenization
2589                 cached.selector = selector;
2590         }
2591         return cached;
2592 };
2593
2594 /**
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
2602  */
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) );
2607
2608         results = results || [];
2609
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 ) {
2613
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 ] ) {
2619
2620                         context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
2621                         if ( !context ) {
2622                                 return results;
2623
2624                         // Precompiled matchers will still verify ancestry, so step up a level
2625                         } else if ( compiled ) {
2626                                 context = context.parentNode;
2627                         }
2628
2629                         selector = selector.slice( tokens.shift().value.length );
2630                 }
2631
2632                 // Fetch a seed set for right-to-left matching
2633                 i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
2634                 while ( i-- ) {
2635                         token = tokens[i];
2636
2637                         // Abort if we hit a combinator
2638                         if ( Expr.relative[ (type = token.type) ] ) {
2639                                 break;
2640                         }
2641                         if ( (find = Expr.find[ type ]) ) {
2642                                 // Search, expanding context for leading sibling combinators
2643                                 if ( (seed = find(
2644                                         token.matches[0].replace( runescape, funescape ),
2645                                         rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
2646                                 )) ) {
2647
2648                                         // If seed is empty or no tokens remain, we can return early
2649                                         tokens.splice( i, 1 );
2650                                         selector = seed.length && toSelector( tokens );
2651                                         if ( !selector ) {
2652                                                 push.apply( results, seed );
2653                                                 return results;
2654                                         }
2655
2656                                         break;
2657                                 }
2658                         }
2659                 }
2660         }
2661
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 ) )(
2665                 seed,
2666                 context,
2667                 !documentIsHTML,
2668                 results,
2669                 !context || rsibling.test( selector ) && testContext( context.parentNode ) || context
2670         );
2671         return results;
2672 };
2673
2674 // One-time assignments
2675
2676 // Sort stability
2677 support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
2678
2679 // Support: Chrome 14-35+
2680 // Always assume duplicates if they aren't passed to the comparison function
2681 support.detectDuplicates = !!hasDuplicate;
2682
2683 // Initialize against the default document
2684 setDocument();
2685
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;
2691 });
2692
2693 // Support: IE<8
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") === "#" ;
2699 }) ) {
2700         addHandle( "type|href|height|width", function( elem, name, isXML ) {
2701                 if ( !isXML ) {
2702                         return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
2703                 }
2704         });
2705 }
2706
2707 // Support: IE<9
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" ) === "";
2713 }) ) {
2714         addHandle( "value", function( elem, name, isXML ) {
2715                 if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
2716                         return elem.defaultValue;
2717                 }
2718         });
2719 }
2720
2721 // Support: IE<9
2722 // Use getAttributeNode to fetch booleans when getAttribute lies
2723 if ( !assert(function( el ) {
2724         return el.getAttribute("disabled") == null;
2725 }) ) {
2726         addHandle( booleans, function( elem, name, isXML ) {
2727                 var val;
2728                 if ( !isXML ) {
2729                         return elem[ name ] === true ? name.toLowerCase() :
2730                                         (val = elem.getAttributeNode( name )) && val.specified ?
2731                                         val.value :
2732                                 null;
2733                 }
2734         });
2735 }
2736
2737 return Sizzle;
2738
2739 })( window );
2740
2741
2742
2743 jQuery.find = Sizzle;
2744 jQuery.expr = Sizzle.selectors;
2745
2746 // Deprecated
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;
2753
2754
2755
2756
2757 var dir = function( elem, dir, until ) {
2758         var matched = [],
2759                 truncate = until !== undefined;
2760
2761         while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
2762                 if ( elem.nodeType === 1 ) {
2763                         if ( truncate && jQuery( elem ).is( until ) ) {
2764                                 break;
2765                         }
2766                         matched.push( elem );
2767                 }
2768         }
2769         return matched;
2770 };
2771
2772
2773 var siblings = function( n, elem ) {
2774         var matched = [];
2775
2776         for ( ; n; n = n.nextSibling ) {
2777                 if ( n.nodeType === 1 && n !== elem ) {
2778                         matched.push( n );
2779                 }
2780         }
2781
2782         return matched;
2783 };
2784
2785
2786 var rneedsContext = jQuery.expr.match.needsContext;
2787
2788 var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );
2789
2790
2791
2792 var risSimple = /^.[^:#\[\.,]*$/;
2793
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;
2799                 } );
2800
2801         }
2802
2803         if ( qualifier.nodeType ) {
2804                 return jQuery.grep( elements, function( elem ) {
2805                         return ( elem === qualifier ) !== not;
2806                 } );
2807
2808         }
2809
2810         if ( typeof qualifier === "string" ) {
2811                 if ( risSimple.test( qualifier ) ) {
2812                         return jQuery.filter( qualifier, elements, not );
2813                 }
2814
2815                 qualifier = jQuery.filter( qualifier, elements );
2816         }
2817
2818         return jQuery.grep( elements, function( elem ) {
2819                 return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1;
2820         } );
2821 }
2822
2823 jQuery.filter = function( expr, elems, not ) {
2824         var elem = elems[ 0 ];
2825
2826         if ( not ) {
2827                 expr = ":not(" + expr + ")";
2828         }
2829
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;
2834                 } ) );
2835 };
2836
2837 jQuery.fn.extend( {
2838         find: function( selector ) {
2839                 var i, ret,
2840                         len = this.length,
2841                         self = this;
2842
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 ) ) {
2847                                                 return true;
2848                                         }
2849                                 }
2850                         } ) );
2851                 }
2852
2853                 ret = this.pushStack( [] );
2854
2855                 for ( i = 0; i < len; i++ ) {
2856                         jQuery.find( selector, self[ i ], ret );
2857                 }
2858
2859                 return len > 1 ? jQuery.uniqueSort( ret ) : ret;
2860         },
2861         filter: function( selector ) {
2862                 return this.pushStack( winnow( this, selector || [], false ) );
2863         },
2864         not: function( selector ) {
2865                 return this.pushStack( winnow( this, selector || [], true ) );
2866         },
2867         is: function( selector ) {
2868                 return !!winnow(
2869                         this,
2870
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 ) :
2875                                 selector || [],
2876                         false
2877                 ).length;
2878         }
2879 } );
2880
2881
2882 // Initialize a jQuery object
2883
2884
2885 // A central reference to the root jQuery(document)
2886 var rootjQuery,
2887
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-]+))$/,
2893
2894         init = jQuery.fn.init = function( selector, context, root ) {
2895                 var match, elem;
2896
2897                 // HANDLE: $(""), $(null), $(undefined), $(false)
2898                 if ( !selector ) {
2899                         return this;
2900                 }
2901
2902                 // Method init() accepts an alternate rootjQuery
2903                 // so migrate can support jQuery.sub (gh-2101)
2904                 root = root || rootjQuery;
2905
2906                 // Handle HTML strings
2907                 if ( typeof selector === "string" ) {
2908                         if ( selector[ 0 ] === "<" &&
2909                                 selector[ selector.length - 1 ] === ">" &&
2910                                 selector.length >= 3 ) {
2911
2912                                 // Assume that strings that start and end with <> are HTML and skip the regex check
2913                                 match = [ null, selector, null ];
2914
2915                         } else {
2916                                 match = rquickExpr.exec( selector );
2917                         }
2918
2919                         // Match html or make sure no context is specified for #id
2920                         if ( match && ( match[ 1 ] || !context ) ) {
2921
2922                                 // HANDLE: $(html) -> $(array)
2923                                 if ( match[ 1 ] ) {
2924                                         context = context instanceof jQuery ? context[ 0 ] : context;
2925
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(
2929                                                 match[ 1 ],
2930                                                 context && context.nodeType ? context.ownerDocument || context : document,
2931                                                 true
2932                                         ) );
2933
2934                                         // HANDLE: $(html, props)
2935                                         if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
2936                                                 for ( match in context ) {
2937
2938                                                         // Properties of context are called as methods if possible
2939                                                         if ( jQuery.isFunction( this[ match ] ) ) {
2940                                                                 this[ match ]( context[ match ] );
2941
2942                                                         // ...and otherwise set as attributes
2943                                                         } else {
2944                                                                 this.attr( match, context[ match ] );
2945                                                         }
2946                                                 }
2947                                         }
2948
2949                                         return this;
2950
2951                                 // HANDLE: $(#id)
2952                                 } else {
2953                                         elem = document.getElementById( match[ 2 ] );
2954
2955                                         if ( elem ) {
2956
2957                                                 // Inject the element directly into the jQuery object
2958                                                 this[ 0 ] = elem;
2959                                                 this.length = 1;
2960                                         }
2961                                         return this;
2962                                 }
2963
2964                         // HANDLE: $(expr, $(...))
2965                         } else if ( !context || context.jquery ) {
2966                                 return ( context || root ).find( selector );
2967
2968                         // HANDLE: $(expr, context)
2969                         // (which is just equivalent to: $(context).find(expr)
2970                         } else {
2971                                 return this.constructor( context ).find( selector );
2972                         }
2973
2974                 // HANDLE: $(DOMElement)
2975                 } else if ( selector.nodeType ) {
2976                         this[ 0 ] = selector;
2977                         this.length = 1;
2978                         return this;
2979
2980                 // HANDLE: $(function)
2981                 // Shortcut for document ready
2982                 } else if ( jQuery.isFunction( selector ) ) {
2983                         return root.ready !== undefined ?
2984                                 root.ready( selector ) :
2985
2986                                 // Execute immediately if ready is not present
2987                                 selector( jQuery );
2988                 }
2989
2990                 return jQuery.makeArray( selector, this );
2991         };
2992
2993 // Give the init function the jQuery prototype for later instantiation
2994 init.prototype = jQuery.fn;
2995
2996 // Initialize central reference
2997 rootjQuery = jQuery( document );
2998
2999
3000 var rparentsprev = /^(?:parents|prev(?:Until|All))/,
3001
3002         // Methods guaranteed to produce a unique set when starting from a unique set
3003         guaranteedUnique = {
3004                 children: true,
3005                 contents: true,
3006                 next: true,
3007                 prev: true
3008         };
3009
3010 jQuery.fn.extend( {
3011         has: function( target ) {
3012                 var targets = jQuery( target, this ),
3013                         l = targets.length;
3014
3015                 return this.filter( function() {
3016                         var i = 0;
3017                         for ( ; i < l; i++ ) {
3018                                 if ( jQuery.contains( this, targets[ i ] ) ) {
3019                                         return true;
3020                                 }
3021                         }
3022                 } );
3023         },
3024
3025         closest: function( selectors, context ) {
3026                 var cur,
3027                         i = 0,
3028                         l = this.length,
3029                         matched = [],
3030                         targets = typeof selectors !== "string" && jQuery( selectors );
3031
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 ) {
3036
3037                                         // Always skip document fragments
3038                                         if ( cur.nodeType < 11 && ( targets ?
3039                                                 targets.index( cur ) > -1 :
3040
3041                                                 // Don't pass non-elements to Sizzle
3042                                                 cur.nodeType === 1 &&
3043                                                         jQuery.find.matchesSelector( cur, selectors ) ) ) {
3044
3045                                                 matched.push( cur );
3046                                                 break;
3047                                         }
3048                                 }
3049                         }
3050                 }
3051
3052                 return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
3053         },
3054
3055         // Determine the position of an element within the set
3056         index: function( elem ) {
3057
3058                 // No argument, return index in parent
3059                 if ( !elem ) {
3060                         return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
3061                 }
3062
3063                 // Index in selector
3064                 if ( typeof elem === "string" ) {
3065                         return indexOf.call( jQuery( elem ), this[ 0 ] );
3066                 }
3067
3068                 // Locate the position of the desired element
3069                 return indexOf.call( this,
3070
3071                         // If it receives a jQuery object, the first element is used
3072                         elem.jquery ? elem[ 0 ] : elem
3073                 );
3074         },
3075
3076         add: function( selector, context ) {
3077                 return this.pushStack(
3078                         jQuery.uniqueSort(
3079                                 jQuery.merge( this.get(), jQuery( selector, context ) )
3080                         )
3081                 );
3082         },
3083
3084         addBack: function( selector ) {
3085                 return this.add( selector == null ?
3086                         this.prevObject : this.prevObject.filter( selector )
3087                 );
3088         }
3089 } );
3090
3091 function sibling( cur, dir ) {
3092         while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
3093         return cur;
3094 }
3095
3096 jQuery.each( {
3097         parent: function( elem ) {
3098                 var parent = elem.parentNode;
3099                 return parent && parent.nodeType !== 11 ? parent : null;
3100         },
3101         parents: function( elem ) {
3102                 return dir( elem, "parentNode" );
3103         },
3104         parentsUntil: function( elem, i, until ) {
3105                 return dir( elem, "parentNode", until );
3106         },
3107         next: function( elem ) {
3108                 return sibling( elem, "nextSibling" );
3109         },
3110         prev: function( elem ) {
3111                 return sibling( elem, "previousSibling" );
3112         },
3113         nextAll: function( elem ) {
3114                 return dir( elem, "nextSibling" );
3115         },
3116         prevAll: function( elem ) {
3117                 return dir( elem, "previousSibling" );
3118         },
3119         nextUntil: function( elem, i, until ) {
3120                 return dir( elem, "nextSibling", until );
3121         },
3122         prevUntil: function( elem, i, until ) {
3123                 return dir( elem, "previousSibling", until );
3124         },
3125         siblings: function( elem ) {
3126                 return siblings( ( elem.parentNode || {} ).firstChild, elem );
3127         },
3128         children: function( elem ) {
3129                 return siblings( elem.firstChild );
3130         },
3131         contents: function( elem ) {
3132                 return elem.contentDocument || jQuery.merge( [], elem.childNodes );
3133         }
3134 }, function( name, fn ) {
3135         jQuery.fn[ name ] = function( until, selector ) {
3136                 var matched = jQuery.map( this, fn, until );
3137
3138                 if ( name.slice( -5 ) !== "Until" ) {
3139                         selector = until;
3140                 }
3141
3142                 if ( selector && typeof selector === "string" ) {
3143                         matched = jQuery.filter( selector, matched );
3144                 }
3145
3146                 if ( this.length > 1 ) {
3147
3148                         // Remove duplicates
3149                         if ( !guaranteedUnique[ name ] ) {
3150                                 jQuery.uniqueSort( matched );
3151                         }
3152
3153                         // Reverse order for parents* and prev-derivatives
3154                         if ( rparentsprev.test( name ) ) {
3155                                 matched.reverse();
3156                         }
3157                 }
3158
3159                 return this.pushStack( matched );
3160         };
3161 } );
3162 var rnotwhite = ( /\S+/g );
3163
3164
3165
3166 // Convert String-formatted options into Object-formatted ones
3167 function createOptions( options ) {
3168         var object = {};
3169         jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
3170                 object[ flag ] = true;
3171         } );
3172         return object;
3173 }
3174
3175 /*
3176  * Create a callback list using the following parameters:
3177  *
3178  *      options: an optional list of space-separated options that will change how
3179  *                      the callback list behaves or a more traditional option object
3180  *
3181  * By default a callback list will act like an event callback list and can be
3182  * "fired" multiple times.
3183  *
3184  * Possible options:
3185  *
3186  *      once:                   will ensure the callback list can only be fired once (like a Deferred)
3187  *
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)
3191  *
3192  *      unique:                 will ensure a callback can only be added once (no duplicate in the list)
3193  *
3194  *      stopOnFalse:    interrupt callings when a callback returns false
3195  *
3196  */
3197 jQuery.Callbacks = function( options ) {
3198
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 );
3204
3205         var // Flag to know if list is currently firing
3206                 firing,
3207
3208                 // Last fire value for non-forgettable lists
3209                 memory,
3210
3211                 // Flag to know if list was already fired
3212                 fired,
3213
3214                 // Flag to prevent firing
3215                 locked,
3216
3217                 // Actual callback list
3218                 list = [],
3219
3220                 // Queue of execution data for repeatable lists
3221                 queue = [],
3222
3223                 // Index of currently firing callback (modified by add/remove as needed)
3224                 firingIndex = -1,
3225
3226                 // Fire callbacks
3227                 fire = function() {
3228
3229                         // Enforce single-firing
3230                         locked = options.once;
3231
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 ) {
3238
3239                                         // Run callback and check for early termination
3240                                         if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
3241                                                 options.stopOnFalse ) {
3242
3243                                                 // Jump to end and forget the data so .add doesn't re-fire
3244                                                 firingIndex = list.length;
3245                                                 memory = false;
3246                                         }
3247                                 }
3248                         }
3249
3250                         // Forget the data if we're done with it
3251                         if ( !options.memory ) {
3252                                 memory = false;
3253                         }
3254
3255                         firing = false;
3256
3257                         // Clean up if we're done firing for good
3258                         if ( locked ) {
3259
3260                                 // Keep an empty list if we have data for future add calls
3261                                 if ( memory ) {
3262                                         list = [];
3263
3264                                 // Otherwise, this object is spent
3265                                 } else {
3266                                         list = "";
3267                                 }
3268                         }
3269                 },
3270
3271                 // Actual Callbacks object
3272                 self = {
3273
3274                         // Add a callback or a collection of callbacks to the list
3275                         add: function() {
3276                                 if ( list ) {
3277
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 );
3282                                         }
3283
3284                                         ( function add( args ) {
3285                                                 jQuery.each( args, function( _, arg ) {
3286                                                         if ( jQuery.isFunction( arg ) ) {
3287                                                                 if ( !options.unique || !self.has( arg ) ) {
3288                                                                         list.push( arg );
3289                                                                 }
3290                                                         } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {
3291
3292                                                                 // Inspect recursively
3293                                                                 add( arg );
3294                                                         }
3295                                                 } );
3296                                         } )( arguments );
3297
3298                                         if ( memory && !firing ) {
3299                                                 fire();
3300                                         }
3301                                 }
3302                                 return this;
3303                         },
3304
3305                         // Remove a callback from the list
3306                         remove: function() {
3307                                 jQuery.each( arguments, function( _, arg ) {
3308                                         var index;
3309                                         while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
3310                                                 list.splice( index, 1 );
3311
3312                                                 // Handle firing indexes
3313                                                 if ( index <= firingIndex ) {
3314                                                         firingIndex--;
3315                                                 }
3316                                         }
3317                                 } );
3318                                 return this;
3319                         },
3320
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 ) {
3324                                 return fn ?
3325                                         jQuery.inArray( fn, list ) > -1 :
3326                                         list.length > 0;
3327                         },
3328
3329                         // Remove all callbacks from the list
3330                         empty: function() {
3331                                 if ( list ) {
3332                                         list = [];
3333                                 }
3334                                 return this;
3335                         },
3336
3337                         // Disable .fire and .add
3338                         // Abort any current/pending executions
3339                         // Clear all callbacks and values
3340                         disable: function() {
3341                                 locked = queue = [];
3342                                 list = memory = "";
3343                                 return this;
3344                         },
3345                         disabled: function() {
3346                                 return !list;
3347                         },
3348
3349                         // Disable .fire
3350                         // Also disable .add unless we have memory (since it would have no effect)
3351                         // Abort any pending executions
3352                         lock: function() {
3353                                 locked = queue = [];
3354                                 if ( !memory && !firing ) {
3355                                         list = memory = "";
3356                                 }
3357                                 return this;
3358                         },
3359                         locked: function() {
3360                                 return !!locked;
3361                         },
3362
3363                         // Call all callbacks with the given context and arguments
3364                         fireWith: function( context, args ) {
3365                                 if ( !locked ) {
3366                                         args = args || [];
3367                                         args = [ context, args.slice ? args.slice() : args ];
3368                                         queue.push( args );
3369                                         if ( !firing ) {
3370                                                 fire();
3371                                         }
3372                                 }
3373                                 return this;
3374                         },
3375
3376                         // Call all the callbacks with the given arguments
3377                         fire: function() {
3378                                 self.fireWith( this, arguments );
3379                                 return this;
3380                         },
3381
3382                         // To know if the callbacks have already been called at least once
3383                         fired: function() {
3384                                 return !!fired;
3385                         }
3386                 };
3387
3388         return self;
3389 };
3390
3391
3392 function Identity( v ) {
3393         return v;
3394 }
3395 function Thrower( ex ) {
3396         throw ex;
3397 }
3398
3399 function adoptValue( value, resolve, reject ) {
3400         var method;
3401
3402         try {
3403
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 );
3407
3408                 // Other thenables
3409                 } else if ( value && jQuery.isFunction( ( method = value.then ) ) ) {
3410                         method.call( value, resolve, reject );
3411
3412                 // Other non-thenables
3413                 } else {
3414
3415                         // Support: Android 4.0 only
3416                         // Strict mode functions invoked without .call/.apply get global-object context
3417                         resolve.call( undefined, value );
3418                 }
3419
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.
3423         } catch ( value ) {
3424
3425                 // Support: Android 4.0 only
3426                 // Strict mode functions invoked without .call/.apply get global-object context
3427                 reject.call( undefined, value );
3428         }
3429 }
3430
3431 jQuery.extend( {
3432
3433         Deferred: function( func ) {
3434                 var tuples = [
3435
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" ]
3444                         ],
3445                         state = "pending",
3446                         promise = {
3447                                 state: function() {
3448                                         return state;
3449                                 },
3450                                 always: function() {
3451                                         deferred.done( arguments ).fail( arguments );
3452                                         return this;
3453                                 },
3454                                 "catch": function( fn ) {
3455                                         return promise.then( null, fn );
3456                                 },
3457
3458                                 // Keep pipe for back-compat
3459                                 pipe: function( /* fnDone, fnFail, fnProgress */ ) {
3460                                         var fns = arguments;
3461
3462                                         return jQuery.Deferred( function( newDefer ) {
3463                                                 jQuery.each( tuples, function( i, tuple ) {
3464
3465                                                         // Map tuples (progress, done, fail) to arguments (done, fail, progress)
3466                                                         var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];
3467
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 ) ) {
3474                                                                         returned.promise()
3475                                                                                 .progress( newDefer.notify )
3476                                                                                 .done( newDefer.resolve )
3477                                                                                 .fail( newDefer.reject );
3478                                                                 } else {
3479                                                                         newDefer[ tuple[ 0 ] + "With" ](
3480                                                                                 this,
3481                                                                                 fn ? [ returned ] : arguments
3482                                                                         );
3483                                                                 }
3484                                                         } );
3485                                                 } );
3486                                                 fns = null;
3487                                         } ).promise();
3488                                 },
3489                                 then: function( onFulfilled, onRejected, onProgress ) {
3490                                         var maxDepth = 0;
3491                                         function resolve( depth, deferred, handler, special ) {
3492                                                 return function() {
3493                                                         var that = this,
3494                                                                 args = arguments,
3495                                                                 mightThrow = function() {
3496                                                                         var returned, then;
3497
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 ) {
3502                                                                                 return;
3503                                                                         }
3504
3505                                                                         returned = handler.apply( that, args );
3506
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" );
3511                                                                         }
3512
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
3517                                                                         then = returned &&
3518
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" ) &&
3524                                                                                 returned.then;
3525
3526                                                                         // Handle a returned thenable
3527                                                                         if ( jQuery.isFunction( then ) ) {
3528
3529                                                                                 // Special processors (notify) just wait for resolution
3530                                                                                 if ( special ) {
3531                                                                                         then.call(
3532                                                                                                 returned,
3533                                                                                                 resolve( maxDepth, deferred, Identity, special ),
3534                                                                                                 resolve( maxDepth, deferred, Thrower, special )
3535                                                                                         );
3536
3537                                                                                 // Normal processors (resolve) also hook into progress
3538                                                                                 } else {
3539
3540                                                                                         // ...and disregard older resolution values
3541                                                                                         maxDepth++;
3542
3543                                                                                         then.call(
3544                                                                                                 returned,
3545                                                                                                 resolve( maxDepth, deferred, Identity, special ),
3546                                                                                                 resolve( maxDepth, deferred, Thrower, special ),
3547                                                                                                 resolve( maxDepth, deferred, Identity,
3548                                                                                                         deferred.notifyWith )
3549                                                                                         );
3550                                                                                 }
3551
3552                                                                         // Handle all other returned values
3553                                                                         } else {
3554
3555                                                                                 // Only substitute handlers pass on context
3556                                                                                 // and multiple values (non-spec behavior)
3557                                                                                 if ( handler !== Identity ) {
3558                                                                                         that = undefined;
3559                                                                                         args = [ returned ];
3560                                                                                 }
3561
3562                                                                                 // Process the value(s)
3563                                                                                 // Default process is resolve
3564                                                                                 ( special || deferred.resolveWith )( that, args );
3565                                                                         }
3566                                                                 },
3567
3568                                                                 // Only normal processors (resolve) catch and reject exceptions
3569                                                                 process = special ?
3570                                                                         mightThrow :
3571                                                                         function() {
3572                                                                                 try {
3573                                                                                         mightThrow();
3574                                                                                 } catch ( e ) {
3575
3576                                                                                         if ( jQuery.Deferred.exceptionHook ) {
3577                                                                                                 jQuery.Deferred.exceptionHook( e,
3578                                                                                                         process.stackTrace );
3579                                                                                         }
3580
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 ) {
3585
3586                                                                                                 // Only substitute handlers pass on context
3587                                                                                                 // and multiple values (non-spec behavior)
3588                                                                                                 if ( handler !== Thrower ) {
3589                                                                                                         that = undefined;
3590                                                                                                         args = [ e ];
3591                                                                                                 }
3592
3593                                                                                                 deferred.rejectWith( that, args );
3594                                                                                         }
3595                                                                                 }
3596                                                                         };
3597
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
3602                                                         if ( depth ) {
3603                                                                 process();
3604                                                         } else {
3605
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();
3610                                                                 }
3611                                                                 window.setTimeout( process );
3612                                                         }
3613                                                 };
3614                                         }
3615
3616                                         return jQuery.Deferred( function( newDefer ) {
3617
3618                                                 // progress_handlers.add( ... )
3619                                                 tuples[ 0 ][ 3 ].add(
3620                                                         resolve(
3621                                                                 0,
3622                                                                 newDefer,
3623                                                                 jQuery.isFunction( onProgress ) ?
3624                                                                         onProgress :
3625                                                                         Identity,
3626                                                                 newDefer.notifyWith
3627                                                         )
3628                                                 );
3629
3630                                                 // fulfilled_handlers.add( ... )
3631                                                 tuples[ 1 ][ 3 ].add(
3632                                                         resolve(
3633                                                                 0,
3634                                                                 newDefer,
3635                                                                 jQuery.isFunction( onFulfilled ) ?
3636                                                                         onFulfilled :
3637                                                                         Identity
3638                                                         )
3639                                                 );
3640
3641                                                 // rejected_handlers.add( ... )
3642                                                 tuples[ 2 ][ 3 ].add(
3643                                                         resolve(
3644                                                                 0,
3645                                                                 newDefer,
3646                                                                 jQuery.isFunction( onRejected ) ?
3647                                                                         onRejected :
3648                                                                         Thrower
3649                                                         )
3650                                                 );
3651                                         } ).promise();
3652                                 },
3653
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;
3658                                 }
3659                         },
3660                         deferred = {};
3661
3662                 // Add list-specific methods
3663                 jQuery.each( tuples, function( i, tuple ) {
3664                         var list = tuple[ 2 ],
3665                                 stateString = tuple[ 5 ];
3666
3667                         // promise.progress = list.add
3668                         // promise.done = list.add
3669                         // promise.fail = list.add
3670                         promise[ tuple[ 1 ] ] = list.add;
3671
3672                         // Handle state
3673                         if ( stateString ) {
3674                                 list.add(
3675                                         function() {
3676
3677                                                 // state = "resolved" (i.e., fulfilled)
3678                                                 // state = "rejected"
3679                                                 state = stateString;
3680                                         },
3681
3682                                         // rejected_callbacks.disable
3683                                         // fulfilled_callbacks.disable
3684                                         tuples[ 3 - i ][ 2 ].disable,
3685
3686                                         // progress_callbacks.lock
3687                                         tuples[ 0 ][ 2 ].lock
3688                                 );
3689                         }
3690
3691                         // progress_handlers.fire
3692                         // fulfilled_handlers.fire
3693                         // rejected_handlers.fire
3694                         list.add( tuple[ 3 ].fire );
3695
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 );
3701                                 return this;
3702                         };
3703
3704                         // deferred.notifyWith = list.fireWith
3705                         // deferred.resolveWith = list.fireWith
3706                         // deferred.rejectWith = list.fireWith
3707                         deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
3708                 } );
3709
3710                 // Make the deferred a promise
3711                 promise.promise( deferred );
3712
3713                 // Call given func if any
3714                 if ( func ) {
3715                         func.call( deferred, deferred );
3716                 }
3717
3718                 // All done!
3719                 return deferred;
3720         },
3721
3722         // Deferred helper
3723         when: function( singleValue ) {
3724                 var
3725
3726                         // count of uncompleted subordinates
3727                         remaining = arguments.length,
3728
3729                         // count of unprocessed arguments
3730                         i = remaining,
3731
3732                         // subordinate fulfillment data
3733                         resolveContexts = Array( i ),
3734                         resolveValues = slice.call( arguments ),
3735
3736                         // the master Deferred
3737                         master = jQuery.Deferred(),
3738
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 );
3746                                         }
3747                                 };
3748                         };
3749
3750                 // Single- and empty arguments are adopted like Promise.resolve
3751                 if ( remaining <= 1 ) {
3752                         adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject );
3753
3754                         // Use .then() to unwrap secondary thenables (cf. gh-3000)
3755                         if ( master.state() === "pending" ||
3756                                 jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {
3757
3758                                 return master.then();
3759                         }
3760                 }
3761
3762                 // Multiple arguments are aggregated like Promise.all array elements
3763                 while ( i-- ) {
3764                         adoptValue( resolveValues[ i ], updateFunc( i ), master.reject );
3765                 }
3766
3767                 return master.promise();
3768         }
3769 } );
3770
3771
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$/;
3775
3776 jQuery.Deferred.exceptionHook = function( error, stack ) {
3777
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 );
3782         }
3783 };
3784
3785
3786
3787
3788 jQuery.readyException = function( error ) {
3789         window.setTimeout( function() {
3790                 throw error;
3791         } );
3792 };
3793
3794
3795
3796
3797 // The deferred used on DOM ready
3798 var readyList = jQuery.Deferred();
3799
3800 jQuery.fn.ready = function( fn ) {
3801
3802         readyList
3803                 .then( fn )
3804
3805                 // Wrap jQuery.readyException in a function so that the lookup
3806                 // happens at the time of error handling instead of callback
3807                 // registration.
3808                 .catch( function( error ) {
3809                         jQuery.readyException( error );
3810                 } );
3811
3812         return this;
3813 };
3814
3815 jQuery.extend( {
3816
3817         // Is the DOM ready to be used? Set to true once it occurs.
3818         isReady: false,
3819
3820         // A counter to track how many items to wait for before
3821         // the ready event fires. See #6781
3822         readyWait: 1,
3823
3824         // Hold (or release) the ready event
3825         holdReady: function( hold ) {
3826                 if ( hold ) {
3827                         jQuery.readyWait++;
3828                 } else {
3829                         jQuery.ready( true );
3830                 }
3831         },
3832
3833         // Handle when the DOM is ready
3834         ready: function( wait ) {
3835
3836                 // Abort if there are pending holds or we're already ready
3837                 if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
3838                         return;
3839                 }
3840
3841                 // Remember that the DOM is ready
3842                 jQuery.isReady = true;
3843
3844                 // If a normal DOM Ready event fired, decrement, and wait if need be
3845                 if ( wait !== true && --jQuery.readyWait > 0 ) {
3846                         return;
3847                 }
3848
3849                 // If there are functions bound, to execute
3850                 readyList.resolveWith( document, [ jQuery ] );
3851         }
3852 } );
3853
3854 jQuery.ready.then = readyList.then;
3855
3856 // The ready event handler and self cleanup method
3857 function completed() {
3858         document.removeEventListener( "DOMContentLoaded", completed );
3859         window.removeEventListener( "load", completed );
3860         jQuery.ready();
3861 }
3862
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 ) ) {
3869
3870         // Handle it asynchronously to allow scripts the opportunity to delay ready
3871         window.setTimeout( jQuery.ready );
3872
3873 } else {
3874
3875         // Use the handy event callback
3876         document.addEventListener( "DOMContentLoaded", completed );
3877
3878         // A fallback to window.onload, that will always work
3879         window.addEventListener( "load", completed );
3880 }
3881
3882
3883
3884
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 ) {
3888         var i = 0,
3889                 len = elems.length,
3890                 bulk = key == null;
3891
3892         // Sets many values
3893         if ( jQuery.type( key ) === "object" ) {
3894                 chainable = true;
3895                 for ( i in key ) {
3896                         access( elems, fn, i, key[ i ], true, emptyGet, raw );
3897                 }
3898
3899         // Sets one value
3900         } else if ( value !== undefined ) {
3901                 chainable = true;
3902
3903                 if ( !jQuery.isFunction( value ) ) {
3904                         raw = true;
3905                 }
3906
3907                 if ( bulk ) {
3908
3909                         // Bulk operations run against the entire set
3910                         if ( raw ) {
3911                                 fn.call( elems, value );
3912                                 fn = null;
3913
3914                         // ...except when executing function values
3915                         } else {
3916                                 bulk = fn;
3917                                 fn = function( elem, key, value ) {
3918                                         return bulk.call( jQuery( elem ), value );
3919                                 };
3920                         }
3921                 }
3922
3923                 if ( fn ) {
3924                         for ( ; i < len; i++ ) {
3925                                 fn(
3926                                         elems[ i ], key, raw ?
3927                                         value :
3928                                         value.call( elems[ i ], i, fn( elems[ i ], key ) )
3929                                 );
3930                         }
3931                 }
3932         }
3933
3934         return chainable ?
3935                 elems :
3936
3937                 // Gets
3938                 bulk ?
3939                         fn.call( elems ) :
3940                         len ? fn( elems[ 0 ], key ) : emptyGet;
3941 };
3942 var acceptData = function( owner ) {
3943
3944         // Accepts only:
3945         //  - Node
3946         //    - Node.ELEMENT_NODE
3947         //    - Node.DOCUMENT_NODE
3948         //  - Object
3949         //    - Any
3950         return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
3951 };
3952
3953
3954
3955
3956 function Data() {
3957         this.expando = jQuery.expando + Data.uid++;
3958 }
3959
3960 Data.uid = 1;
3961
3962 Data.prototype = {
3963
3964         cache: function( owner ) {
3965
3966                 // Check if the owner object already has a cache
3967                 var value = owner[ this.expando ];
3968
3969                 // If not, create one
3970                 if ( !value ) {
3971                         value = {};
3972
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 ) ) {
3977
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;
3982
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
3986                                 } else {
3987                                         Object.defineProperty( owner, this.expando, {
3988                                                 value: value,
3989                                                 configurable: true
3990                                         } );
3991                                 }
3992                         }
3993                 }
3994
3995                 return value;
3996         },
3997         set: function( owner, data, value ) {
3998                 var prop,
3999                         cache = this.cache( owner );
4000
4001                 // Handle: [ owner, key, value ] args
4002                 // Always use camelCase key (gh-2257)
4003                 if ( typeof data === "string" ) {
4004                         cache[ jQuery.camelCase( data ) ] = value;
4005
4006                 // Handle: [ owner, { properties } ] args
4007                 } else {
4008
4009                         // Copy the properties one-by-one to the cache object
4010                         for ( prop in data ) {
4011                                 cache[ jQuery.camelCase( prop ) ] = data[ prop ];
4012                         }
4013                 }
4014                 return cache;
4015         },
4016         get: function( owner, key ) {
4017                 return key === undefined ?
4018                         this.cache( owner ) :
4019
4020                         // Always use camelCase key (gh-2257)
4021                         owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ];
4022         },
4023         access: function( owner, key, value ) {
4024
4025                 // In cases where either:
4026                 //
4027                 //   1. No key was specified
4028                 //   2. A string key was specified, but no value provided
4029                 //
4030                 // Take the "read" path and allow the get method to determine
4031                 // which value to return, respectively either:
4032                 //
4033                 //   1. The entire cache object
4034                 //   2. The data stored at the key
4035                 //
4036                 if ( key === undefined ||
4037                                 ( ( key && typeof key === "string" ) && value === undefined ) ) {
4038
4039                         return this.get( owner, key );
4040                 }
4041
4042                 // When the key is not a string, or both a key and value
4043                 // are specified, set or extend (existing objects) with either:
4044                 //
4045                 //   1. An object of properties
4046                 //   2. A key and value
4047                 //
4048                 this.set( owner, key, value );
4049
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;
4053         },
4054         remove: function( owner, key ) {
4055                 var i,
4056                         cache = owner[ this.expando ];
4057
4058                 if ( cache === undefined ) {
4059                         return;
4060                 }
4061
4062                 if ( key !== undefined ) {
4063
4064                         // Support array or space separated string of keys
4065                         if ( jQuery.isArray( key ) ) {
4066
4067                                 // If key is an array of keys...
4068                                 // We always set camelCase keys, so remove that.
4069                                 key = key.map( jQuery.camelCase );
4070                         } else {
4071                                 key = jQuery.camelCase( key );
4072
4073                                 // If a key with the spaces exists, use it.
4074                                 // Otherwise, create an array by matching non-whitespace
4075                                 key = key in cache ?
4076                                         [ key ] :
4077                                         ( key.match( rnotwhite ) || [] );
4078                         }
4079
4080                         i = key.length;
4081
4082                         while ( i-- ) {
4083                                 delete cache[ key[ i ] ];
4084                         }
4085                 }
4086
4087                 // Remove the expando if there's no more data
4088                 if ( key === undefined || jQuery.isEmptyObject( cache ) ) {
4089
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;
4096                         } else {
4097                                 delete owner[ this.expando ];
4098                         }
4099                 }
4100         },
4101         hasData: function( owner ) {
4102                 var cache = owner[ this.expando ];
4103                 return cache !== undefined && !jQuery.isEmptyObject( cache );
4104         }
4105 };
4106 var dataPriv = new Data();
4107
4108 var dataUser = new Data();
4109
4110
4111
4112 //      Implementation Summary
4113 //
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
4121
4122 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
4123         rmultiDash = /[A-Z]/g;
4124
4125 function dataAttr( elem, key, data ) {
4126         var name;
4127
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 );
4133
4134                 if ( typeof data === "string" ) {
4135                         try {
4136                                 data = data === "true" ? true :
4137                                         data === "false" ? false :
4138                                         data === "null" ? null :
4139
4140                                         // Only convert to a number if it doesn't change the string
4141                                         +data + "" === data ? +data :
4142                                         rbrace.test( data ) ? JSON.parse( data ) :
4143                                         data;
4144                         } catch ( e ) {}
4145
4146                         // Make sure we set the data so it isn't changed later
4147                         dataUser.set( elem, key, data );
4148                 } else {
4149                         data = undefined;
4150                 }
4151         }
4152         return data;
4153 }
4154
4155 jQuery.extend( {
4156         hasData: function( elem ) {
4157                 return dataUser.hasData( elem ) || dataPriv.hasData( elem );
4158         },
4159
4160         data: function( elem, name, data ) {
4161                 return dataUser.access( elem, name, data );
4162         },
4163
4164         removeData: function( elem, name ) {
4165                 dataUser.remove( elem, name );
4166         },
4167
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 );
4172         },
4173
4174         _removeData: function( elem, name ) {
4175                 dataPriv.remove( elem, name );
4176         }
4177 } );
4178
4179 jQuery.fn.extend( {
4180         data: function( key, value ) {
4181                 var i, name, data,
4182                         elem = this[ 0 ],
4183                         attrs = elem && elem.attributes;
4184
4185                 // Gets all values
4186                 if ( key === undefined ) {
4187                         if ( this.length ) {
4188                                 data = dataUser.get( elem );
4189
4190                                 if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
4191                                         i = attrs.length;
4192                                         while ( i-- ) {
4193
4194                                                 // Support: IE 11 only
4195                                                 // The attrs elements can be null (#14894)
4196                                                 if ( attrs[ i ] ) {
4197                                                         name = attrs[ i ].name;
4198                                                         if ( name.indexOf( "data-" ) === 0 ) {
4199                                                                 name = jQuery.camelCase( name.slice( 5 ) );
4200                                                                 dataAttr( elem, name, data[ name ] );
4201                                                         }
4202                                                 }
4203                                         }
4204                                         dataPriv.set( elem, "hasDataAttrs", true );
4205                                 }
4206                         }
4207
4208                         return data;
4209                 }
4210
4211                 // Sets multiple values
4212                 if ( typeof key === "object" ) {
4213                         return this.each( function() {
4214                                 dataUser.set( this, key );
4215                         } );
4216                 }
4217
4218                 return access( this, function( value ) {
4219                         var data;
4220
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 ) {
4227
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 ) {
4232                                         return data;
4233                                 }
4234
4235                                 // Attempt to "discover" the data in
4236                                 // HTML5 custom data-* attrs
4237                                 data = dataAttr( elem, key );
4238                                 if ( data !== undefined ) {
4239                                         return data;
4240                                 }
4241
4242                                 // We tried really hard, but the data doesn't exist.
4243                                 return;
4244                         }
4245
4246                         // Set the data...
4247                         this.each( function() {
4248
4249                                 // We always store the camelCased key
4250                                 dataUser.set( this, key, value );
4251                         } );
4252                 }, null, value, arguments.length > 1, null, true );
4253         },
4254
4255         removeData: function( key ) {
4256                 return this.each( function() {
4257                         dataUser.remove( this, key );
4258                 } );
4259         }
4260 } );
4261
4262
4263 jQuery.extend( {
4264         queue: function( elem, type, data ) {
4265                 var queue;
4266
4267                 if ( elem ) {
4268                         type = ( type || "fx" ) + "queue";
4269                         queue = dataPriv.get( elem, type );
4270
4271                         // Speed up dequeue by getting out quickly if this is just a lookup
4272                         if ( data ) {
4273                                 if ( !queue || jQuery.isArray( data ) ) {
4274                                         queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
4275                                 } else {
4276                                         queue.push( data );
4277                                 }
4278                         }
4279                         return queue || [];
4280                 }
4281         },
4282
4283         dequeue: function( elem, type ) {
4284                 type = type || "fx";
4285
4286                 var queue = jQuery.queue( elem, type ),
4287                         startLength = queue.length,
4288                         fn = queue.shift(),
4289                         hooks = jQuery._queueHooks( elem, type ),
4290                         next = function() {
4291                                 jQuery.dequeue( elem, type );
4292                         };
4293
4294                 // If the fx queue is dequeued, always remove the progress sentinel
4295                 if ( fn === "inprogress" ) {
4296                         fn = queue.shift();
4297                         startLength--;
4298                 }
4299
4300                 if ( fn ) {
4301
4302                         // Add a progress sentinel to prevent the fx queue from being
4303                         // automatically dequeued
4304                         if ( type === "fx" ) {
4305                                 queue.unshift( "inprogress" );
4306                         }
4307
4308                         // Clear up the last queue stop function
4309                         delete hooks.stop;
4310                         fn.call( elem, next, hooks );
4311                 }
4312
4313                 if ( !startLength && hooks ) {
4314                         hooks.empty.fire();
4315                 }
4316         },
4317
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 ] );
4324                         } )
4325                 } );
4326         }
4327 } );
4328
4329 jQuery.fn.extend( {
4330         queue: function( type, data ) {
4331                 var setter = 2;
4332
4333                 if ( typeof type !== "string" ) {
4334                         data = type;
4335                         type = "fx";
4336                         setter--;
4337                 }
4338
4339                 if ( arguments.length < setter ) {
4340                         return jQuery.queue( this[ 0 ], type );
4341                 }
4342
4343                 return data === undefined ?
4344                         this :
4345                         this.each( function() {
4346                                 var queue = jQuery.queue( this, type, data );
4347
4348                                 // Ensure a hooks for this queue
4349                                 jQuery._queueHooks( this, type );
4350
4351                                 if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
4352                                         jQuery.dequeue( this, type );
4353                                 }
4354                         } );
4355         },
4356         dequeue: function( type ) {
4357                 return this.each( function() {
4358                         jQuery.dequeue( this, type );
4359                 } );
4360         },
4361         clearQueue: function( type ) {
4362                 return this.queue( type || "fx", [] );
4363         },
4364
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 ) {
4368                 var tmp,
4369                         count = 1,
4370                         defer = jQuery.Deferred(),
4371                         elements = this,
4372                         i = this.length,
4373                         resolve = function() {
4374                                 if ( !( --count ) ) {
4375                                         defer.resolveWith( elements, [ elements ] );
4376                                 }
4377                         };
4378
4379                 if ( typeof type !== "string" ) {
4380                         obj = type;
4381                         type = undefined;
4382                 }
4383                 type = type || "fx";
4384
4385                 while ( i-- ) {
4386                         tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
4387                         if ( tmp && tmp.empty ) {
4388                                 count++;
4389                                 tmp.empty.add( resolve );
4390                         }
4391                 }
4392                 resolve();
4393                 return defer.promise( obj );
4394         }
4395 } );
4396 var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
4397
4398 var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
4399
4400
4401 var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
4402
4403 var isHiddenWithinTree = function( elem, el ) {
4404
4405                 // isHiddenWithinTree might be called from jQuery#filter function;
4406                 // in that case, element will be second argument
4407                 elem = el || elem;
4408
4409                 // Inline style trumps all
4410                 return elem.style.display === "none" ||
4411                         elem.style.display === "" &&
4412
4413                         // Otherwise, check computed style
4414                         // Support: Firefox <=43 - 45
4415                         // Disconnected elements can have computed display: none, so first confirm that elem is
4416                         // in the document.
4417                         jQuery.contains( elem.ownerDocument, elem ) &&
4418
4419                         jQuery.css( elem, "display" ) === "none";
4420         };
4421
4422 var swap = function( elem, options, callback, args ) {
4423         var ret, name,
4424                 old = {};
4425
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 ];
4430         }
4431
4432         ret = callback.apply( elem, args || [] );
4433
4434         // Revert the old values
4435         for ( name in options ) {
4436                 elem.style[ name ] = old[ name ];
4437         }
4438
4439         return ret;
4440 };
4441
4442
4443
4444
4445 function adjustCSS( elem, prop, valueParts, tween ) {
4446         var adjusted,
4447                 scale = 1,
4448                 maxIterations = 20,
4449                 currentValue = tween ?
4450                         function() {
4451                                 return tween.cur();
4452                         } :
4453                         function() {
4454                                 return jQuery.css( elem, prop, "" );
4455                         },
4456                 initial = currentValue(),
4457                 unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
4458
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 ) );
4462
4463         if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
4464
4465                 // Trust units reported by jQuery.css
4466                 unit = unit || initialInUnit[ 3 ];
4467
4468                 // Make sure we update the tween properties later on
4469                 valueParts = valueParts || [];
4470
4471                 // Iteratively approximate from a nonzero starting point
4472                 initialInUnit = +initial || 1;
4473
4474                 do {
4475
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";
4479
4480                         // Adjust and apply
4481                         initialInUnit = initialInUnit / scale;
4482                         jQuery.style( elem, prop, initialInUnit + unit );
4483
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.
4486                 } while (
4487                         scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations
4488                 );
4489         }
4490
4491         if ( valueParts ) {
4492                 initialInUnit = +initialInUnit || +initial || 0;
4493
4494                 // Apply relative offset (+=/-=) if specified
4495                 adjusted = valueParts[ 1 ] ?
4496                         initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
4497                         +valueParts[ 2 ];
4498                 if ( tween ) {
4499                         tween.unit = unit;
4500                         tween.start = initialInUnit;
4501                         tween.end = adjusted;
4502                 }
4503         }
4504         return adjusted;
4505 }
4506
4507
4508 var defaultDisplayMap = {};
4509
4510 function getDefaultDisplay( elem ) {
4511         var temp,
4512                 doc = elem.ownerDocument,
4513                 nodeName = elem.nodeName,
4514                 display = defaultDisplayMap[ nodeName ];
4515
4516         if ( display ) {
4517                 return display;
4518         }
4519
4520         temp = doc.body.appendChild( doc.createElement( nodeName ) ),
4521         display = jQuery.css( temp, "display" );
4522
4523         temp.parentNode.removeChild( temp );
4524
4525         if ( display === "none" ) {
4526                 display = "block";
4527         }
4528         defaultDisplayMap[ nodeName ] = display;
4529
4530         return display;
4531 }
4532
4533 function showHide( elements, show ) {
4534         var display, elem,
4535                 values = [],
4536                 index = 0,
4537                 length = elements.length;
4538
4539         // Determine new display value for elements that need to change
4540         for ( ; index < length; index++ ) {
4541                 elem = elements[ index ];
4542                 if ( !elem.style ) {
4543                         continue;
4544                 }
4545
4546                 display = elem.style.display;
4547                 if ( show ) {
4548
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 = "";
4556                                 }
4557                         }
4558                         if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
4559                                 values[ index ] = getDefaultDisplay( elem );
4560                         }
4561                 } else {
4562                         if ( display !== "none" ) {
4563                                 values[ index ] = "none";
4564
4565                                 // Remember what we're overwriting
4566                                 dataPriv.set( elem, "display", display );
4567                         }
4568                 }
4569         }
4570
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 ];
4575                 }
4576         }
4577
4578         return elements;
4579 }
4580
4581 jQuery.fn.extend( {
4582         show: function() {
4583                 return showHide( this, true );
4584         },
4585         hide: function() {
4586                 return showHide( this );
4587         },
4588         toggle: function( state ) {
4589                 if ( typeof state === "boolean" ) {
4590                         return state ? this.show() : this.hide();
4591                 }
4592
4593                 return this.each( function() {
4594                         if ( isHiddenWithinTree( this ) ) {
4595                                 jQuery( this ).show();
4596                         } else {
4597                                 jQuery( this ).hide();
4598                         }
4599                 } );
4600         }
4601 } );
4602 var rcheckableType = ( /^(?:checkbox|radio)$/i );
4603
4604 var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i );
4605
4606 var rscriptType = ( /^$|\/(?:java|ecma)script/i );
4607
4608
4609
4610 // We have to close these tags to support XHTML (#13200)
4611 var wrapMap = {
4612
4613         // Support: IE <=9 only
4614         option: [ 1, "<select multiple='multiple'>", "</select>" ],
4615
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>" ],
4623
4624         _default: [ 0, "", "" ]
4625 };
4626
4627 // Support: IE <=9 only
4628 wrapMap.optgroup = wrapMap.option;
4629
4630 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
4631 wrapMap.th = wrapMap.td;
4632
4633
4634 function getAll( context, tag ) {
4635
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 || "*" ) :
4642                         [];
4643
4644         return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
4645                 jQuery.merge( [ context ], ret ) :
4646                 ret;
4647 }
4648
4649
4650 // Mark scripts as having already been evaluated
4651 function setGlobalEval( elems, refElements ) {
4652         var i = 0,
4653                 l = elems.length;
4654
4655         for ( ; i < l; i++ ) {
4656                 dataPriv.set(
4657                         elems[ i ],
4658                         "globalEval",
4659                         !refElements || dataPriv.get( refElements[ i ], "globalEval" )
4660                 );
4661         }
4662 }
4663
4664
4665 var rhtml = /<|&#?\w+;/;
4666
4667 function buildFragment( elems, context, scripts, selection, ignored ) {
4668         var elem, tmp, tag, wrap, contains, j,
4669                 fragment = context.createDocumentFragment(),
4670                 nodes = [],
4671                 i = 0,
4672                 l = elems.length;
4673
4674         for ( ; i < l; i++ ) {
4675                 elem = elems[ i ];
4676
4677                 if ( elem || elem === 0 ) {
4678
4679                         // Add nodes directly
4680                         if ( jQuery.type( elem ) === "object" ) {
4681
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 );
4685
4686                         // Convert non-html into a text node
4687                         } else if ( !rhtml.test( elem ) ) {
4688                                 nodes.push( context.createTextNode( elem ) );
4689
4690                         // Convert html into DOM nodes
4691                         } else {
4692                                 tmp = tmp || fragment.appendChild( context.createElement( "div" ) );
4693
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 ];
4698
4699                                 // Descend through wrappers to the right content
4700                                 j = wrap[ 0 ];
4701                                 while ( j-- ) {
4702                                         tmp = tmp.lastChild;
4703                                 }
4704
4705                                 // Support: Android <=4.0 only, PhantomJS 1 only
4706                                 // push.apply(_, arraylike) throws on ancient WebKit
4707                                 jQuery.merge( nodes, tmp.childNodes );
4708
4709                                 // Remember the top-level container
4710                                 tmp = fragment.firstChild;
4711
4712                                 // Ensure the created nodes are orphaned (#12392)
4713                                 tmp.textContent = "";
4714                         }
4715                 }
4716         }
4717
4718         // Remove wrapper from fragment
4719         fragment.textContent = "";
4720
4721         i = 0;
4722         while ( ( elem = nodes[ i++ ] ) ) {
4723
4724                 // Skip elements already in the context collection (trac-4087)
4725                 if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
4726                         if ( ignored ) {
4727                                 ignored.push( elem );
4728                         }
4729                         continue;
4730                 }
4731
4732                 contains = jQuery.contains( elem.ownerDocument, elem );
4733
4734                 // Append to fragment
4735                 tmp = getAll( fragment.appendChild( elem ), "script" );
4736
4737                 // Preserve script evaluation history
4738                 if ( contains ) {
4739                         setGlobalEval( tmp );
4740                 }
4741
4742                 // Capture executables
4743                 if ( scripts ) {
4744                         j = 0;
4745                         while ( ( elem = tmp[ j++ ] ) ) {
4746                                 if ( rscriptType.test( elem.type || "" ) ) {
4747                                         scripts.push( elem );
4748                                 }
4749                         }
4750                 }
4751         }
4752
4753         return fragment;
4754 }
4755
4756
4757 ( function() {
4758         var fragment = document.createDocumentFragment(),
4759                 div = fragment.appendChild( document.createElement( "div" ) ),
4760                 input = document.createElement( "input" );
4761
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" );
4769
4770         div.appendChild( input );
4771
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;
4775
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;
4780 } )();
4781 var documentElement = document.documentElement;
4782
4783
4784
4785 var
4786         rkeyEvent = /^key/,
4787         rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
4788         rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
4789
4790 function returnTrue() {
4791         return true;
4792 }
4793
4794 function returnFalse() {
4795         return false;
4796 }
4797
4798 // Support: IE <=9 only
4799 // See #13393 for more info
4800 function safeActiveElement() {
4801         try {
4802                 return document.activeElement;
4803         } catch ( err ) { }
4804 }
4805
4806 function on( elem, types, selector, data, fn, one ) {
4807         var origFn, type;
4808
4809         // Types can be a map of types/handlers
4810         if ( typeof types === "object" ) {
4811
4812                 // ( types-Object, selector, data )
4813                 if ( typeof selector !== "string" ) {
4814
4815                         // ( types-Object, data )
4816                         data = data || selector;
4817                         selector = undefined;
4818                 }
4819                 for ( type in types ) {
4820                         on( elem, type, selector, data, types[ type ], one );
4821                 }
4822                 return elem;
4823         }
4824
4825         if ( data == null && fn == null ) {
4826
4827                 // ( types, fn )
4828                 fn = selector;
4829                 data = selector = undefined;
4830         } else if ( fn == null ) {
4831                 if ( typeof selector === "string" ) {
4832
4833                         // ( types, selector, fn )
4834                         fn = data;
4835                         data = undefined;
4836                 } else {
4837
4838                         // ( types, data, fn )
4839                         fn = data;
4840                         data = selector;
4841                         selector = undefined;
4842                 }
4843         }
4844         if ( fn === false ) {
4845                 fn = returnFalse;
4846         } else if ( !fn ) {
4847                 return elem;
4848         }
4849
4850         if ( one === 1 ) {
4851                 origFn = fn;
4852                 fn = function( event ) {
4853
4854                         // Can use an empty set, since event contains the info
4855                         jQuery().off( event );
4856                         return origFn.apply( this, arguments );
4857                 };
4858
4859                 // Use same guid so caller can remove using origFn
4860                 fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
4861         }
4862         return elem.each( function() {
4863                 jQuery.event.add( this, types, fn, data, selector );
4864         } );
4865 }
4866
4867 /*
4868  * Helper functions for managing events -- not part of the public interface.
4869  * Props to Dean Edwards' addEvent library for many of the ideas.
4870  */
4871 jQuery.event = {
4872
4873         global: {},
4874
4875         add: function( elem, types, handler, data, selector ) {
4876
4877                 var handleObjIn, eventHandle, tmp,
4878                         events, t, handleObj,
4879                         special, handlers, type, namespaces, origType,
4880                         elemData = dataPriv.get( elem );
4881
4882                 // Don't attach events to noData or text/comment nodes (but allow plain objects)
4883                 if ( !elemData ) {
4884                         return;
4885                 }
4886
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;
4892                 }
4893
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)
4896                 if ( selector ) {
4897                         jQuery.find.matchesSelector( documentElement, selector );
4898                 }
4899
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++;
4903                 }
4904
4905                 // Init the element's event structure and main handler, if this is the first
4906                 if ( !( events = elemData.events ) ) {
4907                         events = elemData.events = {};
4908                 }
4909                 if ( !( eventHandle = elemData.handle ) ) {
4910                         eventHandle = elemData.handle = function( e ) {
4911
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;
4916                         };
4917                 }
4918
4919                 // Handle multiple events separated by a space
4920                 types = ( types || "" ).match( rnotwhite ) || [ "" ];
4921                 t = types.length;
4922                 while ( t-- ) {
4923                         tmp = rtypenamespace.exec( types[ t ] ) || [];
4924                         type = origType = tmp[ 1 ];
4925                         namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
4926
4927                         // There *must* be a type, no attaching namespace-only handlers
4928                         if ( !type ) {
4929                                 continue;
4930                         }
4931
4932                         // If event changes its type, use the special event handlers for the changed type
4933                         special = jQuery.event.special[ type ] || {};
4934
4935                         // If selector defined, determine special event api type, otherwise given type
4936                         type = ( selector ? special.delegateType : special.bindType ) || type;
4937
4938                         // Update special based on newly reset type
4939                         special = jQuery.event.special[ type ] || {};
4940
4941                         // handleObj is passed to all event handlers
4942                         handleObj = jQuery.extend( {
4943                                 type: type,
4944                                 origType: origType,
4945                                 data: data,
4946                                 handler: handler,
4947                                 guid: handler.guid,
4948                                 selector: selector,
4949                                 needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
4950                                 namespace: namespaces.join( "." )
4951                         }, handleObjIn );
4952
4953                         // Init the event handler queue if we're the first
4954                         if ( !( handlers = events[ type ] ) ) {
4955                                 handlers = events[ type ] = [];
4956                                 handlers.delegateCount = 0;
4957
4958                                 // Only use addEventListener if the special events handler returns false
4959                                 if ( !special.setup ||
4960                                         special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
4961
4962                                         if ( elem.addEventListener ) {
4963                                                 elem.addEventListener( type, eventHandle );
4964                                         }
4965                                 }
4966                         }
4967
4968                         if ( special.add ) {
4969                                 special.add.call( elem, handleObj );
4970
4971                                 if ( !handleObj.handler.guid ) {
4972                                         handleObj.handler.guid = handler.guid;
4973                                 }
4974                         }
4975
4976                         // Add to the element's handler list, delegates in front
4977                         if ( selector ) {
4978                                 handlers.splice( handlers.delegateCount++, 0, handleObj );
4979                         } else {
4980                                 handlers.push( handleObj );
4981                         }
4982
4983                         // Keep track of which events have ever been used, for event optimization
4984                         jQuery.event.global[ type ] = true;
4985                 }
4986
4987         },
4988
4989         // Detach an event or set of events from an element
4990         remove: function( elem, types, handler, selector, mappedTypes ) {
4991
4992                 var j, origCount, tmp,
4993                         events, t, handleObj,
4994                         special, handlers, type, namespaces, origType,
4995                         elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );
4996
4997                 if ( !elemData || !( events = elemData.events ) ) {
4998                         return;
4999                 }
5000
5001                 // Once for each type.namespace in types; type may be omitted
5002                 types = ( types || "" ).match( rnotwhite ) || [ "" ];
5003                 t = types.length;
5004                 while ( t-- ) {
5005                         tmp = rtypenamespace.exec( types[ t ] ) || [];
5006                         type = origType = tmp[ 1 ];
5007                         namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
5008
5009                         // Unbind all events (on this namespace, if provided) for the element
5010                         if ( !type ) {
5011                                 for ( type in events ) {
5012                                         jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
5013                                 }
5014                                 continue;
5015                         }
5016
5017                         special = jQuery.event.special[ type ] || {};
5018                         type = ( selector ? special.delegateType : special.bindType ) || type;
5019                         handlers = events[ type ] || [];
5020                         tmp = tmp[ 2 ] &&
5021                                 new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );
5022
5023                         // Remove matching events
5024                         origCount = j = handlers.length;
5025                         while ( j-- ) {
5026                                 handleObj = handlers[ j ];
5027
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 );
5034
5035                                         if ( handleObj.selector ) {
5036                                                 handlers.delegateCount--;
5037                                         }
5038                                         if ( special.remove ) {
5039                                                 special.remove.call( elem, handleObj );
5040                                         }
5041                                 }
5042                         }
5043
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 ) {
5049
5050                                         jQuery.removeEvent( elem, type, elemData.handle );
5051                                 }
5052
5053                                 delete events[ type ];
5054                         }
5055                 }
5056
5057                 // Remove data and the expando if it's no longer used
5058                 if ( jQuery.isEmptyObject( events ) ) {
5059                         dataPriv.remove( elem, "handle events" );
5060                 }
5061         },
5062
5063         dispatch: function( nativeEvent ) {
5064
5065                 // Make a writable jQuery.Event from the native event object
5066                 var event = jQuery.event.fix( nativeEvent );
5067
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 ] || {};
5072
5073                 // Use the fix-ed jQuery.Event rather than the (read-only) native event
5074                 args[ 0 ] = event;
5075
5076                 for ( i = 1; i < arguments.length; i++ ) {
5077                         args[ i ] = arguments[ i ];
5078                 }
5079
5080                 event.delegateTarget = this;
5081
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 ) {
5084                         return;
5085                 }
5086
5087                 // Determine handlers
5088                 handlerQueue = jQuery.event.handlers.call( this, event, handlers );
5089
5090                 // Run delegates first; they may want to stop propagation beneath us
5091                 i = 0;
5092                 while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
5093                         event.currentTarget = matched.elem;
5094
5095                         j = 0;
5096                         while ( ( handleObj = matched.handlers[ j++ ] ) &&
5097                                 !event.isImmediatePropagationStopped() ) {
5098
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 ) ) {
5102
5103                                         event.handleObj = handleObj;
5104                                         event.data = handleObj.data;
5105
5106                                         ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
5107                                                 handleObj.handler ).apply( matched.elem, args );
5108
5109                                         if ( ret !== undefined ) {
5110                                                 if ( ( event.result = ret ) === false ) {
5111                                                         event.preventDefault();
5112                                                         event.stopPropagation();
5113                                                 }
5114                                         }
5115                                 }
5116                         }
5117                 }
5118
5119                 // Call the postDispatch hook for the mapped type
5120                 if ( special.postDispatch ) {
5121                         special.postDispatch.call( this, event );
5122                 }
5123
5124                 return event.result;
5125         },
5126
5127         handlers: function( event, handlers ) {
5128                 var i, matches, sel, handleObj,
5129                         handlerQueue = [],
5130                         delegateCount = handlers.delegateCount,
5131                         cur = event.target;
5132
5133                 // Support: IE <=9
5134                 // Find delegate handlers
5135                 // Black-hole SVG <use> instance trees (#13180)
5136                 //
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 ) ) {
5141
5142                         for ( ; cur !== this; cur = cur.parentNode || this ) {
5143
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" ) ) {
5147                                         matches = [];
5148                                         for ( i = 0; i < delegateCount; i++ ) {
5149                                                 handleObj = handlers[ i ];
5150
5151                                                 // Don't conflict with Object.prototype properties (#13203)
5152                                                 sel = handleObj.selector + " ";
5153
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;
5158                                                 }
5159                                                 if ( matches[ sel ] ) {
5160                                                         matches.push( handleObj );
5161                                                 }
5162                                         }
5163                                         if ( matches.length ) {
5164                                                 handlerQueue.push( { elem: cur, handlers: matches } );
5165                                         }
5166                                 }
5167                         }
5168                 }
5169
5170                 // Add the remaining (directly-bound) handlers
5171                 if ( delegateCount < handlers.length ) {
5172                         handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } );
5173                 }
5174
5175                 return handlerQueue;
5176         },
5177
5178         addProp: function( name, hook ) {
5179                 Object.defineProperty( jQuery.Event.prototype, name, {
5180                         enumerable: true,
5181                         configurable: true,
5182
5183                         get: jQuery.isFunction( hook ) ?
5184                                 function() {
5185                                         if ( this.originalEvent ) {
5186                                                         return hook( this.originalEvent );
5187                                         }
5188                                 } :
5189                                 function() {
5190                                         if ( this.originalEvent ) {
5191                                                         return this.originalEvent[ name ];
5192                                         }
5193                                 },
5194
5195                         set: function( value ) {
5196                                 Object.defineProperty( this, name, {
5197                                         enumerable: true,
5198                                         configurable: true,
5199                                         writable: true,
5200                                         value: value
5201                                 } );
5202                         }
5203                 } );
5204         },
5205
5206         fix: function( originalEvent ) {
5207                 return originalEvent[ jQuery.expando ] ?
5208                         originalEvent :
5209                         new jQuery.Event( originalEvent );
5210         },
5211
5212         special: {
5213                 load: {
5214
5215                         // Prevent triggered image.load events from bubbling to window.load
5216                         noBubble: true
5217                 },
5218                 focus: {
5219
5220                         // Fire native event if possible so blur/focus sequence is correct
5221                         trigger: function() {
5222                                 if ( this !== safeActiveElement() && this.focus ) {
5223                                         this.focus();
5224                                         return false;
5225                                 }
5226                         },
5227                         delegateType: "focusin"
5228                 },
5229                 blur: {
5230                         trigger: function() {
5231                                 if ( this === safeActiveElement() && this.blur ) {
5232                                         this.blur();
5233                                         return false;
5234                                 }
5235                         },
5236                         delegateType: "focusout"
5237                 },
5238                 click: {
5239
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" ) ) {
5243                                         this.click();
5244                                         return false;
5245                                 }
5246                         },
5247
5248                         // For cross-browser consistency, don't fire native .click() on links
5249                         _default: function( event ) {
5250                                 return jQuery.nodeName( event.target, "a" );
5251                         }
5252                 },
5253
5254                 beforeunload: {
5255                         postDispatch: function( event ) {
5256
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;
5261                                 }
5262                         }
5263                 }
5264         }
5265 };
5266
5267 jQuery.removeEvent = function( elem, type, handle ) {
5268
5269         // This "if" is needed for plain objects
5270         if ( elem.removeEventListener ) {
5271                 elem.removeEventListener( type, handle );
5272         }
5273 };
5274
5275 jQuery.Event = function( src, props ) {
5276
5277         // Allow instantiation without the 'new' keyword
5278         if ( !( this instanceof jQuery.Event ) ) {
5279                 return new jQuery.Event( src, props );
5280         }
5281
5282         // Event object
5283         if ( src && src.type ) {
5284                 this.originalEvent = src;
5285                 this.type = src.type;
5286
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 &&
5291
5292                                 // Support: Android <=2.3 only
5293                                 src.returnValue === false ?
5294                         returnTrue :
5295                         returnFalse;
5296
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 :
5302                         src.target;
5303
5304                 this.currentTarget = src.currentTarget;
5305                 this.relatedTarget = src.relatedTarget;
5306
5307         // Event type
5308         } else {
5309                 this.type = src;
5310         }
5311
5312         // Put explicitly provided properties onto the event object
5313         if ( props ) {
5314                 jQuery.extend( this, props );
5315         }
5316
5317         // Create a timestamp if incoming event doesn't have one
5318         this.timeStamp = src && src.timeStamp || jQuery.now();
5319
5320         // Mark it as fixed
5321         this[ jQuery.expando ] = true;
5322 };
5323
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,
5331         isSimulated: false,
5332
5333         preventDefault: function() {
5334                 var e = this.originalEvent;
5335
5336                 this.isDefaultPrevented = returnTrue;
5337
5338                 if ( e && !this.isSimulated ) {
5339                         e.preventDefault();
5340                 }
5341         },
5342         stopPropagation: function() {
5343                 var e = this.originalEvent;
5344
5345                 this.isPropagationStopped = returnTrue;
5346
5347                 if ( e && !this.isSimulated ) {
5348                         e.stopPropagation();
5349                 }
5350         },
5351         stopImmediatePropagation: function() {
5352                 var e = this.originalEvent;
5353
5354                 this.isImmediatePropagationStopped = returnTrue;
5355
5356                 if ( e && !this.isSimulated ) {
5357                         e.stopImmediatePropagation();
5358                 }
5359
5360                 this.stopPropagation();
5361         }
5362 };
5363
5364 // Includes all common event props including KeyEvent and MouseEvent specific props
5365 jQuery.each( {
5366         altKey: true,
5367         bubbles: true,
5368         cancelable: true,
5369         changedTouches: true,
5370         ctrlKey: true,
5371         detail: true,
5372         eventPhase: true,
5373         metaKey: true,
5374         pageX: true,
5375         pageY: true,
5376         shiftKey: true,
5377         view: true,
5378         "char": true,
5379         charCode: true,
5380         key: true,
5381         keyCode: true,
5382         button: true,
5383         buttons: true,
5384         clientX: true,
5385         clientY: true,
5386         offsetX: true,
5387         offsetY: true,
5388         pointerId: true,
5389         pointerType: true,
5390         screenX: true,
5391         screenY: true,
5392         targetTouches: true,
5393         toElement: true,
5394         touches: true,
5395
5396         which: function( event ) {
5397                 var button = event.button;
5398
5399                 // Add which for key events
5400                 if ( event.which == null && rkeyEvent.test( event.type ) ) {
5401                         return event.charCode != null ? event.charCode : event.keyCode;
5402                 }
5403
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 ) ) );
5407                 }
5408
5409                 return event.which;
5410         }
5411 }, jQuery.event.addProp );
5412
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
5416 //
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).
5421 jQuery.each( {
5422         mouseenter: "mouseover",
5423         mouseleave: "mouseout",
5424         pointerenter: "pointerover",
5425         pointerleave: "pointerout"
5426 }, function( orig, fix ) {
5427         jQuery.event.special[ orig ] = {
5428                 delegateType: fix,
5429                 bindType: fix,
5430
5431                 handle: function( event ) {
5432                         var ret,
5433                                 target = this,
5434                                 related = event.relatedTarget,
5435                                 handleObj = event.handleObj;
5436
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 );
5442                                 event.type = fix;
5443                         }
5444                         return ret;
5445                 }
5446         };
5447 } );
5448
5449 jQuery.fn.extend( {
5450
5451         on: function( types, selector, data, fn ) {
5452                 return on( this, types, selector, data, fn );
5453         },
5454         one: function( types, selector, data, fn ) {
5455                 return on( this, types, selector, data, fn, 1 );
5456         },
5457         off: function( types, selector, fn ) {
5458                 var handleObj, type;
5459                 if ( types && types.preventDefault && types.handleObj ) {
5460
5461                         // ( event )  dispatched jQuery.Event
5462                         handleObj = types.handleObj;
5463                         jQuery( types.delegateTarget ).off(
5464                                 handleObj.namespace ?
5465                                         handleObj.origType + "." + handleObj.namespace :
5466                                         handleObj.origType,
5467                                 handleObj.selector,
5468                                 handleObj.handler
5469                         );
5470                         return this;
5471                 }
5472                 if ( typeof types === "object" ) {
5473
5474                         // ( types-object [, selector] )
5475                         for ( type in types ) {
5476                                 this.off( type, selector, types[ type ] );
5477                         }
5478                         return this;
5479                 }
5480                 if ( selector === false || typeof selector === "function" ) {
5481
5482                         // ( types [, fn] )
5483                         fn = selector;
5484                         selector = undefined;
5485                 }
5486                 if ( fn === false ) {
5487                         fn = returnFalse;
5488                 }
5489                 return this.each( function() {
5490                         jQuery.event.remove( this, types, fn, selector );
5491                 } );
5492         }
5493 } );
5494
5495
5496 var
5497
5498         /* eslint-disable max-len */
5499
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,
5502
5503         /* eslint-enable */
5504
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,
5509
5510         // checked="checked" or checked
5511         rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
5512         rscriptTypeMasked = /^true\/(.*)/,
5513         rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
5514
5515 function manipulationTarget( elem, content ) {
5516         if ( jQuery.nodeName( elem, "table" ) &&
5517                 jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {
5518
5519                 return elem.getElementsByTagName( "tbody" )[ 0 ] || elem;
5520         }
5521
5522         return elem;
5523 }
5524
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;
5528         return elem;
5529 }
5530 function restoreScript( elem ) {
5531         var match = rscriptTypeMasked.exec( elem.type );
5532
5533         if ( match ) {
5534                 elem.type = match[ 1 ];
5535         } else {
5536                 elem.removeAttribute( "type" );
5537         }
5538
5539         return elem;
5540 }
5541
5542 function cloneCopyEvent( src, dest ) {
5543         var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
5544
5545         if ( dest.nodeType !== 1 ) {
5546                 return;
5547         }
5548
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;
5554
5555                 if ( events ) {
5556                         delete pdataCur.handle;
5557                         pdataCur.events = {};
5558
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 ] );
5562                                 }
5563                         }
5564                 }
5565         }
5566
5567         // 2. Copy user data
5568         if ( dataUser.hasData( src ) ) {
5569                 udataOld = dataUser.access( src );
5570                 udataCur = jQuery.extend( {}, udataOld );
5571
5572                 dataUser.set( dest, udataCur );
5573         }
5574 }
5575
5576 // Fix IE bugs, see support tests
5577 function fixInput( src, dest ) {
5578         var nodeName = dest.nodeName.toLowerCase();
5579
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;
5583
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;
5587         }
5588 }
5589
5590 function domManip( collection, args, callback, ignored ) {
5591
5592         // Flatten any nested arrays
5593         args = concat.apply( [], args );
5594
5595         var fragment, first, scripts, hasScripts, node, doc,
5596                 i = 0,
5597                 l = collection.length,
5598                 iNoClone = l - 1,
5599                 value = args[ 0 ],
5600                 isFunction = jQuery.isFunction( value );
5601
5602         // We can't cloneNode fragments that contain checked, in WebKit
5603         if ( isFunction ||
5604                         ( l > 1 && typeof value === "string" &&
5605                                 !support.checkClone && rchecked.test( value ) ) ) {
5606                 return collection.each( function( index ) {
5607                         var self = collection.eq( index );
5608                         if ( isFunction ) {
5609                                 args[ 0 ] = value.call( this, index, self.html() );
5610                         }
5611                         domManip( self, args, callback, ignored );
5612                 } );
5613         }
5614
5615         if ( l ) {
5616                 fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
5617                 first = fragment.firstChild;
5618
5619                 if ( fragment.childNodes.length === 1 ) {
5620                         fragment = first;
5621                 }
5622
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;
5627
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++ ) {
5632                                 node = fragment;
5633
5634                                 if ( i !== iNoClone ) {
5635                                         node = jQuery.clone( node, true, true );
5636
5637                                         // Keep references to cloned scripts for later restoration
5638                                         if ( hasScripts ) {
5639
5640                                                 // Support: Android <=4.0 only, PhantomJS 1 only
5641                                                 // push.apply(_, arraylike) throws on ancient WebKit
5642                                                 jQuery.merge( scripts, getAll( node, "script" ) );
5643                                         }
5644                                 }
5645
5646                                 callback.call( collection[ i ], node, i );
5647                         }
5648
5649                         if ( hasScripts ) {
5650                                 doc = scripts[ scripts.length - 1 ].ownerDocument;
5651
5652                                 // Reenable scripts
5653                                 jQuery.map( scripts, restoreScript );
5654
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 ) ) {
5661
5662                                                 if ( node.src ) {
5663
5664                                                         // Optional AJAX dependency, but won't run scripts if not present
5665                                                         if ( jQuery._evalUrl ) {
5666                                                                 jQuery._evalUrl( node.src );
5667                                                         }
5668                                                 } else {
5669                                                         DOMEval( node.textContent.replace( rcleanScript, "" ), doc );
5670                                                 }
5671                                         }
5672                                 }
5673                         }
5674                 }
5675         }
5676
5677         return collection;
5678 }
5679
5680 function remove( elem, selector, keepData ) {
5681         var node,
5682                 nodes = selector ? jQuery.filter( selector, elem ) : elem,
5683                 i = 0;
5684
5685         for ( ; ( node = nodes[ i ] ) != null; i++ ) {
5686                 if ( !keepData && node.nodeType === 1 ) {
5687                         jQuery.cleanData( getAll( node ) );
5688                 }
5689
5690                 if ( node.parentNode ) {
5691                         if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
5692                                 setGlobalEval( getAll( node, "script" ) );
5693                         }
5694                         node.parentNode.removeChild( node );
5695                 }
5696         }
5697
5698         return elem;
5699 }
5700
5701 jQuery.extend( {
5702         htmlPrefilter: function( html ) {
5703                 return html.replace( rxhtmlTag, "<$1></$2>" );
5704         },
5705
5706         clone: function( elem, dataAndEvents, deepDataAndEvents ) {
5707                 var i, l, srcElements, destElements,
5708                         clone = elem.cloneNode( true ),
5709                         inPage = jQuery.contains( elem.ownerDocument, elem );
5710
5711                 // Fix IE cloning issues
5712                 if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
5713                                 !jQuery.isXMLDoc( elem ) ) {
5714
5715                         // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
5716                         destElements = getAll( clone );
5717                         srcElements = getAll( elem );
5718
5719                         for ( i = 0, l = srcElements.length; i < l; i++ ) {
5720                                 fixInput( srcElements[ i ], destElements[ i ] );
5721                         }
5722                 }
5723
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 );
5729
5730                                 for ( i = 0, l = srcElements.length; i < l; i++ ) {
5731                                         cloneCopyEvent( srcElements[ i ], destElements[ i ] );
5732                                 }
5733                         } else {
5734                                 cloneCopyEvent( elem, clone );
5735                         }
5736                 }
5737
5738                 // Preserve script evaluation history
5739                 destElements = getAll( clone, "script" );
5740                 if ( destElements.length > 0 ) {
5741                         setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
5742                 }
5743
5744                 // Return the cloned set
5745                 return clone;
5746         },
5747
5748         cleanData: function( elems ) {
5749                 var data, elem, type,
5750                         special = jQuery.event.special,
5751                         i = 0;
5752
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 );
5760
5761                                                         // This is a shortcut to avoid jQuery.event.remove's overhead
5762                                                         } else {
5763                                                                 jQuery.removeEvent( elem, type, data.handle );
5764                                                         }
5765                                                 }
5766                                         }
5767
5768                                         // Support: Chrome <=35 - 45+
5769                                         // Assign undefined instead of using delete, see Data#remove
5770                                         elem[ dataPriv.expando ] = undefined;
5771                                 }
5772                                 if ( elem[ dataUser.expando ] ) {
5773
5774                                         // Support: Chrome <=35 - 45+
5775                                         // Assign undefined instead of using delete, see Data#remove
5776                                         elem[ dataUser.expando ] = undefined;
5777                                 }
5778                         }
5779                 }
5780         }
5781 } );
5782
5783 jQuery.fn.extend( {
5784         detach: function( selector ) {
5785                 return remove( this, selector, true );
5786         },
5787
5788         remove: function( selector ) {
5789                 return remove( this, selector );
5790         },
5791
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;
5799                                         }
5800                                 } );
5801                 }, null, value, arguments.length );
5802         },
5803
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 );
5809                         }
5810                 } );
5811         },
5812
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 );
5818                         }
5819                 } );
5820         },
5821
5822         before: function() {
5823                 return domManip( this, arguments, function( elem ) {
5824                         if ( this.parentNode ) {
5825                                 this.parentNode.insertBefore( elem, this );
5826                         }
5827                 } );
5828         },
5829
5830         after: function() {
5831                 return domManip( this, arguments, function( elem ) {
5832                         if ( this.parentNode ) {
5833                                 this.parentNode.insertBefore( elem, this.nextSibling );
5834                         }
5835                 } );
5836         },
5837
5838         empty: function() {
5839                 var elem,
5840                         i = 0;
5841
5842                 for ( ; ( elem = this[ i ] ) != null; i++ ) {
5843                         if ( elem.nodeType === 1 ) {
5844
5845                                 // Prevent memory leaks
5846                                 jQuery.cleanData( getAll( elem, false ) );
5847
5848                                 // Remove any remaining nodes
5849                                 elem.textContent = "";
5850                         }
5851                 }
5852
5853                 return this;
5854         },
5855
5856         clone: function( dataAndEvents, deepDataAndEvents ) {
5857                 dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
5858                 deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
5859
5860                 return this.map( function() {
5861                         return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
5862                 } );
5863         },
5864
5865         html: function( value ) {
5866                 return access( this, function( value ) {
5867                         var elem = this[ 0 ] || {},
5868                                 i = 0,
5869                                 l = this.length;
5870
5871                         if ( value === undefined && elem.nodeType === 1 ) {
5872                                 return elem.innerHTML;
5873                         }
5874
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() ] ) {
5878
5879                                 value = jQuery.htmlPrefilter( value );
5880
5881                                 try {
5882                                         for ( ; i < l; i++ ) {
5883                                                 elem = this[ i ] || {};
5884
5885                                                 // Remove element nodes and prevent memory leaks
5886                                                 if ( elem.nodeType === 1 ) {
5887                                                         jQuery.cleanData( getAll( elem, false ) );
5888                                                         elem.innerHTML = value;
5889                                                 }
5890                                         }
5891
5892                                         elem = 0;
5893
5894                                 // If using innerHTML throws an exception, use the fallback method
5895                                 } catch ( e ) {}
5896                         }
5897
5898                         if ( elem ) {
5899                                 this.empty().append( value );
5900                         }
5901                 }, null, value, arguments.length );
5902         },
5903
5904         replaceWith: function() {
5905                 var ignored = [];
5906
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;
5910
5911                         if ( jQuery.inArray( this, ignored ) < 0 ) {
5912                                 jQuery.cleanData( getAll( this ) );
5913                                 if ( parent ) {
5914                                         parent.replaceChild( elem, this );
5915                                 }
5916                         }
5917
5918                 // Force callback invocation
5919                 }, ignored );
5920         }
5921 } );
5922
5923 jQuery.each( {
5924         appendTo: "append",
5925         prependTo: "prepend",
5926         insertBefore: "before",
5927         insertAfter: "after",
5928         replaceAll: "replaceWith"
5929 }, function( name, original ) {
5930         jQuery.fn[ name ] = function( selector ) {
5931                 var elems,
5932                         ret = [],
5933                         insert = jQuery( selector ),
5934                         last = insert.length - 1,
5935                         i = 0;
5936
5937                 for ( ; i <= last; i++ ) {
5938                         elems = i === last ? this : this.clone( true );
5939                         jQuery( insert[ i ] )[ original ]( elems );
5940
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() );
5944                 }
5945
5946                 return this.pushStack( ret );
5947         };
5948 } );
5949 var rmargin = ( /^margin/ );
5950
5951 var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
5952
5953 var getStyles = function( elem ) {
5954
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;
5959
5960                 if ( !view || !view.opener ) {
5961                         view = window;
5962                 }
5963
5964                 return view.getComputedStyle( elem );
5965         };
5966
5967
5968
5969 ( function() {
5970
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() {
5974
5975                 // This is a singleton, we need to execute it only once
5976                 if ( !div ) {
5977                         return;
5978                 }
5979
5980                 div.style.cssText =
5981                         "box-sizing:border-box;" +
5982                         "position:relative;display:block;" +
5983                         "margin:auto;border:1px;padding:1px;" +
5984                         "top:1%;width:50%";
5985                 div.innerHTML = "";
5986                 documentElement.appendChild( container );
5987
5988                 var divStyle = window.getComputedStyle( div );
5989                 pixelPositionVal = divStyle.top !== "1%";
5990
5991                 // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
5992                 reliableMarginLeftVal = divStyle.marginLeft === "2px";
5993                 boxSizingReliableVal = divStyle.width === "4px";
5994
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";
5999
6000                 documentElement.removeChild( container );
6001
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
6004                 div = null;
6005         }
6006
6007         var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal,
6008                 container = document.createElement( "div" ),
6009                 div = document.createElement( "div" );
6010
6011         // Finish early in limited (non-browser) environments
6012         if ( !div.style ) {
6013                 return;
6014         }
6015
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";
6021
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 );
6025
6026         jQuery.extend( support, {
6027                 pixelPosition: function() {
6028                         computeStyleTests();
6029                         return pixelPositionVal;
6030                 },
6031                 boxSizingReliable: function() {
6032                         computeStyleTests();
6033                         return boxSizingReliableVal;
6034                 },
6035                 pixelMarginRight: function() {
6036                         computeStyleTests();
6037                         return pixelMarginRightVal;
6038                 },
6039                 reliableMarginLeft: function() {
6040                         computeStyleTests();
6041                         return reliableMarginLeftVal;
6042                 }
6043         } );
6044 } )();
6045
6046
6047 function curCSS( elem, name, computed ) {
6048         var width, minWidth, maxWidth, ret,
6049                 style = elem.style;
6050
6051         computed = computed || getStyles( elem );
6052
6053         // Support: IE <=9 only
6054         // getPropertyValue is only needed for .css('filter') (#12537)
6055         if ( computed ) {
6056                 ret = computed.getPropertyValue( name ) || computed[ name ];
6057
6058                 if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
6059                         ret = jQuery.style( elem, name );
6060                 }
6061
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 ) ) {
6068
6069                         // Remember the original values
6070                         width = style.width;
6071                         minWidth = style.minWidth;
6072                         maxWidth = style.maxWidth;
6073
6074                         // Put in the new values to get a computed value out
6075                         style.minWidth = style.maxWidth = style.width = ret;
6076                         ret = computed.width;
6077
6078                         // Revert the changed values
6079                         style.width = width;
6080                         style.minWidth = minWidth;
6081                         style.maxWidth = maxWidth;
6082                 }
6083         }
6084
6085         return ret !== undefined ?
6086
6087                 // Support: IE <=9 - 11 only
6088                 // IE returns zIndex value as an integer.
6089                 ret + "" :
6090                 ret;
6091 }
6092
6093
6094 function addGetHookIf( conditionFn, hookFn ) {
6095
6096         // Define the hook, we'll check on the first run if it's really needed.
6097         return {
6098                 get: function() {
6099                         if ( conditionFn() ) {
6100
6101                                 // Hook not needed (or it's not possible to use it due
6102                                 // to missing dependency), remove it.
6103                                 delete this.get;
6104                                 return;
6105                         }
6106
6107                         // Hook needed; redefine it so that the support test is not executed again.
6108                         return ( this.get = hookFn ).apply( this, arguments );
6109                 }
6110         };
6111 }
6112
6113
6114 var
6115
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 = {
6122                 letterSpacing: "0",
6123                 fontWeight: "400"
6124         },
6125
6126         cssPrefixes = [ "Webkit", "Moz", "ms" ],
6127         emptyStyle = document.createElement( "div" ).style;
6128
6129 // Return a css property mapped to a potentially vendor prefixed property
6130 function vendorPropName( name ) {
6131
6132         // Shortcut for names that are not vendor prefixed
6133         if ( name in emptyStyle ) {
6134                 return name;
6135         }
6136
6137         // Check for vendor prefixed names
6138         var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
6139                 i = cssPrefixes.length;
6140
6141         while ( i-- ) {
6142                 name = cssPrefixes[ i ] + capName;
6143                 if ( name in emptyStyle ) {
6144                         return name;
6145                 }
6146         }
6147 }
6148
6149 function setPositiveNumber( elem, value, subtract ) {
6150
6151         // Any relative (+/-) values have already been
6152         // normalized at this point
6153         var matches = rcssNum.exec( value );
6154         return matches ?
6155
6156                 // Guard against undefined "subtract", e.g., when used as in cssHooks
6157                 Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
6158                 value;
6159 }
6160
6161 function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
6162         var i = extra === ( isBorderBox ? "border" : "content" ) ?
6163
6164                 // If we already have the right measurement, avoid augmentation
6165                 4 :
6166
6167                 // Otherwise initialize for horizontal or vertical properties
6168                 name === "width" ? 1 : 0,
6169
6170                 val = 0;
6171
6172         for ( ; i < 4; i += 2 ) {
6173
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 );
6177                 }
6178
6179                 if ( isBorderBox ) {
6180
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 );
6184                         }
6185
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 );
6189                         }
6190                 } else {
6191
6192                         // At this point, extra isn't content, so add padding
6193                         val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
6194
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 );
6198                         }
6199                 }
6200         }
6201
6202         return val;
6203 }
6204
6205 function getWidthOrHeight( elem, name, extra ) {
6206
6207         // Start with offset property, which is equivalent to the border-box value
6208         var val,
6209                 valueIsBorderBox = true,
6210                 styles = getStyles( elem ),
6211                 isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
6212
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 ];
6218         }
6219
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 ) {
6224
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 ];
6229                 }
6230
6231                 // Computed unit is not pixels. Stop here and return.
6232                 if ( rnumnonpx.test( val ) ) {
6233                         return val;
6234                 }
6235
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 ] );
6240
6241                 // Normalize "", auto, and prepare for extra
6242                 val = parseFloat( val ) || 0;
6243         }
6244
6245         // Use the active box-sizing model to add/subtract irrelevant styles
6246         return ( val +
6247                 augmentWidthOrHeight(
6248                         elem,
6249                         name,
6250                         extra || ( isBorderBox ? "border" : "content" ),
6251                         valueIsBorderBox,
6252                         styles
6253                 )
6254         ) + "px";
6255 }
6256
6257 jQuery.extend( {
6258
6259         // Add in style property hooks for overriding the default
6260         // behavior of getting and setting a style property
6261         cssHooks: {
6262                 opacity: {
6263                         get: function( elem, computed ) {
6264                                 if ( computed ) {
6265
6266                                         // We should always get a number back from opacity
6267                                         var ret = curCSS( elem, "opacity" );
6268                                         return ret === "" ? "1" : ret;
6269                                 }
6270                         }
6271                 }
6272         },
6273
6274         // Don't automatically add "px" to these possibly-unitless properties
6275         cssNumber: {
6276                 "animationIterationCount": true,
6277                 "columnCount": true,
6278                 "fillOpacity": true,
6279                 "flexGrow": true,
6280                 "flexShrink": true,
6281                 "fontWeight": true,
6282                 "lineHeight": true,
6283                 "opacity": true,
6284                 "order": true,
6285                 "orphans": true,
6286                 "widows": true,
6287                 "zIndex": true,
6288                 "zoom": true
6289         },
6290
6291         // Add in properties whose names you wish to fix before
6292         // setting or getting the value
6293         cssProps: {
6294                 "float": "cssFloat"
6295         },
6296
6297         // Get and set the style property on a DOM Node
6298         style: function( elem, name, value, extra ) {
6299
6300                 // Don't set styles on text and comment nodes
6301                 if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
6302                         return;
6303                 }
6304
6305                 // Make sure that we're working with the right name
6306                 var ret, type, hooks,
6307                         origName = jQuery.camelCase( name ),
6308                         style = elem.style;
6309
6310                 name = jQuery.cssProps[ origName ] ||
6311                         ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );
6312
6313                 // Gets hook for the prefixed version, then unprefixed version
6314                 hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
6315
6316                 // Check if we're setting a value
6317                 if ( value !== undefined ) {
6318                         type = typeof value;
6319
6320                         // Convert "+=" or "-=" to relative numbers (#7345)
6321                         if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
6322                                 value = adjustCSS( elem, name, ret );
6323
6324                                 // Fixes bug #9237
6325                                 type = "number";
6326                         }
6327
6328                         // Make sure that null and NaN values aren't set (#7116)
6329                         if ( value == null || value !== value ) {
6330                                 return;
6331                         }
6332
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" );
6336                         }
6337
6338                         // background-* props affect original clone's values
6339                         if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
6340                                 style[ name ] = "inherit";
6341                         }
6342
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 ) {
6346
6347                                 style[ name ] = value;
6348                         }
6349
6350                 } else {
6351
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 ) {
6355
6356                                 return ret;
6357                         }
6358
6359                         // Otherwise just get the value from the style object
6360                         return style[ name ];
6361                 }
6362         },
6363
6364         css: function( elem, name, extra, styles ) {
6365                 var val, num, hooks,
6366                         origName = jQuery.camelCase( name );
6367
6368                 // Make sure that we're working with the right name
6369                 name = jQuery.cssProps[ origName ] ||
6370                         ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );
6371
6372                 // Try prefixed name followed by the unprefixed name
6373                 hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
6374
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 );
6378                 }
6379
6380                 // Otherwise, if a way to get the computed value exists, use that
6381                 if ( val === undefined ) {
6382                         val = curCSS( elem, name, styles );
6383                 }
6384
6385                 // Convert "normal" to computed value
6386                 if ( val === "normal" && name in cssNormalTransform ) {
6387                         val = cssNormalTransform[ name ];
6388                 }
6389
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;
6394                 }
6395                 return val;
6396         }
6397 } );
6398
6399 jQuery.each( [ "height", "width" ], function( i, name ) {
6400         jQuery.cssHooks[ name ] = {
6401                 get: function( elem, computed, extra ) {
6402                         if ( computed ) {
6403
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" ) ) &&
6407
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 );
6417                                                 } ) :
6418                                                 getWidthOrHeight( elem, name, extra );
6419                         }
6420                 },
6421
6422                 set: function( elem, value, extra ) {
6423                         var matches,
6424                                 styles = extra && getStyles( elem ),
6425                                 subtract = extra && augmentWidthOrHeight(
6426                                         elem,
6427                                         name,
6428                                         extra,
6429                                         jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
6430                                         styles
6431                                 );
6432
6433                         // Convert to pixels if value adjustment is needed
6434                         if ( subtract && ( matches = rcssNum.exec( value ) ) &&
6435                                 ( matches[ 3 ] || "px" ) !== "px" ) {
6436
6437                                 elem.style[ name ] = value;
6438                                 value = jQuery.css( elem, name );
6439                         }
6440
6441                         return setPositiveNumber( elem, value, subtract );
6442                 }
6443         };
6444 } );
6445
6446 jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
6447         function( elem, computed ) {
6448                 if ( computed ) {
6449                         return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
6450                                 elem.getBoundingClientRect().left -
6451                                         swap( elem, { marginLeft: 0 }, function() {
6452                                                 return elem.getBoundingClientRect().left;
6453                                         } )
6454                                 ) + "px";
6455                 }
6456         }
6457 );
6458
6459 // These hooks are used by animate to expand properties
6460 jQuery.each( {
6461         margin: "",
6462         padding: "",
6463         border: "Width"
6464 }, function( prefix, suffix ) {
6465         jQuery.cssHooks[ prefix + suffix ] = {
6466                 expand: function( value ) {
6467                         var i = 0,
6468                                 expanded = {},
6469
6470                                 // Assumes a single number if not a string
6471                                 parts = typeof value === "string" ? value.split( " " ) : [ value ];
6472
6473                         for ( ; i < 4; i++ ) {
6474                                 expanded[ prefix + cssExpand[ i ] + suffix ] =
6475                                         parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
6476                         }
6477
6478                         return expanded;
6479                 }
6480         };
6481
6482         if ( !rmargin.test( prefix ) ) {
6483                 jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
6484         }
6485 } );
6486
6487 jQuery.fn.extend( {
6488         css: function( name, value ) {
6489                 return access( this, function( elem, name, value ) {
6490                         var styles, len,
6491                                 map = {},
6492                                 i = 0;
6493
6494                         if ( jQuery.isArray( name ) ) {
6495                                 styles = getStyles( elem );
6496                                 len = name.length;
6497
6498                                 for ( ; i < len; i++ ) {
6499                                         map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
6500                                 }
6501
6502                                 return map;
6503                         }
6504
6505                         return value !== undefined ?
6506                                 jQuery.style( elem, name, value ) :
6507                                 jQuery.css( elem, name );
6508                 }, name, value, arguments.length > 1 );
6509         }
6510 } );
6511
6512
6513 function Tween( elem, options, prop, end, easing ) {
6514         return new Tween.prototype.init( elem, options, prop, end, easing );
6515 }
6516 jQuery.Tween = Tween;
6517
6518 Tween.prototype = {
6519         constructor: Tween,
6520         init: function( elem, options, prop, end, easing, unit ) {
6521                 this.elem = elem;
6522                 this.prop = prop;
6523                 this.easing = easing || jQuery.easing._default;
6524                 this.options = options;
6525                 this.start = this.now = this.cur();
6526                 this.end = end;
6527                 this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
6528         },
6529         cur: function() {
6530                 var hooks = Tween.propHooks[ this.prop ];
6531
6532                 return hooks && hooks.get ?
6533                         hooks.get( this ) :
6534                         Tween.propHooks._default.get( this );
6535         },
6536         run: function( percent ) {
6537                 var eased,
6538                         hooks = Tween.propHooks[ this.prop ];
6539
6540                 if ( this.options.duration ) {
6541                         this.pos = eased = jQuery.easing[ this.easing ](
6542                                 percent, this.options.duration * percent, 0, 1, this.options.duration
6543                         );
6544                 } else {
6545                         this.pos = eased = percent;
6546                 }
6547                 this.now = ( this.end - this.start ) * eased + this.start;
6548
6549                 if ( this.options.step ) {
6550                         this.options.step.call( this.elem, this.now, this );
6551                 }
6552
6553                 if ( hooks && hooks.set ) {
6554                         hooks.set( this );
6555                 } else {
6556                         Tween.propHooks._default.set( this );
6557                 }
6558                 return this;
6559         }
6560 };
6561
6562 Tween.prototype.init.prototype = Tween.prototype;
6563
6564 Tween.propHooks = {
6565         _default: {
6566                 get: function( tween ) {
6567                         var result;
6568
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 ];
6574                         }
6575
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, "" );
6581
6582                         // Empty strings, null, undefined and "auto" are converted to 0.
6583                         return !result || result === "auto" ? 0 : result;
6584                 },
6585                 set: function( tween ) {
6586
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 );
6596                         } else {
6597                                 tween.elem[ tween.prop ] = tween.now;
6598                         }
6599                 }
6600         }
6601 };
6602
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;
6609                 }
6610         }
6611 };
6612
6613 jQuery.easing = {
6614         linear: function( p ) {
6615                 return p;
6616         },
6617         swing: function( p ) {
6618                 return 0.5 - Math.cos( p * Math.PI ) / 2;
6619         },
6620         _default: "swing"
6621 };
6622
6623 jQuery.fx = Tween.prototype.init;
6624
6625 // Back compat <1.8 extension point
6626 jQuery.fx.step = {};
6627
6628
6629
6630
6631 var
6632         fxNow, timerId,
6633         rfxtypes = /^(?:toggle|show|hide)$/,
6634         rrun = /queueHooks$/;
6635
6636 function raf() {
6637         if ( timerId ) {
6638                 window.requestAnimationFrame( raf );
6639                 jQuery.fx.tick();
6640         }
6641 }
6642
6643 // Animations created synchronously will run synchronously
6644 function createFxNow() {
6645         window.setTimeout( function() {
6646                 fxNow = undefined;
6647         } );
6648         return ( fxNow = jQuery.now() );
6649 }
6650
6651 // Generate parameters to create a standard animation
6652 function genFx( type, includeWidth ) {
6653         var which,
6654                 i = 0,
6655                 attrs = { height: type };
6656
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;
6663         }
6664
6665         if ( includeWidth ) {
6666                 attrs.opacity = attrs.width = type;
6667         }
6668
6669         return attrs;
6670 }
6671
6672 function createTween( value, prop, animation ) {
6673         var tween,
6674                 collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
6675                 index = 0,
6676                 length = collection.length;
6677         for ( ; index < length; index++ ) {
6678                 if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {
6679
6680                         // We're done with this property
6681                         return tween;
6682                 }
6683         }
6684 }
6685
6686 function defaultPrefilter( elem, props, opts ) {
6687         var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
6688                 isBox = "width" in props || "height" in props,
6689                 anim = this,
6690                 orig = {},
6691                 style = elem.style,
6692                 hidden = elem.nodeType && isHiddenWithinTree( elem ),
6693                 dataShow = dataPriv.get( elem, "fxshow" );
6694
6695         // Queue-skipping animations hijack the fx hooks
6696         if ( !opts.queue ) {
6697                 hooks = jQuery._queueHooks( elem, "fx" );
6698                 if ( hooks.unqueued == null ) {
6699                         hooks.unqueued = 0;
6700                         oldfire = hooks.empty.fire;
6701                         hooks.empty.fire = function() {
6702                                 if ( !hooks.unqueued ) {
6703                                         oldfire();
6704                                 }
6705                         };
6706                 }
6707                 hooks.unqueued++;
6708
6709                 anim.always( function() {
6710
6711                         // Ensure the complete handler is called before this completes
6712                         anim.always( function() {
6713                                 hooks.unqueued--;
6714                                 if ( !jQuery.queue( elem, "fx" ).length ) {
6715                                         hooks.empty.fire();
6716                                 }
6717                         } );
6718                 } );
6719         }
6720
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" ) ) {
6728
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 ) {
6732                                         hidden = true;
6733
6734                                 // Ignore all other no-op show/hide data
6735                                 } else {
6736                                         continue;
6737                                 }
6738                         }
6739                         orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
6740                 }
6741         }
6742
6743         // Bail out if this is a no-op like .hide().hide()
6744         propTween = !jQuery.isEmptyObject( props );
6745         if ( !propTween && jQuery.isEmptyObject( orig ) ) {
6746                 return;
6747         }
6748
6749         // Restrict "overflow" and "display" styles during box animations
6750         if ( isBox && elem.nodeType === 1 ) {
6751
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 ];
6756
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" );
6761                 }
6762                 display = jQuery.css( elem, "display" );
6763                 if ( display === "none" ) {
6764                         if ( restoreDisplay ) {
6765                                 display = restoreDisplay;
6766                         } else {
6767
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 ] );
6773                         }
6774                 }
6775
6776                 // Animate inline elements as inline-block
6777                 if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) {
6778                         if ( jQuery.css( elem, "float" ) === "none" ) {
6779
6780                                 // Restore the original display value at the end of pure show/hide animations
6781                                 if ( !propTween ) {
6782                                         anim.done( function() {
6783                                                 style.display = restoreDisplay;
6784                                         } );
6785                                         if ( restoreDisplay == null ) {
6786                                                 display = style.display;
6787                                                 restoreDisplay = display === "none" ? "" : display;
6788                                         }
6789                                 }
6790                                 style.display = "inline-block";
6791                         }
6792                 }
6793         }
6794
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 ];
6801                 } );
6802         }
6803
6804         // Implement show/hide animations
6805         propTween = false;
6806         for ( prop in orig ) {
6807
6808                 // General show/hide setup for this element animation
6809                 if ( !propTween ) {
6810                         if ( dataShow ) {
6811                                 if ( "hidden" in dataShow ) {
6812                                         hidden = dataShow.hidden;
6813                                 }
6814                         } else {
6815                                 dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
6816                         }
6817
6818                         // Store hidden/visible for toggle so `.stop().toggle()` "reverses"
6819                         if ( toggle ) {
6820                                 dataShow.hidden = !hidden;
6821                         }
6822
6823                         // Show elements before animating them
6824                         if ( hidden ) {
6825                                 showHide( [ elem ], true );
6826                         }
6827
6828                         /* eslint-disable no-loop-func */
6829
6830                         anim.done( function() {
6831
6832                         /* eslint-enable no-loop-func */
6833
6834                                 // The final step of a "hide" animation is actually hiding the element
6835                                 if ( !hidden ) {
6836                                         showHide( [ elem ] );
6837                                 }
6838                                 dataPriv.remove( elem, "fxshow" );
6839                                 for ( prop in orig ) {
6840                                         jQuery.style( elem, prop, orig[ prop ] );
6841                                 }
6842                         } );
6843                 }
6844
6845                 // Per-property setup
6846                 propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
6847                 if ( !( prop in dataShow ) ) {
6848                         dataShow[ prop ] = propTween.start;
6849                         if ( hidden ) {
6850                                 propTween.end = propTween.start;
6851                                 propTween.start = 0;
6852                         }
6853                 }
6854         }
6855 }
6856
6857 function propFilter( props, specialEasing ) {
6858         var index, name, easing, value, hooks;
6859
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 ];
6868                 }
6869
6870                 if ( index !== name ) {
6871                         props[ name ] = value;
6872                         delete props[ index ];
6873                 }
6874
6875                 hooks = jQuery.cssHooks[ name ];
6876                 if ( hooks && "expand" in hooks ) {
6877                         value = hooks.expand( value );
6878                         delete props[ name ];
6879
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;
6886                                 }
6887                         }
6888                 } else {
6889                         specialEasing[ name ] = easing;
6890                 }
6891         }
6892 }
6893
6894 function Animation( elem, properties, options ) {
6895         var result,
6896                 stopped,
6897                 index = 0,
6898                 length = Animation.prefilters.length,
6899                 deferred = jQuery.Deferred().always( function() {
6900
6901                         // Don't match elem in the :animated selector
6902                         delete tick.elem;
6903                 } ),
6904                 tick = function() {
6905                         if ( stopped ) {
6906                                 return false;
6907                         }
6908                         var currentTime = fxNow || createFxNow(),
6909                                 remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
6910
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,
6914                                 percent = 1 - temp,
6915                                 index = 0,
6916                                 length = animation.tweens.length;
6917
6918                         for ( ; index < length; index++ ) {
6919                                 animation.tweens[ index ].run( percent );
6920                         }
6921
6922                         deferred.notifyWith( elem, [ animation, percent, remaining ] );
6923
6924                         if ( percent < 1 && length ) {
6925                                 return remaining;
6926                         } else {
6927                                 deferred.resolveWith( elem, [ animation ] );
6928                                 return false;
6929                         }
6930                 },
6931                 animation = deferred.promise( {
6932                         elem: elem,
6933                         props: jQuery.extend( {}, properties ),
6934                         opts: jQuery.extend( true, {
6935                                 specialEasing: {},
6936                                 easing: jQuery.easing._default
6937                         }, options ),
6938                         originalProperties: properties,
6939                         originalOptions: options,
6940                         startTime: fxNow || createFxNow(),
6941                         duration: options.duration,
6942                         tweens: [],
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 );
6947                                 return tween;
6948                         },
6949                         stop: function( gotoEnd ) {
6950                                 var index = 0,
6951
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;
6955                                 if ( stopped ) {
6956                                         return this;
6957                                 }
6958                                 stopped = true;
6959                                 for ( ; index < length; index++ ) {
6960                                         animation.tweens[ index ].run( 1 );
6961                                 }
6962
6963                                 // Resolve when we played the last frame; otherwise, reject
6964                                 if ( gotoEnd ) {
6965                                         deferred.notifyWith( elem, [ animation, 1, 0 ] );
6966                                         deferred.resolveWith( elem, [ animation, gotoEnd ] );
6967                                 } else {
6968                                         deferred.rejectWith( elem, [ animation, gotoEnd ] );
6969                                 }
6970                                 return this;
6971                         }
6972                 } ),
6973                 props = animation.props;
6974
6975         propFilter( props, animation.opts.specialEasing );
6976
6977         for ( ; index < length; index++ ) {
6978                 result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
6979                 if ( result ) {
6980                         if ( jQuery.isFunction( result.stop ) ) {
6981                                 jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
6982                                         jQuery.proxy( result.stop, result );
6983                         }
6984                         return result;
6985                 }
6986         }
6987
6988         jQuery.map( props, createTween, animation );
6989
6990         if ( jQuery.isFunction( animation.opts.start ) ) {
6991                 animation.opts.start.call( elem, animation );
6992         }
6993
6994         jQuery.fx.timer(
6995                 jQuery.extend( tick, {
6996                         elem: elem,
6997                         anim: animation,
6998                         queue: animation.opts.queue
6999                 } )
7000         );
7001
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 );
7007 }
7008
7009 jQuery.Animation = jQuery.extend( Animation, {
7010
7011         tweeners: {
7012                 "*": [ function( prop, value ) {
7013                         var tween = this.createTween( prop, value );
7014                         adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
7015                         return tween;
7016                 } ]
7017         },
7018
7019         tweener: function( props, callback ) {
7020                 if ( jQuery.isFunction( props ) ) {
7021                         callback = props;
7022                         props = [ "*" ];
7023                 } else {
7024                         props = props.match( rnotwhite );
7025                 }
7026
7027                 var prop,
7028                         index = 0,
7029                         length = props.length;
7030
7031                 for ( ; index < length; index++ ) {
7032                         prop = props[ index ];
7033                         Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
7034                         Animation.tweeners[ prop ].unshift( callback );
7035                 }
7036         },
7037
7038         prefilters: [ defaultPrefilter ],
7039
7040         prefilter: function( callback, prepend ) {
7041                 if ( prepend ) {
7042                         Animation.prefilters.unshift( callback );
7043                 } else {
7044                         Animation.prefilters.push( callback );
7045                 }
7046         }
7047 } );
7048
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,
7053                 duration: speed,
7054                 easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
7055         };
7056
7057         // Go to the end state if fx are off or if document is hidden
7058         if ( jQuery.fx.off || document.hidden ) {
7059                 opt.duration = 0;
7060
7061         } else {
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;
7065         }
7066
7067         // Normalize opt.queue - true/undefined/null -> "fx"
7068         if ( opt.queue == null || opt.queue === true ) {
7069                 opt.queue = "fx";
7070         }
7071
7072         // Queueing
7073         opt.old = opt.complete;
7074
7075         opt.complete = function() {
7076                 if ( jQuery.isFunction( opt.old ) ) {
7077                         opt.old.call( this );
7078                 }
7079
7080                 if ( opt.queue ) {
7081                         jQuery.dequeue( this, opt.queue );
7082                 }
7083         };
7084
7085         return opt;
7086 };
7087
7088 jQuery.fn.extend( {
7089         fadeTo: function( speed, to, easing, callback ) {
7090
7091                 // Show any hidden elements after setting opacity to 0
7092                 return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show()
7093
7094                         // Animate to the value specified
7095                         .end().animate( { opacity: to }, speed, easing, callback );
7096         },
7097         animate: function( prop, speed, easing, callback ) {
7098                 var empty = jQuery.isEmptyObject( prop ),
7099                         optall = jQuery.speed( speed, easing, callback ),
7100                         doAnimation = function() {
7101
7102                                 // Operate on a copy of prop so per-property easing won't be lost
7103                                 var anim = Animation( this, jQuery.extend( {}, prop ), optall );
7104
7105                                 // Empty animations, or finishing resolves immediately
7106                                 if ( empty || dataPriv.get( this, "finish" ) ) {
7107                                         anim.stop( true );
7108                                 }
7109                         };
7110                         doAnimation.finish = doAnimation;
7111
7112                 return empty || optall.queue === false ?
7113                         this.each( doAnimation ) :
7114                         this.queue( optall.queue, doAnimation );
7115         },
7116         stop: function( type, clearQueue, gotoEnd ) {
7117                 var stopQueue = function( hooks ) {
7118                         var stop = hooks.stop;
7119                         delete hooks.stop;
7120                         stop( gotoEnd );
7121                 };
7122
7123                 if ( typeof type !== "string" ) {
7124                         gotoEnd = clearQueue;
7125                         clearQueue = type;
7126                         type = undefined;
7127                 }
7128                 if ( clearQueue && type !== false ) {
7129                         this.queue( type || "fx", [] );
7130                 }
7131
7132                 return this.each( function() {
7133                         var dequeue = true,
7134                                 index = type != null && type + "queueHooks",
7135                                 timers = jQuery.timers,
7136                                 data = dataPriv.get( this );
7137
7138                         if ( index ) {
7139                                 if ( data[ index ] && data[ index ].stop ) {
7140                                         stopQueue( data[ index ] );
7141                                 }
7142                         } else {
7143                                 for ( index in data ) {
7144                                         if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
7145                                                 stopQueue( data[ index ] );
7146                                         }
7147                                 }
7148                         }
7149
7150                         for ( index = timers.length; index--; ) {
7151                                 if ( timers[ index ].elem === this &&
7152                                         ( type == null || timers[ index ].queue === type ) ) {
7153
7154                                         timers[ index ].anim.stop( gotoEnd );
7155                                         dequeue = false;
7156                                         timers.splice( index, 1 );
7157                                 }
7158                         }
7159
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 );
7165                         }
7166                 } );
7167         },
7168         finish: function( type ) {
7169                 if ( type !== false ) {
7170                         type = type || "fx";
7171                 }
7172                 return this.each( function() {
7173                         var index,
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;
7179
7180                         // Enable finishing flag on private data
7181                         data.finish = true;
7182
7183                         // Empty the queue first
7184                         jQuery.queue( this, type, [] );
7185
7186                         if ( hooks && hooks.stop ) {
7187                                 hooks.stop.call( this, true );
7188                         }
7189
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 );
7195                                 }
7196                         }
7197
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 );
7202                                 }
7203                         }
7204
7205                         // Turn off finishing flag
7206                         delete data.finish;
7207                 } );
7208         }
7209 } );
7210
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 );
7217         };
7218 } );
7219
7220 // Generate shortcuts for custom animations
7221 jQuery.each( {
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 );
7231         };
7232 } );
7233
7234 jQuery.timers = [];
7235 jQuery.fx.tick = function() {
7236         var timer,
7237                 i = 0,
7238                 timers = jQuery.timers;
7239
7240         fxNow = jQuery.now();
7241
7242         for ( ; i < timers.length; i++ ) {
7243                 timer = timers[ i ];
7244
7245                 // Checks the timer has not already been removed
7246                 if ( !timer() && timers[ i ] === timer ) {
7247                         timers.splice( i--, 1 );
7248                 }
7249         }
7250
7251         if ( !timers.length ) {
7252                 jQuery.fx.stop();
7253         }
7254         fxNow = undefined;
7255 };
7256
7257 jQuery.fx.timer = function( timer ) {
7258         jQuery.timers.push( timer );
7259         if ( timer() ) {
7260                 jQuery.fx.start();
7261         } else {
7262                 jQuery.timers.pop();
7263         }
7264 };
7265
7266 jQuery.fx.interval = 13;
7267 jQuery.fx.start = function() {
7268         if ( !timerId ) {
7269                 timerId = window.requestAnimationFrame ?
7270                         window.requestAnimationFrame( raf ) :
7271                         window.setInterval( jQuery.fx.tick, jQuery.fx.interval );
7272         }
7273 };
7274
7275 jQuery.fx.stop = function() {
7276         if ( window.cancelAnimationFrame ) {
7277                 window.cancelAnimationFrame( timerId );
7278         } else {
7279                 window.clearInterval( timerId );
7280         }
7281
7282         timerId = null;
7283 };
7284
7285 jQuery.fx.speeds = {
7286         slow: 600,
7287         fast: 200,
7288
7289         // Default speed
7290         _default: 400
7291 };
7292
7293
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";
7299
7300         return this.queue( type, function( next, hooks ) {
7301                 var timeout = window.setTimeout( next, time );
7302                 hooks.stop = function() {
7303                         window.clearTimeout( timeout );
7304                 };
7305         } );
7306 };
7307
7308
7309 ( function() {
7310         var input = document.createElement( "input" ),
7311                 select = document.createElement( "select" ),
7312                 opt = select.appendChild( document.createElement( "option" ) );
7313
7314         input.type = "checkbox";
7315
7316         // Support: Android <=4.3 only
7317         // Default value for a checkbox should be "on"
7318         support.checkOn = input.value !== "";
7319
7320         // Support: IE <=11 only
7321         // Must access selectedIndex to make default options select
7322         support.optSelected = opt.selected;
7323
7324         // Support: IE <=11 only
7325         // An input loses its value after becoming a radio
7326         input = document.createElement( "input" );
7327         input.value = "t";
7328         input.type = "radio";
7329         support.radioValue = input.value === "t";
7330 } )();
7331
7332
7333 var boolHook,
7334         attrHandle = jQuery.expr.attrHandle;
7335
7336 jQuery.fn.extend( {
7337         attr: function( name, value ) {
7338                 return access( this, jQuery.attr, name, value, arguments.length > 1 );
7339         },
7340
7341         removeAttr: function( name ) {
7342                 return this.each( function() {
7343                         jQuery.removeAttr( this, name );
7344                 } );
7345         }
7346 } );
7347
7348 jQuery.extend( {
7349         attr: function( elem, name, value ) {
7350                 var ret, hooks,
7351                         nType = elem.nodeType;
7352
7353                 // Don't get/set attributes on text, comment and attribute nodes
7354                 if ( nType === 3 || nType === 8 || nType === 2 ) {
7355                         return;
7356                 }
7357
7358                 // Fallback to prop when attributes are not supported
7359                 if ( typeof elem.getAttribute === "undefined" ) {
7360                         return jQuery.prop( elem, name, value );
7361                 }
7362
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 );
7368                 }
7369
7370                 if ( value !== undefined ) {
7371                         if ( value === null ) {
7372                                 jQuery.removeAttr( elem, name );
7373                                 return;
7374                         }
7375
7376                         if ( hooks && "set" in hooks &&
7377                                 ( ret = hooks.set( elem, value, name ) ) !== undefined ) {
7378                                 return ret;
7379                         }
7380
7381                         elem.setAttribute( name, value + "" );
7382                         return value;
7383                 }
7384
7385                 if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
7386                         return ret;
7387                 }
7388
7389                 ret = jQuery.find.attr( elem, name );
7390
7391                 // Non-existent attributes return null, we normalize to undefined
7392                 return ret == null ? undefined : ret;
7393         },
7394
7395         attrHooks: {
7396                 type: {
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 );
7402                                         if ( val ) {
7403                                                 elem.value = val;
7404                                         }
7405                                         return value;
7406                                 }
7407                         }
7408                 }
7409         },
7410
7411         removeAttr: function( elem, value ) {
7412                 var name,
7413                         i = 0,
7414                         attrNames = value && value.match( rnotwhite );
7415
7416                 if ( attrNames && elem.nodeType === 1 ) {
7417                         while ( ( name = attrNames[ i++ ] ) ) {
7418                                 elem.removeAttribute( name );
7419                         }
7420                 }
7421         }
7422 } );
7423
7424 // Hooks for boolean attributes
7425 boolHook = {
7426         set: function( elem, value, name ) {
7427                 if ( value === false ) {
7428
7429                         // Remove boolean attributes when set to false
7430                         jQuery.removeAttr( elem, name );
7431                 } else {
7432                         elem.setAttribute( name, name );
7433                 }
7434                 return name;
7435         }
7436 };
7437
7438 jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
7439         var getter = attrHandle[ name ] || jQuery.find.attr;
7440
7441         attrHandle[ name ] = function( elem, name, isXML ) {
7442                 var ret, handle,
7443                         lowercaseName = name.toLowerCase();
7444
7445                 if ( !isXML ) {
7446
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 ?
7451                                 lowercaseName :
7452                                 null;
7453                         attrHandle[ lowercaseName ] = handle;
7454                 }
7455                 return ret;
7456         };
7457 } );
7458
7459
7460
7461
7462 var rfocusable = /^(?:input|select|textarea|button)$/i,
7463         rclickable = /^(?:a|area)$/i;
7464
7465 jQuery.fn.extend( {
7466         prop: function( name, value ) {
7467                 return access( this, jQuery.prop, name, value, arguments.length > 1 );
7468         },
7469
7470         removeProp: function( name ) {
7471                 return this.each( function() {
7472                         delete this[ jQuery.propFix[ name ] || name ];
7473                 } );
7474         }
7475 } );
7476
7477 jQuery.extend( {
7478         prop: function( elem, name, value ) {
7479                 var ret, hooks,
7480                         nType = elem.nodeType;
7481
7482                 // Don't get/set properties on text, comment and attribute nodes
7483                 if ( nType === 3 || nType === 8 || nType === 2 ) {
7484                         return;
7485                 }
7486
7487                 if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
7488
7489                         // Fix name and attach hooks
7490                         name = jQuery.propFix[ name ] || name;
7491                         hooks = jQuery.propHooks[ name ];
7492                 }
7493
7494                 if ( value !== undefined ) {
7495                         if ( hooks && "set" in hooks &&
7496                                 ( ret = hooks.set( elem, value, name ) ) !== undefined ) {
7497                                 return ret;
7498                         }
7499
7500                         return ( elem[ name ] = value );
7501                 }
7502
7503                 if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
7504                         return ret;
7505                 }
7506
7507                 return elem[ name ];
7508         },
7509
7510         propHooks: {
7511                 tabIndex: {
7512                         get: function( elem ) {
7513
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" );
7520
7521                                 return tabindex ?
7522                                         parseInt( tabindex, 10 ) :
7523                                         rfocusable.test( elem.nodeName ) ||
7524                                                 rclickable.test( elem.nodeName ) && elem.href ?
7525                                                         0 :
7526                                                         -1;
7527                         }
7528                 }
7529         },
7530
7531         propFix: {
7532                 "for": "htmlFor",
7533                 "class": "className"
7534         }
7535 } );
7536
7537 // Support: IE <=11 only
7538 // Accessing the selectedIndex property
7539 // forces the browser to respect setting selected
7540 // on the option
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;
7549                         }
7550                         return null;
7551                 },
7552                 set: function( elem ) {
7553                         var parent = elem.parentNode;
7554                         if ( parent ) {
7555                                 parent.selectedIndex;
7556
7557                                 if ( parent.parentNode ) {
7558                                         parent.parentNode.selectedIndex;
7559                                 }
7560                         }
7561                 }
7562         };
7563 }
7564
7565 jQuery.each( [
7566         "tabIndex",
7567         "readOnly",
7568         "maxLength",
7569         "cellSpacing",
7570         "cellPadding",
7571         "rowSpan",
7572         "colSpan",
7573         "useMap",
7574         "frameBorder",
7575         "contentEditable"
7576 ], function() {
7577         jQuery.propFix[ this.toLowerCase() ] = this;
7578 } );
7579
7580
7581
7582
7583 var rclass = /[\t\r\n\f]/g;
7584
7585 function getClass( elem ) {
7586         return elem.getAttribute && elem.getAttribute( "class" ) || "";
7587 }
7588
7589 jQuery.fn.extend( {
7590         addClass: function( value ) {
7591                 var classes, elem, cur, curValue, clazz, j, finalValue,
7592                         i = 0;
7593
7594                 if ( jQuery.isFunction( value ) ) {
7595                         return this.each( function( j ) {
7596                                 jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
7597                         } );
7598                 }
7599
7600                 if ( typeof value === "string" && value ) {
7601                         classes = value.match( rnotwhite ) || [];
7602
7603                         while ( ( elem = this[ i++ ] ) ) {
7604                                 curValue = getClass( elem );
7605                                 cur = elem.nodeType === 1 &&
7606                                         ( " " + curValue + " " ).replace( rclass, " " );
7607
7608                                 if ( cur ) {
7609                                         j = 0;
7610                                         while ( ( clazz = classes[ j++ ] ) ) {
7611                                                 if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
7612                                                         cur += clazz + " ";
7613                                                 }
7614                                         }
7615
7616                                         // Only assign if different to avoid unneeded rendering.
7617                                         finalValue = jQuery.trim( cur );
7618                                         if ( curValue !== finalValue ) {
7619                                                 elem.setAttribute( "class", finalValue );
7620                                         }
7621                                 }
7622                         }
7623                 }
7624
7625                 return this;
7626         },
7627
7628         removeClass: function( value ) {
7629                 var classes, elem, cur, curValue, clazz, j, finalValue,
7630                         i = 0;
7631
7632                 if ( jQuery.isFunction( value ) ) {
7633                         return this.each( function( j ) {
7634                                 jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
7635                         } );
7636                 }
7637
7638                 if ( !arguments.length ) {
7639                         return this.attr( "class", "" );
7640                 }
7641
7642                 if ( typeof value === "string" && value ) {
7643                         classes = value.match( rnotwhite ) || [];
7644
7645                         while ( ( elem = this[ i++ ] ) ) {
7646                                 curValue = getClass( elem );
7647
7648                                 // This expression is here for better compressibility (see addClass)
7649                                 cur = elem.nodeType === 1 &&
7650                                         ( " " + curValue + " " ).replace( rclass, " " );
7651
7652                                 if ( cur ) {
7653                                         j = 0;
7654                                         while ( ( clazz = classes[ j++ ] ) ) {
7655
7656                                                 // Remove *all* instances
7657                                                 while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
7658                                                         cur = cur.replace( " " + clazz + " ", " " );
7659                                                 }
7660                                         }
7661
7662                                         // Only assign if different to avoid unneeded rendering.
7663                                         finalValue = jQuery.trim( cur );
7664                                         if ( curValue !== finalValue ) {
7665                                                 elem.setAttribute( "class", finalValue );
7666                                         }
7667                                 }
7668                         }
7669                 }
7670
7671                 return this;
7672         },
7673
7674         toggleClass: function( value, stateVal ) {
7675                 var type = typeof value;
7676
7677                 if ( typeof stateVal === "boolean" && type === "string" ) {
7678                         return stateVal ? this.addClass( value ) : this.removeClass( value );
7679                 }
7680
7681                 if ( jQuery.isFunction( value ) ) {
7682                         return this.each( function( i ) {
7683                                 jQuery( this ).toggleClass(
7684                                         value.call( this, i, getClass( this ), stateVal ),
7685                                         stateVal
7686                                 );
7687                         } );
7688                 }
7689
7690                 return this.each( function() {
7691                         var className, i, self, classNames;
7692
7693                         if ( type === "string" ) {
7694
7695                                 // Toggle individual class names
7696                                 i = 0;
7697                                 self = jQuery( this );
7698                                 classNames = value.match( rnotwhite ) || [];
7699
7700                                 while ( ( className = classNames[ i++ ] ) ) {
7701
7702                                         // Check each className given, space separated list
7703                                         if ( self.hasClass( className ) ) {
7704                                                 self.removeClass( className );
7705                                         } else {
7706                                                 self.addClass( className );
7707                                         }
7708                                 }
7709
7710                         // Toggle whole class name
7711                         } else if ( value === undefined || type === "boolean" ) {
7712                                 className = getClass( this );
7713                                 if ( className ) {
7714
7715                                         // Store className if set
7716                                         dataPriv.set( this, "__className__", className );
7717                                 }
7718
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 ?
7726                                                 "" :
7727                                                 dataPriv.get( this, "__className__" ) || ""
7728                                         );
7729                                 }
7730                         }
7731                 } );
7732         },
7733
7734         hasClass: function( selector ) {
7735                 var className, elem,
7736                         i = 0;
7737
7738                 className = " " + selector + " ";
7739                 while ( ( elem = this[ i++ ] ) ) {
7740                         if ( elem.nodeType === 1 &&
7741                                 ( " " + getClass( elem ) + " " ).replace( rclass, " " )
7742                                         .indexOf( className ) > -1
7743                         ) {
7744                                 return true;
7745                         }
7746                 }
7747
7748                 return false;
7749         }
7750 } );
7751
7752
7753
7754
7755 var rreturn = /\r/g,
7756         rspaces = /[\x20\t\r\n\f]+/g;
7757
7758 jQuery.fn.extend( {
7759         val: function( value ) {
7760                 var hooks, ret, isFunction,
7761                         elem = this[ 0 ];
7762
7763                 if ( !arguments.length ) {
7764                         if ( elem ) {
7765                                 hooks = jQuery.valHooks[ elem.type ] ||
7766                                         jQuery.valHooks[ elem.nodeName.toLowerCase() ];
7767
7768                                 if ( hooks &&
7769                                         "get" in hooks &&
7770                                         ( ret = hooks.get( elem, "value" ) ) !== undefined
7771                                 ) {
7772                                         return ret;
7773                                 }
7774
7775                                 ret = elem.value;
7776
7777                                 return typeof ret === "string" ?
7778
7779                                         // Handle most common string cases
7780                                         ret.replace( rreturn, "" ) :
7781
7782                                         // Handle cases where value is null/undef or number
7783                                         ret == null ? "" : ret;
7784                         }
7785
7786                         return;
7787                 }
7788
7789                 isFunction = jQuery.isFunction( value );
7790
7791                 return this.each( function( i ) {
7792                         var val;
7793
7794                         if ( this.nodeType !== 1 ) {
7795                                 return;
7796                         }
7797
7798                         if ( isFunction ) {
7799                                 val = value.call( this, i, jQuery( this ).val() );
7800                         } else {
7801                                 val = value;
7802                         }
7803
7804                         // Treat null/undefined as ""; convert numbers to string
7805                         if ( val == null ) {
7806                                 val = "";
7807
7808                         } else if ( typeof val === "number" ) {
7809                                 val += "";
7810
7811                         } else if ( jQuery.isArray( val ) ) {
7812                                 val = jQuery.map( val, function( value ) {
7813                                         return value == null ? "" : value + "";
7814                                 } );
7815                         }
7816
7817                         hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
7818
7819                         // If set returns undefined, fall back to normal setting
7820                         if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
7821                                 this.value = val;
7822                         }
7823                 } );
7824         }
7825 } );
7826
7827 jQuery.extend( {
7828         valHooks: {
7829                 option: {
7830                         get: function( elem ) {
7831
7832                                 var val = jQuery.find.attr( elem, "value" );
7833                                 return val != null ?
7834                                         val :
7835
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, " " );
7841                         }
7842                 },
7843                 select: {
7844                         get: function( elem ) {
7845                                 var value, option,
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,
7851                                         i = index < 0 ?
7852                                                 max :
7853                                                 one ? index : 0;
7854
7855                                 // Loop through all the selected options
7856                                 for ( ; i < max; i++ ) {
7857                                         option = options[ i ];
7858
7859                                         // Support: IE <=9 only
7860                                         // IE8-9 doesn't update selected after form reset (#2551)
7861                                         if ( ( option.selected || i === index ) &&
7862
7863                                                         // Don't return options that are disabled or in a disabled optgroup
7864                                                         !option.disabled &&
7865                                                         ( !option.parentNode.disabled ||
7866                                                                 !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
7867
7868                                                 // Get the specific value for the option
7869                                                 value = jQuery( option ).val();
7870
7871                                                 // We don't need an array for one selects
7872                                                 if ( one ) {
7873                                                         return value;
7874                                                 }
7875
7876                                                 // Multi-Selects return an array
7877                                                 values.push( value );
7878                                         }
7879                                 }
7880
7881                                 return values;
7882                         },
7883
7884                         set: function( elem, value ) {
7885                                 var optionSet, option,
7886                                         options = elem.options,
7887                                         values = jQuery.makeArray( value ),
7888                                         i = options.length;
7889
7890                                 while ( i-- ) {
7891                                         option = options[ i ];
7892
7893                                         /* eslint-disable no-cond-assign */
7894
7895                                         if ( option.selected =
7896                                                 jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
7897                                         ) {
7898                                                 optionSet = true;
7899                                         }
7900
7901                                         /* eslint-enable no-cond-assign */
7902                                 }
7903
7904                                 // Force browsers to behave consistently when non-matching value is set
7905                                 if ( !optionSet ) {
7906                                         elem.selectedIndex = -1;
7907                                 }
7908                                 return values;
7909                         }
7910                 }
7911         }
7912 } );
7913
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 );
7920                         }
7921                 }
7922         };
7923         if ( !support.checkOn ) {
7924                 jQuery.valHooks[ this ].get = function( elem ) {
7925                         return elem.getAttribute( "value" ) === null ? "on" : elem.value;
7926                 };
7927         }
7928 } );
7929
7930
7931
7932
7933 // Return jQuery for attributes-only inclusion
7934
7935
7936 var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/;
7937
7938 jQuery.extend( jQuery.event, {
7939
7940         trigger: function( event, data, elem, onlyHandlers ) {
7941
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( "." ) : [];
7946
7947                 cur = tmp = elem = elem || document;
7948
7949                 // Don't do events on text and comment nodes
7950                 if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
7951                         return;
7952                 }
7953
7954                 // focus/blur morphs to focusin/out; ensure we're not firing them right now
7955                 if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
7956                         return;
7957                 }
7958
7959                 if ( type.indexOf( "." ) > -1 ) {
7960
7961                         // Namespaced trigger; create a regexp to match event type in handle()
7962                         namespaces = type.split( "." );
7963                         type = namespaces.shift();
7964                         namespaces.sort();
7965                 }
7966                 ontype = type.indexOf( ":" ) < 0 && "on" + type;
7967
7968                 // Caller can pass in a jQuery.Event object, Object, or just an event type string
7969                 event = event[ jQuery.expando ] ?
7970                         event :
7971                         new jQuery.Event( type, typeof event === "object" && event );
7972
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( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
7978                         null;
7979
7980                 // Clean up the event in case it is being reused
7981                 event.result = undefined;
7982                 if ( !event.target ) {
7983                         event.target = elem;
7984                 }
7985
7986                 // Clone any incoming data and prepend the event, creating the handler arg list
7987                 data = data == null ?
7988                         [ event ] :
7989                         jQuery.makeArray( data, [ event ] );
7990
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 ) {
7994                         return;
7995                 }
7996
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 ) ) {
8000
8001                         bubbleType = special.delegateType || type;
8002                         if ( !rfocusMorph.test( bubbleType + type ) ) {
8003                                 cur = cur.parentNode;
8004                         }
8005                         for ( ; cur; cur = cur.parentNode ) {
8006                                 eventPath.push( cur );
8007                                 tmp = cur;
8008                         }
8009
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 );
8013                         }
8014                 }
8015
8016                 // Fire handlers on the event path
8017                 i = 0;
8018                 while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
8019
8020                         event.type = i > 1 ?
8021                                 bubbleType :
8022                                 special.bindType || type;
8023
8024                         // jQuery handler
8025                         handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] &&
8026                                 dataPriv.get( cur, "handle" );
8027                         if ( handle ) {
8028                                 handle.apply( cur, data );
8029                         }
8030
8031                         // Native handler
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();
8037                                 }
8038                         }
8039                 }
8040                 event.type = type;
8041
8042                 // If nobody prevented the default action, do it now
8043                 if ( !onlyHandlers && !event.isDefaultPrevented() ) {
8044
8045                         if ( ( !special._default ||
8046                                 special._default.apply( eventPath.pop(), data ) === false ) &&
8047                                 acceptData( elem ) ) {
8048
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 ) ) {
8052
8053                                         // Don't re-trigger an onFOO event when we call its FOO() method
8054                                         tmp = elem[ ontype ];
8055
8056                                         if ( tmp ) {
8057                                                 elem[ ontype ] = null;
8058                                         }
8059
8060                                         // Prevent re-triggering of the same event, since we already bubbled it above
8061                                         jQuery.event.triggered = type;
8062                                         elem[ type ]();
8063                                         jQuery.event.triggered = undefined;
8064
8065                                         if ( tmp ) {
8066                                                 elem[ ontype ] = tmp;
8067                                         }
8068                                 }
8069                         }
8070                 }
8071
8072                 return event.result;
8073         },
8074
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(
8079                         new jQuery.Event(),
8080                         event,
8081                         {
8082                                 type: type,
8083                                 isSimulated: true
8084                         }
8085                 );
8086
8087                 jQuery.event.trigger( e, null, elem );
8088         }
8089
8090 } );
8091
8092 jQuery.fn.extend( {
8093
8094         trigger: function( type, data ) {
8095                 return this.each( function() {
8096                         jQuery.event.trigger( type, data, this );
8097                 } );
8098         },
8099         triggerHandler: function( type, data ) {
8100                 var elem = this[ 0 ];
8101                 if ( elem ) {
8102                         return jQuery.event.trigger( type, data, elem, true );
8103                 }
8104         }
8105 } );
8106
8107
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 ) {
8112
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 );
8118         };
8119 } );
8120
8121 jQuery.fn.extend( {
8122         hover: function( fnOver, fnOut ) {
8123                 return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
8124         }
8125 } );
8126
8127
8128
8129
8130 support.focusin = "onfocusin" in window;
8131
8132
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
8136 //
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 ) {
8143
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 ) );
8147                 };
8148
8149                 jQuery.event.special[ fix ] = {
8150                         setup: function() {
8151                                 var doc = this.ownerDocument || this,
8152                                         attaches = dataPriv.access( doc, fix );
8153
8154                                 if ( !attaches ) {
8155                                         doc.addEventListener( orig, handler, true );
8156                                 }
8157                                 dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
8158                         },
8159                         teardown: function() {
8160                                 var doc = this.ownerDocument || this,
8161                                         attaches = dataPriv.access( doc, fix ) - 1;
8162
8163                                 if ( !attaches ) {
8164                                         doc.removeEventListener( orig, handler, true );
8165                                         dataPriv.remove( doc, fix );
8166
8167                                 } else {
8168                                         dataPriv.access( doc, fix, attaches );
8169                                 }
8170                         }
8171                 };
8172         } );
8173 }
8174 var location = window.location;
8175
8176 var nonce = jQuery.now();
8177
8178 var rquery = ( /\?/ );
8179
8180
8181
8182 // Cross-browser xml parsing
8183 jQuery.parseXML = function( data ) {
8184         var xml;
8185         if ( !data || typeof data !== "string" ) {
8186                 return null;
8187         }
8188
8189         // Support: IE 9 - 11 only
8190         // IE throws on parseFromString with invalid input.
8191         try {
8192                 xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
8193         } catch ( e ) {
8194                 xml = undefined;
8195         }
8196
8197         if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
8198                 jQuery.error( "Invalid XML: " + data );
8199         }
8200         return xml;
8201 };
8202
8203
8204 var
8205         rbracket = /\[\]$/,
8206         rCRLF = /\r?\n/g,
8207         rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
8208         rsubmittable = /^(?:input|select|textarea|keygen)/i;
8209
8210 function buildParams( prefix, obj, traditional, add ) {
8211         var name;
8212
8213         if ( jQuery.isArray( obj ) ) {
8214
8215                 // Serialize array item.
8216                 jQuery.each( obj, function( i, v ) {
8217                         if ( traditional || rbracket.test( prefix ) ) {
8218
8219                                 // Treat each array item as a scalar.
8220                                 add( prefix, v );
8221
8222                         } else {
8223
8224                                 // Item is non-scalar (array or object), encode its numeric index.
8225                                 buildParams(
8226                                         prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
8227                                         v,
8228                                         traditional,
8229                                         add
8230                                 );
8231                         }
8232                 } );
8233
8234         } else if ( !traditional && jQuery.type( obj ) === "object" ) {
8235
8236                 // Serialize object item.
8237                 for ( name in obj ) {
8238                         buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
8239                 }
8240
8241         } else {
8242
8243                 // Serialize scalar item.
8244                 add( prefix, obj );
8245         }
8246 }
8247
8248 // Serialize an array of form elements or a set of
8249 // key/values into a query string
8250 jQuery.param = function( a, traditional ) {
8251         var prefix,
8252                 s = [],
8253                 add = function( key, valueOrFunction ) {
8254
8255                         // If value is a function, invoke it and use its return value
8256                         var value = jQuery.isFunction( valueOrFunction ) ?
8257                                 valueOrFunction() :
8258                                 valueOrFunction;
8259
8260                         s[ s.length ] = encodeURIComponent( key ) + "=" +
8261                                 encodeURIComponent( value == null ? "" : value );
8262                 };
8263
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 ) ) ) {
8266
8267                 // Serialize the form elements
8268                 jQuery.each( a, function() {
8269                         add( this.name, this.value );
8270                 } );
8271
8272         } else {
8273
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 );
8278                 }
8279         }
8280
8281         // Return the resulting serialization
8282         return s.join( "&" );
8283 };
8284
8285 jQuery.fn.extend( {
8286         serialize: function() {
8287                 return jQuery.param( this.serializeArray() );
8288         },
8289         serializeArray: function() {
8290                 return this.map( function() {
8291
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;
8295                 } )
8296                 .filter( function() {
8297                         var type = this.type;
8298
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 ) );
8303                 } )
8304                 .map( function( i, elem ) {
8305                         var val = jQuery( this ).val();
8306
8307                         return val == null ?
8308                                 null :
8309                                 jQuery.isArray( val ) ?
8310                                         jQuery.map( val, function( val ) {
8311                                                 return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
8312                                         } ) :
8313                                         { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
8314                 } ).get();
8315         }
8316 } );
8317
8318
8319 var
8320         r20 = /%20/g,
8321         rhash = /#.*$/,
8322         rts = /([?&])_=[^&]*/,
8323         rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
8324
8325         // #7653, #8125, #8152: local protocol detection
8326         rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
8327         rnoContent = /^(?:GET|HEAD)$/,
8328         rprotocol = /^\/\//,
8329
8330         /* Prefilters
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
8338          */
8339         prefilters = {},
8340
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
8345          */
8346         transports = {},
8347
8348         // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
8349         allTypes = "*/".concat( "*" ),
8350
8351         // Anchor tag for parsing the document origin
8352         originAnchor = document.createElement( "a" );
8353         originAnchor.href = location.href;
8354
8355 // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
8356 function addToPrefiltersOrTransports( structure ) {
8357
8358         // dataTypeExpression is optional and defaults to "*"
8359         return function( dataTypeExpression, func ) {
8360
8361                 if ( typeof dataTypeExpression !== "string" ) {
8362                         func = dataTypeExpression;
8363                         dataTypeExpression = "*";
8364                 }
8365
8366                 var dataType,
8367                         i = 0,
8368                         dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
8369
8370                 if ( jQuery.isFunction( func ) ) {
8371
8372                         // For each dataType in the dataTypeExpression
8373                         while ( ( dataType = dataTypes[ i++ ] ) ) {
8374
8375                                 // Prepend if requested
8376                                 if ( dataType[ 0 ] === "+" ) {
8377                                         dataType = dataType.slice( 1 ) || "*";
8378                                         ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );
8379
8380                                 // Otherwise append
8381                                 } else {
8382                                         ( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
8383                                 }
8384                         }
8385                 }
8386         };
8387 }
8388
8389 // Base inspection function for prefilters and transports
8390 function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
8391
8392         var inspected = {},
8393                 seekingTransport = ( structure === transports );
8394
8395         function inspect( dataType ) {
8396                 var selected;
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 ] ) {
8402
8403                                 options.dataTypes.unshift( dataTypeOrTransport );
8404                                 inspect( dataTypeOrTransport );
8405                                 return false;
8406                         } else if ( seekingTransport ) {
8407                                 return !( selected = dataTypeOrTransport );
8408                         }
8409                 } );
8410                 return selected;
8411         }
8412
8413         return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
8414 }
8415
8416 // A special extend for ajax options
8417 // that takes "flat" options (not to be deep extended)
8418 // Fixes #9887
8419 function ajaxExtend( target, src ) {
8420         var key, deep,
8421                 flatOptions = jQuery.ajaxSettings.flatOptions || {};
8422
8423         for ( key in src ) {
8424                 if ( src[ key ] !== undefined ) {
8425                         ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
8426                 }
8427         }
8428         if ( deep ) {
8429                 jQuery.extend( true, target, deep );
8430         }
8431
8432         return target;
8433 }
8434
8435 /* Handles responses to an ajax request:
8436  * - finds the right dataType (mediates between content-type and expected dataType)
8437  * - returns the corresponding response
8438  */
8439 function ajaxHandleResponses( s, jqXHR, responses ) {
8440
8441         var ct, type, finalDataType, firstDataType,
8442                 contents = s.contents,
8443                 dataTypes = s.dataTypes;
8444
8445         // Remove auto dataType and get content-type in the process
8446         while ( dataTypes[ 0 ] === "*" ) {
8447                 dataTypes.shift();
8448                 if ( ct === undefined ) {
8449                         ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
8450                 }
8451         }
8452
8453         // Check if we're dealing with a known content-type
8454         if ( ct ) {
8455                 for ( type in contents ) {
8456                         if ( contents[ type ] && contents[ type ].test( ct ) ) {
8457                                 dataTypes.unshift( type );
8458                                 break;
8459                         }
8460                 }
8461         }
8462
8463         // Check to see if we have a response for the expected dataType
8464         if ( dataTypes[ 0 ] in responses ) {
8465                 finalDataType = dataTypes[ 0 ];
8466         } else {
8467
8468                 // Try convertible dataTypes
8469                 for ( type in responses ) {
8470                         if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
8471                                 finalDataType = type;
8472                                 break;
8473                         }
8474                         if ( !firstDataType ) {
8475                                 firstDataType = type;
8476                         }
8477                 }
8478
8479                 // Or just use first one
8480                 finalDataType = finalDataType || firstDataType;
8481         }
8482
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 );
8489                 }
8490                 return responses[ finalDataType ];
8491         }
8492 }
8493
8494 /* Chain conversions given the request and the original response
8495  * Also sets the responseXXX fields on the jqXHR instance
8496  */
8497 function ajaxConvert( s, response, jqXHR, isSuccess ) {
8498         var conv2, current, conv, tmp, prev,
8499                 converters = {},
8500
8501                 // Work with a copy of dataTypes in case we need to modify it for conversion
8502                 dataTypes = s.dataTypes.slice();
8503
8504         // Create converters map with lowercased keys
8505         if ( dataTypes[ 1 ] ) {
8506                 for ( conv in s.converters ) {
8507                         converters[ conv.toLowerCase() ] = s.converters[ conv ];
8508                 }
8509         }
8510
8511         current = dataTypes.shift();
8512
8513         // Convert to each sequential dataType
8514         while ( current ) {
8515
8516                 if ( s.responseFields[ current ] ) {
8517                         jqXHR[ s.responseFields[ current ] ] = response;
8518                 }
8519
8520                 // Apply the dataFilter if provided
8521                 if ( !prev && isSuccess && s.dataFilter ) {
8522                         response = s.dataFilter( response, s.dataType );
8523                 }
8524
8525                 prev = current;
8526                 current = dataTypes.shift();
8527
8528                 if ( current ) {
8529
8530                         // There's only work to do if current dataType is non-auto
8531                         if ( current === "*" ) {
8532
8533                                 current = prev;
8534
8535                         // Convert response if prev dataType is non-auto and differs from current
8536                         } else if ( prev !== "*" && prev !== current ) {
8537
8538                                 // Seek a direct converter
8539                                 conv = converters[ prev + " " + current ] || converters[ "* " + current ];
8540
8541                                 // If none found, seek a pair
8542                                 if ( !conv ) {
8543                                         for ( conv2 in converters ) {
8544
8545                                                 // If conv2 outputs current
8546                                                 tmp = conv2.split( " " );
8547                                                 if ( tmp[ 1 ] === current ) {
8548
8549                                                         // If prev can be converted to accepted input
8550                                                         conv = converters[ prev + " " + tmp[ 0 ] ] ||
8551                                                                 converters[ "* " + tmp[ 0 ] ];
8552                                                         if ( conv ) {
8553
8554                                                                 // Condense equivalence converters
8555                                                                 if ( conv === true ) {
8556                                                                         conv = converters[ conv2 ];
8557
8558                                                                 // Otherwise, insert the intermediate dataType
8559                                                                 } else if ( converters[ conv2 ] !== true ) {
8560                                                                         current = tmp[ 0 ];
8561                                                                         dataTypes.unshift( tmp[ 1 ] );
8562                                                                 }
8563                                                                 break;
8564                                                         }
8565                                                 }
8566                                         }
8567                                 }
8568
8569                                 // Apply converter (if not an equivalence)
8570                                 if ( conv !== true ) {
8571
8572                                         // Unless errors are allowed to bubble, catch and return them
8573                                         if ( conv && s.throws ) {
8574                                                 response = conv( response );
8575                                         } else {
8576                                                 try {
8577                                                         response = conv( response );
8578                                                 } catch ( e ) {
8579                                                         return {
8580                                                                 state: "parsererror",
8581                                                                 error: conv ? e : "No conversion from " + prev + " to " + current
8582                                                         };
8583                                                 }
8584                                         }
8585                                 }
8586                         }
8587                 }
8588         }
8589
8590         return { state: "success", data: response };
8591 }
8592
8593 jQuery.extend( {
8594
8595         // Counter for holding the number of active queries
8596         active: 0,
8597
8598         // Last-Modified header cache for next request
8599         lastModified: {},
8600         etag: {},
8601
8602         ajaxSettings: {
8603                 url: location.href,
8604                 type: "GET",
8605                 isLocal: rlocalProtocol.test( location.protocol ),
8606                 global: true,
8607                 processData: true,
8608                 async: true,
8609                 contentType: "application/x-www-form-urlencoded; charset=UTF-8",
8610
8611                 /*
8612                 timeout: 0,
8613                 data: null,
8614                 dataType: null,
8615                 username: null,
8616                 password: null,
8617                 cache: null,
8618                 throws: false,
8619                 traditional: false,
8620                 headers: {},
8621                 */
8622
8623                 accepts: {
8624                         "*": allTypes,
8625                         text: "text/plain",
8626                         html: "text/html",
8627                         xml: "application/xml, text/xml",
8628                         json: "application/json, text/javascript"
8629                 },
8630
8631                 contents: {
8632                         xml: /\bxml\b/,
8633                         html: /\bhtml/,
8634                         json: /\bjson\b/
8635                 },
8636
8637                 responseFields: {
8638                         xml: "responseXML",
8639                         text: "responseText",
8640                         json: "responseJSON"
8641                 },
8642
8643                 // Data converters
8644                 // Keys separate source (or catchall "*") and destination types with a single space
8645                 converters: {
8646
8647                         // Convert anything to text
8648                         "* text": String,
8649
8650                         // Text to html (true = no transformation)
8651                         "text html": true,
8652
8653                         // Evaluate text as a json expression
8654                         "text json": JSON.parse,
8655
8656                         // Parse text as xml
8657                         "text xml": jQuery.parseXML
8658                 },
8659
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)
8664                 flatOptions: {
8665                         url: true,
8666                         context: true
8667                 }
8668         },
8669
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 ) {
8674                 return settings ?
8675
8676                         // Building a settings object
8677                         ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
8678
8679                         // Extending ajaxSettings
8680                         ajaxExtend( jQuery.ajaxSettings, target );
8681         },
8682
8683         ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
8684         ajaxTransport: addToPrefiltersOrTransports( transports ),
8685
8686         // Main method
8687         ajax: function( url, options ) {
8688
8689                 // If url is an object, simulate pre-1.5 signature
8690                 if ( typeof url === "object" ) {
8691                         options = url;
8692                         url = undefined;
8693                 }
8694
8695                 // Force options to be an object
8696                 options = options || {};
8697
8698                 var transport,
8699
8700                         // URL without anti-cache param
8701                         cacheURL,
8702
8703                         // Response headers
8704                         responseHeadersString,
8705                         responseHeaders,
8706
8707                         // timeout handle
8708                         timeoutTimer,
8709
8710                         // Url cleanup var
8711                         urlAnchor,
8712
8713                         // Request state (becomes false upon send and true upon completion)
8714                         completed,
8715
8716                         // To know if global events are to be dispatched
8717                         fireGlobals,
8718
8719                         // Loop variable
8720                         i,
8721
8722                         // uncached part of the url
8723                         uncached,
8724
8725                         // Create the final options object
8726                         s = jQuery.ajaxSetup( {}, options ),
8727
8728                         // Callbacks context
8729                         callbackContext = s.context || s,
8730
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 ) :
8735                                         jQuery.event,
8736
8737                         // Deferreds
8738                         deferred = jQuery.Deferred(),
8739                         completeDeferred = jQuery.Callbacks( "once memory" ),
8740
8741                         // Status-dependent callbacks
8742                         statusCode = s.statusCode || {},
8743
8744                         // Headers (they are sent all at once)
8745                         requestHeaders = {},
8746                         requestHeadersNames = {},
8747
8748                         // Default abort message
8749                         strAbort = "canceled",
8750
8751                         // Fake xhr
8752                         jqXHR = {
8753                                 readyState: 0,
8754
8755                                 // Builds headers hashtable if needed
8756                                 getResponseHeader: function( key ) {
8757                                         var match;
8758                                         if ( completed ) {
8759                                                 if ( !responseHeaders ) {
8760                                                         responseHeaders = {};
8761                                                         while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
8762                                                                 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
8763                                                         }
8764                                                 }
8765                                                 match = responseHeaders[ key.toLowerCase() ];
8766                                         }
8767                                         return match == null ? null : match;
8768                                 },
8769
8770                                 // Raw string
8771                                 getAllResponseHeaders: function() {
8772                                         return completed ? responseHeadersString : null;
8773                                 },
8774
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;
8781                                         }
8782                                         return this;
8783                                 },
8784
8785                                 // Overrides response content-type header
8786                                 overrideMimeType: function( type ) {
8787                                         if ( completed == null ) {
8788                                                 s.mimeType = type;
8789                                         }
8790                                         return this;
8791                                 },
8792
8793                                 // Status-dependent callbacks
8794                                 statusCode: function( map ) {
8795                                         var code;
8796                                         if ( map ) {
8797                                                 if ( completed ) {
8798
8799                                                         // Execute the appropriate callbacks
8800                                                         jqXHR.always( map[ jqXHR.status ] );
8801                                                 } else {
8802
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 ] ];
8806                                                         }
8807                                                 }
8808                                         }
8809                                         return this;
8810                                 },
8811
8812                                 // Cancel the request
8813                                 abort: function( statusText ) {
8814                                         var finalText = statusText || strAbort;
8815                                         if ( transport ) {
8816                                                 transport.abort( finalText );
8817                                         }
8818                                         done( 0, finalText );
8819                                         return this;
8820                                 }
8821                         };
8822
8823                 // Attach deferreds
8824                 deferred.promise( jqXHR );
8825
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 + "//" );
8831
8832                 // Alias method option to type as per ticket #12004
8833                 s.type = options.method || options.type || s.method || s.type;
8834
8835                 // Extract dataTypes list
8836                 s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
8837
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" );
8841
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/
8845                         try {
8846                                 urlAnchor.href = s.url;
8847
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;
8853                         } catch ( e ) {
8854
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;
8858                         }
8859                 }
8860
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 );
8864                 }
8865
8866                 // Apply prefilters
8867                 inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
8868
8869                 // If request was aborted inside a prefilter, stop there
8870                 if ( completed ) {
8871                         return jqXHR;
8872                 }
8873
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;
8877
8878                 // Watch for a new set of requests
8879                 if ( fireGlobals && jQuery.active++ === 0 ) {
8880                         jQuery.event.trigger( "ajaxStart" );
8881                 }
8882
8883                 // Uppercase the type
8884                 s.type = s.type.toUpperCase();
8885
8886                 // Determine if request has content
8887                 s.hasContent = !rnoContent.test( s.type );
8888
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, "" );
8893
8894                 // More options handling for requests with no content
8895                 if ( !s.hasContent ) {
8896
8897                         // Remember the hash so we can put it back
8898                         uncached = s.url.slice( cacheURL.length );
8899
8900                         // If data is available, append data to url
8901                         if ( s.data ) {
8902                                 cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;
8903
8904                                 // #9682: remove data so that it's not used in an eventual retry
8905                                 delete s.data;
8906                         }
8907
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;
8912                         }
8913
8914                         // Put hash and anti-cache on the URL that will be requested (gh-1732)
8915                         s.url = cacheURL + uncached;
8916
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, "+" );
8921                 }
8922
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 ] );
8927                         }
8928                         if ( jQuery.etag[ cacheURL ] ) {
8929                                 jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
8930                         }
8931                 }
8932
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 );
8936                 }
8937
8938                 // Set the Accepts header for the server, depending on the dataType
8939                 jqXHR.setRequestHeader(
8940                         "Accept",
8941                         s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
8942                                 s.accepts[ s.dataTypes[ 0 ] ] +
8943                                         ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
8944                                 s.accepts[ "*" ]
8945                 );
8946
8947                 // Check for headers option
8948                 for ( i in s.headers ) {
8949                         jqXHR.setRequestHeader( i, s.headers[ i ] );
8950                 }
8951
8952                 // Allow custom headers/mimetypes and early abort
8953                 if ( s.beforeSend &&
8954                         ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) {
8955
8956                         // Abort if not done already and return
8957                         return jqXHR.abort();
8958                 }
8959
8960                 // Aborting is no longer a cancellation
8961                 strAbort = "abort";
8962
8963                 // Install callbacks on deferreds
8964                 completeDeferred.add( s.complete );
8965                 jqXHR.done( s.success );
8966                 jqXHR.fail( s.error );
8967
8968                 // Get transport
8969                 transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
8970
8971                 // If no transport, we auto-abort
8972                 if ( !transport ) {
8973                         done( -1, "No Transport" );
8974                 } else {
8975                         jqXHR.readyState = 1;
8976
8977                         // Send global event
8978                         if ( fireGlobals ) {
8979                                 globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
8980                         }
8981
8982                         // If request was aborted inside ajaxSend, stop there
8983                         if ( completed ) {
8984                                 return jqXHR;
8985                         }
8986
8987                         // Timeout
8988                         if ( s.async && s.timeout > 0 ) {
8989                                 timeoutTimer = window.setTimeout( function() {
8990                                         jqXHR.abort( "timeout" );
8991                                 }, s.timeout );
8992                         }
8993
8994                         try {
8995                                 completed = false;
8996                                 transport.send( requestHeaders, done );
8997                         } catch ( e ) {
8998
8999                                 // Rethrow post-completion exceptions
9000                                 if ( completed ) {
9001                                         throw e;
9002                                 }
9003
9004                                 // Propagate others as results
9005                                 done( -1, e );
9006                         }
9007                 }
9008
9009                 // Callback for when everything is done
9010                 function done( status, nativeStatusText, responses, headers ) {
9011                         var isSuccess, success, error, response, modified,
9012                                 statusText = nativeStatusText;
9013
9014                         // Ignore repeat invocations
9015                         if ( completed ) {
9016                                 return;
9017                         }
9018
9019                         completed = true;
9020
9021                         // Clear timeout if it exists
9022                         if ( timeoutTimer ) {
9023                                 window.clearTimeout( timeoutTimer );
9024                         }
9025
9026                         // Dereference transport for early garbage collection
9027                         // (no matter how long the jqXHR object will be used)
9028                         transport = undefined;
9029
9030                         // Cache response headers
9031                         responseHeadersString = headers || "";
9032
9033                         // Set readyState
9034                         jqXHR.readyState = status > 0 ? 4 : 0;
9035
9036                         // Determine if successful
9037                         isSuccess = status >= 200 && status < 300 || status === 304;
9038
9039                         // Get response data
9040                         if ( responses ) {
9041                                 response = ajaxHandleResponses( s, jqXHR, responses );
9042                         }
9043
9044                         // Convert no matter what (that way responseXXX fields are always set)
9045                         response = ajaxConvert( s, response, jqXHR, isSuccess );
9046
9047                         // If successful, handle type chaining
9048                         if ( isSuccess ) {
9049
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" );
9053                                         if ( modified ) {
9054                                                 jQuery.lastModified[ cacheURL ] = modified;
9055                                         }
9056                                         modified = jqXHR.getResponseHeader( "etag" );
9057                                         if ( modified ) {
9058                                                 jQuery.etag[ cacheURL ] = modified;
9059                                         }
9060                                 }
9061
9062                                 // if no content
9063                                 if ( status === 204 || s.type === "HEAD" ) {
9064                                         statusText = "nocontent";
9065
9066                                 // if not modified
9067                                 } else if ( status === 304 ) {
9068                                         statusText = "notmodified";
9069
9070                                 // If we have data, let's convert it
9071                                 } else {
9072                                         statusText = response.state;
9073                                         success = response.data;
9074                                         error = response.error;
9075                                         isSuccess = !error;
9076                                 }
9077                         } else {
9078
9079                                 // Extract error from statusText and normalize for non-aborts
9080                                 error = statusText;
9081                                 if ( status || !statusText ) {
9082                                         statusText = "error";
9083                                         if ( status < 0 ) {
9084                                                 status = 0;
9085                                         }
9086                                 }
9087                         }
9088
9089                         // Set data for the fake xhr object
9090                         jqXHR.status = status;
9091                         jqXHR.statusText = ( nativeStatusText || statusText ) + "";
9092
9093                         // Success/Error
9094                         if ( isSuccess ) {
9095                                 deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
9096                         } else {
9097                                 deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
9098                         }
9099
9100                         // Status-dependent callbacks
9101                         jqXHR.statusCode( statusCode );
9102                         statusCode = undefined;
9103
9104                         if ( fireGlobals ) {
9105                                 globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
9106                                         [ jqXHR, s, isSuccess ? success : error ] );
9107                         }
9108
9109                         // Complete
9110                         completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
9111
9112                         if ( fireGlobals ) {
9113                                 globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
9114
9115                                 // Handle the global AJAX counter
9116                                 if ( !( --jQuery.active ) ) {
9117                                         jQuery.event.trigger( "ajaxStop" );
9118                                 }
9119                         }
9120                 }
9121
9122                 return jqXHR;
9123         },
9124
9125         getJSON: function( url, data, callback ) {
9126                 return jQuery.get( url, data, callback, "json" );
9127         },
9128
9129         getScript: function( url, callback ) {
9130                 return jQuery.get( url, undefined, callback, "script" );
9131         }
9132 } );
9133
9134 jQuery.each( [ "get", "post" ], function( i, method ) {
9135         jQuery[ method ] = function( url, data, callback, type ) {
9136
9137                 // Shift arguments if data argument was omitted
9138                 if ( jQuery.isFunction( data ) ) {
9139                         type = type || callback;
9140                         callback = data;
9141                         data = undefined;
9142                 }
9143
9144                 // The url can be an options object (which then must have .url)
9145                 return jQuery.ajax( jQuery.extend( {
9146                         url: url,
9147                         type: method,
9148                         dataType: type,
9149                         data: data,
9150                         success: callback
9151                 }, jQuery.isPlainObject( url ) && url ) );
9152         };
9153 } );
9154
9155
9156 jQuery._evalUrl = function( url ) {
9157         return jQuery.ajax( {
9158                 url: url,
9159
9160                 // Make this explicit, since user can override this through ajaxSetup (#11264)
9161                 type: "GET",
9162                 dataType: "script",
9163                 cache: true,
9164                 async: false,
9165                 global: false,
9166                 "throws": true
9167         } );
9168 };
9169
9170
9171 jQuery.fn.extend( {
9172         wrapAll: function( html ) {
9173                 var wrap;
9174
9175                 if ( this[ 0 ] ) {
9176                         if ( jQuery.isFunction( html ) ) {
9177                                 html = html.call( this[ 0 ] );
9178                         }
9179
9180                         // The elements to wrap the target around
9181                         wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
9182
9183                         if ( this[ 0 ].parentNode ) {
9184                                 wrap.insertBefore( this[ 0 ] );
9185                         }
9186
9187                         wrap.map( function() {
9188                                 var elem = this;
9189
9190                                 while ( elem.firstElementChild ) {
9191                                         elem = elem.firstElementChild;
9192                                 }
9193
9194                                 return elem;
9195                         } ).append( this );
9196                 }
9197
9198                 return this;
9199         },
9200
9201         wrapInner: function( html ) {
9202                 if ( jQuery.isFunction( html ) ) {
9203                         return this.each( function( i ) {
9204                                 jQuery( this ).wrapInner( html.call( this, i ) );
9205                         } );
9206                 }
9207
9208                 return this.each( function() {
9209                         var self = jQuery( this ),
9210                                 contents = self.contents();
9211
9212                         if ( contents.length ) {
9213                                 contents.wrapAll( html );
9214
9215                         } else {
9216                                 self.append( html );
9217                         }
9218                 } );
9219         },
9220
9221         wrap: function( html ) {
9222                 var isFunction = jQuery.isFunction( html );
9223
9224                 return this.each( function( i ) {
9225                         jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html );
9226                 } );
9227         },
9228
9229         unwrap: function( selector ) {
9230                 this.parent( selector ).not( "body" ).each( function() {
9231                         jQuery( this ).replaceWith( this.childNodes );
9232                 } );
9233                 return this;
9234         }
9235 } );
9236
9237
9238 jQuery.expr.pseudos.hidden = function( elem ) {
9239         return !jQuery.expr.pseudos.visible( elem );
9240 };
9241 jQuery.expr.pseudos.visible = function( elem ) {
9242         return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
9243 };
9244
9245
9246
9247
9248 jQuery.ajaxSettings.xhr = function() {
9249         try {
9250                 return new window.XMLHttpRequest();
9251         } catch ( e ) {}
9252 };
9253
9254 var xhrSuccessStatus = {
9255
9256                 // File protocol always yields status code 0, assume 200
9257                 0: 200,
9258
9259                 // Support: IE <=9 only
9260                 // #1450: sometimes IE returns 1223 when it should be 204
9261                 1223: 204
9262         },
9263         xhrSupported = jQuery.ajaxSettings.xhr();
9264
9265 support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
9266 support.ajax = xhrSupported = !!xhrSupported;
9267
9268 jQuery.ajaxTransport( function( options ) {
9269         var callback, errorCallback;
9270
9271         // Cross domain only allowed if supported through XMLHttpRequest
9272         if ( support.cors || xhrSupported && !options.crossDomain ) {
9273                 return {
9274                         send: function( headers, complete ) {
9275                                 var i,
9276                                         xhr = options.xhr();
9277
9278                                 xhr.open(
9279                                         options.type,
9280                                         options.url,
9281                                         options.async,
9282                                         options.username,
9283                                         options.password
9284                                 );
9285
9286                                 // Apply custom fields if provided
9287                                 if ( options.xhrFields ) {
9288                                         for ( i in options.xhrFields ) {
9289                                                 xhr[ i ] = options.xhrFields[ i ];
9290                                         }
9291                                 }
9292
9293                                 // Override mime type if needed
9294                                 if ( options.mimeType && xhr.overrideMimeType ) {
9295                                         xhr.overrideMimeType( options.mimeType );
9296                                 }
9297
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";
9305                                 }
9306
9307                                 // Set headers
9308                                 for ( i in headers ) {
9309                                         xhr.setRequestHeader( i, headers[ i ] );
9310                                 }
9311
9312                                 // Callback
9313                                 callback = function( type ) {
9314                                         return function() {
9315                                                 if ( callback ) {
9316                                                         callback = errorCallback = xhr.onload =
9317                                                                 xhr.onerror = xhr.onabort = xhr.onreadystatechange = null;
9318
9319                                                         if ( type === "abort" ) {
9320                                                                 xhr.abort();
9321                                                         } else if ( type === "error" ) {
9322
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" );
9328                                                                 } else {
9329                                                                         complete(
9330
9331                                                                                 // File: protocol always yields status 0; see #8605, #14207
9332                                                                                 xhr.status,
9333                                                                                 xhr.statusText
9334                                                                         );
9335                                                                 }
9336                                                         } else {
9337                                                                 complete(
9338                                                                         xhrSuccessStatus[ xhr.status ] || xhr.status,
9339                                                                         xhr.statusText,
9340
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()
9349                                                                 );
9350                                                         }
9351                                                 }
9352                                         };
9353                                 };
9354
9355                                 // Listen to events
9356                                 xhr.onload = callback();
9357                                 errorCallback = xhr.onerror = callback( "error" );
9358
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;
9364                                 } else {
9365                                         xhr.onreadystatechange = function() {
9366
9367                                                 // Check readyState before timeout as it changes
9368                                                 if ( xhr.readyState === 4 ) {
9369
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() {
9375                                                                 if ( callback ) {
9376                                                                         errorCallback();
9377                                                                 }
9378                                                         } );
9379                                                 }
9380                                         };
9381                                 }
9382
9383                                 // Create the abort callback
9384                                 callback = callback( "abort" );
9385
9386                                 try {
9387
9388                                         // Do send the request (this may raise an exception)
9389                                         xhr.send( options.hasContent && options.data || null );
9390                                 } catch ( e ) {
9391
9392                                         // #14683: Only rethrow if this hasn't been notified as an error yet
9393                                         if ( callback ) {
9394                                                 throw e;
9395                                         }
9396                                 }
9397                         },
9398
9399                         abort: function() {
9400                                 if ( callback ) {
9401                                         callback();
9402                                 }
9403                         }
9404                 };
9405         }
9406 } );
9407
9408
9409
9410
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;
9415         }
9416 } );
9417
9418 // Install script dataType
9419 jQuery.ajaxSetup( {
9420         accepts: {
9421                 script: "text/javascript, application/javascript, " +
9422                         "application/ecmascript, application/x-ecmascript"
9423         },
9424         contents: {
9425                 script: /\b(?:java|ecma)script\b/
9426         },
9427         converters: {
9428                 "text script": function( text ) {
9429                         jQuery.globalEval( text );
9430                         return text;
9431                 }
9432         }
9433 } );
9434
9435 // Handle cache's special case and crossDomain
9436 jQuery.ajaxPrefilter( "script", function( s ) {
9437         if ( s.cache === undefined ) {
9438                 s.cache = false;
9439         }
9440         if ( s.crossDomain ) {
9441                 s.type = "GET";
9442         }
9443 } );
9444
9445 // Bind script tag hack transport
9446 jQuery.ajaxTransport( "script", function( s ) {
9447
9448         // This transport only deals with cross domain requests
9449         if ( s.crossDomain ) {
9450                 var script, callback;
9451                 return {
9452                         send: function( _, complete ) {
9453                                 script = jQuery( "<script>" ).prop( {
9454                                         charset: s.scriptCharset,
9455                                         src: s.url
9456                                 } ).on(
9457                                         "load error",
9458                                         callback = function( evt ) {
9459                                                 script.remove();
9460                                                 callback = null;
9461                                                 if ( evt ) {
9462                                                         complete( evt.type === "error" ? 404 : 200, evt.type );
9463                                                 }
9464                                         }
9465                                 );
9466
9467                                 // Use native DOM manipulation to avoid our domManip AJAX trickery
9468                                 document.head.appendChild( script[ 0 ] );
9469                         },
9470                         abort: function() {
9471                                 if ( callback ) {
9472                                         callback();
9473                                 }
9474                         }
9475                 };
9476         }
9477 } );
9478
9479
9480
9481
9482 var oldCallbacks = [],
9483         rjsonp = /(=)\?(?=&|$)|\?\?/;
9484
9485 // Default jsonp settings
9486 jQuery.ajaxSetup( {
9487         jsonp: "callback",
9488         jsonpCallback: function() {
9489                 var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
9490                 this[ callback ] = true;
9491                 return callback;
9492         }
9493 } );
9494
9495 // Detect, normalize options and install callbacks for jsonp requests
9496 jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
9497
9498         var callbackName, overwritten, responseContainer,
9499                 jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
9500                         "url" :
9501                         typeof s.data === "string" &&
9502                                 ( s.contentType || "" )
9503                                         .indexOf( "application/x-www-form-urlencoded" ) === 0 &&
9504                                 rjsonp.test( s.data ) && "data"
9505                 );
9506
9507         // Handle iff the expected data type is "jsonp" or we have a parameter to set
9508         if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
9509
9510                 // Get callback name, remembering preexisting value associated with it
9511                 callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
9512                         s.jsonpCallback() :
9513                         s.jsonpCallback;
9514
9515                 // Insert callback into url or form data
9516                 if ( jsonProp ) {
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;
9520                 }
9521
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" );
9526                         }
9527                         return responseContainer[ 0 ];
9528                 };
9529
9530                 // Force json dataType
9531                 s.dataTypes[ 0 ] = "json";
9532
9533                 // Install callback
9534                 overwritten = window[ callbackName ];
9535                 window[ callbackName ] = function() {
9536                         responseContainer = arguments;
9537                 };
9538
9539                 // Clean-up function (fires after converters)
9540                 jqXHR.always( function() {
9541
9542                         // If previous value didn't exist - remove it
9543                         if ( overwritten === undefined ) {
9544                                 jQuery( window ).removeProp( callbackName );
9545
9546                         // Otherwise restore preexisting value
9547                         } else {
9548                                 window[ callbackName ] = overwritten;
9549                         }
9550
9551                         // Save back as free
9552                         if ( s[ callbackName ] ) {
9553
9554                                 // Make sure that re-using the options doesn't screw things around
9555                                 s.jsonpCallback = originalSettings.jsonpCallback;
9556
9557                                 // Save the callback name for future use
9558                                 oldCallbacks.push( callbackName );
9559                         }
9560
9561                         // Call if it was a function and we have a response
9562                         if ( responseContainer && jQuery.isFunction( overwritten ) ) {
9563                                 overwritten( responseContainer[ 0 ] );
9564                         }
9565
9566                         responseContainer = overwritten = undefined;
9567                 } );
9568
9569                 // Delegate to script
9570                 return "script";
9571         }
9572 } );
9573
9574
9575
9576
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;
9586 } )();
9587
9588
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" ) {
9595                 return [];
9596         }
9597         if ( typeof context === "boolean" ) {
9598                 keepScripts = context;
9599                 context = false;
9600         }
9601
9602         var base, parsed, scripts;
9603
9604         if ( !context ) {
9605
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( "" );
9610
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 );
9617                 } else {
9618                         context = document;
9619                 }
9620         }
9621
9622         parsed = rsingleTag.exec( data );
9623         scripts = !keepScripts && [];
9624
9625         // Single tag
9626         if ( parsed ) {
9627                 return [ context.createElement( parsed[ 1 ] ) ];
9628         }
9629
9630         parsed = buildFragment( [ data ], context, scripts );
9631
9632         if ( scripts && scripts.length ) {
9633                 jQuery( scripts ).remove();
9634         }
9635
9636         return jQuery.merge( [], parsed.childNodes );
9637 };
9638
9639
9640 /**
9641  * Load a url into a page
9642  */
9643 jQuery.fn.load = function( url, params, callback ) {
9644         var selector, type, response,
9645                 self = this,
9646                 off = url.indexOf( " " );
9647
9648         if ( off > -1 ) {
9649                 selector = jQuery.trim( url.slice( off ) );
9650                 url = url.slice( 0, off );
9651         }
9652
9653         // If it's a function
9654         if ( jQuery.isFunction( params ) ) {
9655
9656                 // We assume that it's the callback
9657                 callback = params;
9658                 params = undefined;
9659
9660         // Otherwise, build a param string
9661         } else if ( params && typeof params === "object" ) {
9662                 type = "POST";
9663         }
9664
9665         // If we have elements to modify, make the request
9666         if ( self.length > 0 ) {
9667                 jQuery.ajax( {
9668                         url: url,
9669
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",
9674                         dataType: "html",
9675                         data: params
9676                 } ).done( function( responseText ) {
9677
9678                         // Save response for use in complete callback
9679                         response = arguments;
9680
9681                         self.html( selector ?
9682
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 ) :
9686
9687                                 // Otherwise use the full result
9688                                 responseText );
9689
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 ] );
9696                         } );
9697                 } );
9698         }
9699
9700         return this;
9701 };
9702
9703
9704
9705
9706 // Attach a bunch of functions for handling common AJAX events
9707 jQuery.each( [
9708         "ajaxStart",
9709         "ajaxStop",
9710         "ajaxComplete",
9711         "ajaxError",
9712         "ajaxSuccess",
9713         "ajaxSend"
9714 ], function( i, type ) {
9715         jQuery.fn[ type ] = function( fn ) {
9716                 return this.on( type, fn );
9717         };
9718 } );
9719
9720
9721
9722
9723 jQuery.expr.pseudos.animated = function( elem ) {
9724         return jQuery.grep( jQuery.timers, function( fn ) {
9725                 return elem === fn.elem;
9726         } ).length;
9727 };
9728
9729
9730
9731
9732 /**
9733  * Gets a window from an element
9734  */
9735 function getWindow( elem ) {
9736         return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
9737 }
9738
9739 jQuery.offset = {
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 ),
9744                         props = {};
9745
9746                 // Set position first, in-case top/left are set even on static elem
9747                 if ( position === "static" ) {
9748                         elem.style.position = "relative";
9749                 }
9750
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;
9756
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;
9763
9764                 } else {
9765                         curTop = parseFloat( curCSSTop ) || 0;
9766                         curLeft = parseFloat( curCSSLeft ) || 0;
9767                 }
9768
9769                 if ( jQuery.isFunction( options ) ) {
9770
9771                         // Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
9772                         options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
9773                 }
9774
9775                 if ( options.top != null ) {
9776                         props.top = ( options.top - curOffset.top ) + curTop;
9777                 }
9778                 if ( options.left != null ) {
9779                         props.left = ( options.left - curOffset.left ) + curLeft;
9780                 }
9781
9782                 if ( "using" in options ) {
9783                         options.using.call( elem, props );
9784
9785                 } else {
9786                         curElem.css( props );
9787                 }
9788         }
9789 };
9790
9791 jQuery.fn.extend( {
9792         offset: function( options ) {
9793
9794                 // Preserve chaining for setter
9795                 if ( arguments.length ) {
9796                         return options === undefined ?
9797                                 this :
9798                                 this.each( function( i ) {
9799                                         jQuery.offset.setOffset( this, options, i );
9800                                 } );
9801                 }
9802
9803                 var docElem, win, rect, doc,
9804                         elem = this[ 0 ];
9805
9806                 if ( !elem ) {
9807                         return;
9808                 }
9809
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 };
9815                 }
9816
9817                 rect = elem.getBoundingClientRect();
9818
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;
9824
9825                         return {
9826                                 top: rect.top + win.pageYOffset - docElem.clientTop,
9827                                 left: rect.left + win.pageXOffset - docElem.clientLeft
9828                         };
9829                 }
9830
9831                 // Return zeros for disconnected and hidden elements (gh-2310)
9832                 return rect;
9833         },
9834
9835         position: function() {
9836                 if ( !this[ 0 ] ) {
9837                         return;
9838                 }
9839
9840                 var offsetParent, offset,
9841                         elem = this[ 0 ],
9842                         parentOffset = { top: 0, left: 0 };
9843
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" ) {
9847
9848                         // Assume getBoundingClientRect is there when computed position is fixed
9849                         offset = elem.getBoundingClientRect();
9850
9851                 } else {
9852
9853                         // Get *real* offsetParent
9854                         offsetParent = this.offsetParent();
9855
9856                         // Get correct offsets
9857                         offset = this.offset();
9858                         if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
9859                                 parentOffset = offsetParent.offset();
9860                         }
9861
9862                         // Add offsetParent borders
9863                         parentOffset = {
9864                                 top: parentOffset.top + jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ),
9865                                 left: parentOffset.left + jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true )
9866                         };
9867                 }
9868
9869                 // Subtract parent offsets and element margins
9870                 return {
9871                         top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
9872                         left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
9873                 };
9874         },
9875
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
9881         //
9882         // but those exceptions were never presented as a real life use-cases
9883         // and might be considered as more preferable results.
9884         //
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;
9889
9890                         while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
9891                                 offsetParent = offsetParent.offsetParent;
9892                         }
9893
9894                         return offsetParent || documentElement;
9895                 } );
9896         }
9897 } );
9898
9899 // Create scrollLeft and scrollTop methods
9900 jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
9901         var top = "pageYOffset" === prop;
9902
9903         jQuery.fn[ method ] = function( val ) {
9904                 return access( this, function( elem, method, val ) {
9905                         var win = getWindow( elem );
9906
9907                         if ( val === undefined ) {
9908                                 return win ? win[ prop ] : elem[ method ];
9909                         }
9910
9911                         if ( win ) {
9912                                 win.scrollTo(
9913                                         !top ? val : win.pageXOffset,
9914                                         top ? val : win.pageYOffset
9915                                 );
9916
9917                         } else {
9918                                 elem[ method ] = val;
9919                         }
9920                 }, method, val, arguments.length );
9921         };
9922 } );
9923
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 ) {
9933                         if ( computed ) {
9934                                 computed = curCSS( elem, prop );
9935
9936                                 // If curCSS returns percentage, fallback to offset
9937                                 return rnumnonpx.test( computed ) ?
9938                                         jQuery( elem ).position()[ prop ] + "px" :
9939                                         computed;
9940                         }
9941                 }
9942         );
9943 } );
9944
9945
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 ) {
9950
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" );
9955
9956                         return access( this, function( elem, type, value ) {
9957                                 var doc;
9958
9959                                 if ( jQuery.isWindow( elem ) ) {
9960
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 ];
9965                                 }
9966
9967                                 // Get document width or height
9968                                 if ( elem.nodeType === 9 ) {
9969                                         doc = elem.documentElement;
9970
9971                                         // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
9972                                         // whichever is greatest
9973                                         return Math.max(
9974                                                 elem.body[ "scroll" + name ], doc[ "scroll" + name ],
9975                                                 elem.body[ "offset" + name ], doc[ "offset" + name ],
9976                                                 doc[ "client" + name ]
9977                                         );
9978                                 }
9979
9980                                 return value === undefined ?
9981
9982                                         // Get width or height on the element, requesting but not forcing parseFloat
9983                                         jQuery.css( elem, type, extra ) :
9984
9985                                         // Set width or height on the element
9986                                         jQuery.style( elem, type, value, extra );
9987                         }, type, chainable ? margin : undefined, chainable );
9988                 };
9989         } );
9990 } );
9991
9992
9993 jQuery.fn.extend( {
9994
9995         bind: function( types, data, fn ) {
9996                 return this.on( types, null, data, fn );
9997         },
9998         unbind: function( types, fn ) {
9999                 return this.off( types, null, fn );
10000         },
10001
10002         delegate: function( selector, types, data, fn ) {
10003                 return this.on( types, selector, data, fn );
10004         },
10005         undelegate: function( selector, types, fn ) {
10006
10007                 // ( namespace ) or ( selector, types [, fn] )
10008                 return arguments.length === 1 ?
10009                         this.off( selector, "**" ) :
10010                         this.off( types, selector || "**", fn );
10011         }
10012 } );
10013
10014 jQuery.parseJSON = JSON.parse;
10015
10016
10017
10018
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.
10026
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
10031
10032 if ( typeof define === "function" && define.amd ) {
10033         define( "jquery", [], function() {
10034                 return jQuery;
10035         } );
10036 }
10037
10038
10039
10040
10041
10042 var
10043
10044         // Map over jQuery in case of overwrite
10045         _jQuery = window.jQuery,
10046
10047         // Map over the $ in case of overwrite
10048         _$ = window.$;
10049
10050 jQuery.noConflict = function( deep ) {
10051         if ( window.$ === jQuery ) {
10052                 window.$ = _$;
10053         }
10054
10055         if ( deep && window.jQuery === jQuery ) {
10056                 window.jQuery = _jQuery;
10057         }
10058
10059         return jQuery;
10060 };
10061
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)
10065 if ( !noGlobal ) {
10066         window.jQuery = window.$ = jQuery;
10067 }
10068
10069
10070 return jQuery;
10071 } );
10072
10073 /**
10074  * @license AngularJS v1.5.11
10075  * (c) 2010-2017 Google, Inc. http://angularjs.org
10076  * License: MIT
10077  */
10078 (function(window){
10079   var _jQuery = window.jQuery.noConflict(true);
10080
10081 /**
10082  * @description
10083  *
10084  * This object provides a utility for producing rich Error messages within
10085  * Angular. It can be called as follows:
10086  *
10087  * var exampleMinErr = minErr('example');
10088  * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
10089  *
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
10094  * take.
10095  *
10096  * If fewer arguments are specified than necessary for interpolation, the extra
10097  * interpolation markers will be preserved in the final string.
10098  *
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.
10104  *
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
10109  */
10110
10111 function minErr(module, ErrorConstructor) {
10112   ErrorConstructor = ErrorConstructor || Error;
10113   return function() {
10114     var SKIP_INDEXES = 2;
10115
10116     var templateArgs = arguments,
10117       code = templateArgs[0],
10118       message = '[' + (module ? module + ':' : '') + code + '] ',
10119       template = templateArgs[1],
10120       paramPrefix, i;
10121
10122     message += template.replace(/\{\d+\}/g, function(match) {
10123       var index = +match.slice(1, -1),
10124         shiftedIndex = index + SKIP_INDEXES;
10125
10126       if (shiftedIndex < templateArgs.length) {
10127         return toDebugString(templateArgs[shiftedIndex]);
10128       }
10129
10130       return match;
10131     });
10132
10133     message += '\nhttp://errors.angularjs.org/1.5.11/' +
10134       (module ? module + '/' : '') + code;
10135
10136     for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
10137       message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
10138         encodeURIComponent(toDebugString(templateArgs[i]));
10139     }
10140
10141     return new ErrorConstructor(message);
10142   };
10143 }
10144
10145 /* We need to tell ESLint what variables are being exported */
10146 /* exported
10147   angular,
10148   msie,
10149   jqLite,
10150   jQuery,
10151   slice,
10152   splice,
10153   push,
10154   toString,
10155   ngMinErr,
10156   angularModule,
10157   uid,
10158   REGEX_STRING_REGEXP,
10159   VALIDITY_STATE_PROPERTY,
10160
10161   lowercase,
10162   uppercase,
10163   manualLowercase,
10164   manualUppercase,
10165   nodeName_,
10166   isArrayLike,
10167   forEach,
10168   forEachSorted,
10169   reverseParams,
10170   nextUid,
10171   setHashKey,
10172   extend,
10173   toInt,
10174   inherit,
10175   merge,
10176   noop,
10177   identity,
10178   valueFn,
10179   isUndefined,
10180   isDefined,
10181   isObject,
10182   isBlankObject,
10183   isString,
10184   isNumber,
10185   isNumberNaN,
10186   isDate,
10187   isArray,
10188   isFunction,
10189   isRegExp,
10190   isWindow,
10191   isScope,
10192   isFile,
10193   isFormData,
10194   isBlob,
10195   isBoolean,
10196   isPromiseLike,
10197   trim,
10198   escapeForRegexp,
10199   isElement,
10200   makeMap,
10201   includes,
10202   arrayRemove,
10203   copy,
10204   equals,
10205   csp,
10206   jq,
10207   concat,
10208   sliceArgs,
10209   bind,
10210   toJsonReplacer,
10211   toJson,
10212   fromJson,
10213   convertTimezoneToLocal,
10214   timezoneToOffset,
10215   startingTag,
10216   tryDecodeURIComponent,
10217   parseKeyValue,
10218   toKeyValue,
10219   encodeUriSegment,
10220   encodeUriQuery,
10221   angularInit,
10222   bootstrap,
10223   getTestability,
10224   snake_case,
10225   bindJQuery,
10226   assertArg,
10227   assertArgFn,
10228   assertNotHasOwnProperty,
10229   getter,
10230   getBlockNodes,
10231   hasOwnProperty,
10232   createMap,
10233
10234   NODE_TYPE_ELEMENT,
10235   NODE_TYPE_ATTRIBUTE,
10236   NODE_TYPE_TEXT,
10237   NODE_TYPE_COMMENT,
10238   NODE_TYPE_DOCUMENT,
10239   NODE_TYPE_DOCUMENT_FRAGMENT
10240 */
10241
10242 ////////////////////////////////////
10243
10244 /**
10245  * @ngdoc module
10246  * @name ng
10247  * @module ng
10248  * @installation
10249  * @description
10250  *
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.
10256  *
10257  * <div doc-module-components="ng"></div>
10258  */
10259
10260 var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
10261
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';
10265
10266 var hasOwnProperty = Object.prototype.hasOwnProperty;
10267
10268 var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
10269 var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
10270
10271
10272 var manualLowercase = function(s) {
10273   /* eslint-disable no-bitwise */
10274   return isString(s)
10275       ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
10276       : s;
10277   /* eslint-enable */
10278 };
10279 var manualUppercase = function(s) {
10280   /* eslint-disable no-bitwise */
10281   return isString(s)
10282       ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
10283       : s;
10284   /* eslint-enable */
10285 };
10286
10287
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;
10294 }
10295
10296
10297 var
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
10301     slice             = [].slice,
10302     splice            = [].splice,
10303     push              = [].push,
10304     toString          = Object.prototype.toString,
10305     getPrototypeOf    = Object.getPrototypeOf,
10306     ngMinErr          = minErr('ng'),
10307
10308     /** @name angular */
10309     angular           = window.angular || (window.angular = {}),
10310     angularModule,
10311     uid               = 0;
10312
10313 /**
10314  * documentMode is an IE-only property
10315  * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
10316  */
10317 msie = window.document.documentMode;
10318
10319
10320 /**
10321  * @private
10322  * @param {*} obj
10323  * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
10324  *                   String ...)
10325  */
10326 function isArrayLike(obj) {
10327
10328   // `null`, `undefined` and `window` are not array-like
10329   if (obj == null || isWindow(obj)) return false;
10330
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;
10336
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;
10340
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');
10345
10346 }
10347
10348 /**
10349  * @ngdoc function
10350  * @name angular.forEach
10351  * @module ng
10352  * @kind function
10353  *
10354  * @description
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.
10359  *
10360  * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
10361  * using the `hasOwnProperty` method.
10362  *
10363  * Unlike ES262's
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.
10367  *
10368    ```js
10369      var values = {name: 'misko', gender: 'male'};
10370      var log = [];
10371      angular.forEach(values, function(value, key) {
10372        this.push(key + ': ' + value);
10373      }, log);
10374      expect(log).toEqual(['name: misko', 'gender: male']);
10375    ```
10376  *
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`.
10381  */
10382
10383 function forEach(obj, iterator, context) {
10384   var key, length;
10385   if (obj) {
10386     if (isFunction(obj)) {
10387       for (key in 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);
10392         }
10393       }
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);
10399         }
10400       }
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
10405       for (key in obj) {
10406         iterator.call(context, obj[key], key, obj);
10407       }
10408     } else if (typeof obj.hasOwnProperty === 'function') {
10409       // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
10410       for (key in obj) {
10411         if (obj.hasOwnProperty(key)) {
10412           iterator.call(context, obj[key], key, obj);
10413         }
10414       }
10415     } else {
10416       // Slow path for objects which do not have a method `hasOwnProperty`
10417       for (key in obj) {
10418         if (hasOwnProperty.call(obj, key)) {
10419           iterator.call(context, obj[key], key, obj);
10420         }
10421       }
10422     }
10423   }
10424   return obj;
10425 }
10426
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]);
10431   }
10432   return keys;
10433 }
10434
10435
10436 /**
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)}
10440  */
10441 function reverseParams(iteratorFn) {
10442   return function(value, key) {iteratorFn(key, value);};
10443 }
10444
10445 /**
10446  * A consistent way of creating unique IDs in angular.
10447  *
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.
10450  *
10451  * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
10452  *
10453  * @returns {number} an unique alpha-numeric string
10454  */
10455 function nextUid() {
10456   return ++uid;
10457 }
10458
10459
10460 /**
10461  * Set or clear the hashkey for an object.
10462  * @param obj object
10463  * @param h the hashkey (!truthy to delete the hashkey)
10464  */
10465 function setHashKey(obj, h) {
10466   if (h) {
10467     obj.$$hashKey = h;
10468   } else {
10469     delete obj.$$hashKey;
10470   }
10471 }
10472
10473
10474 function baseExtend(dst, objs, deep) {
10475   var h = dst.$$hashKey;
10476
10477   for (var i = 0, ii = objs.length; i < ii; ++i) {
10478     var obj = objs[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++) {
10482       var key = keys[j];
10483       var src = obj[key];
10484
10485       if (deep && isObject(src)) {
10486         if (isDate(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();
10494         } else {
10495           if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
10496           baseExtend(dst[key], [src], true);
10497         }
10498       } else {
10499         dst[key] = src;
10500       }
10501     }
10502   }
10503
10504   setHashKey(dst, h);
10505   return dst;
10506 }
10507
10508 /**
10509  * @ngdoc function
10510  * @name angular.extend
10511  * @module ng
10512  * @kind function
10513  *
10514  * @description
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)`.
10518  *
10519  * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
10520  * {@link angular.merge} for this.
10521  *
10522  * @param {Object} dst Destination object.
10523  * @param {...Object} src Source object(s).
10524  * @returns {Object} Reference to `dst`.
10525  */
10526 function extend(dst) {
10527   return baseExtend(dst, slice.call(arguments, 1), false);
10528 }
10529
10530
10531 /**
10532 * @ngdoc function
10533 * @name angular.merge
10534 * @module ng
10535 * @kind function
10536 *
10537 * @description
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)`.
10541 *
10542 * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
10543 * objects, performing a deep copy.
10544 *
10545 * @param {Object} dst Destination object.
10546 * @param {...Object} src Source object(s).
10547 * @returns {Object} Reference to `dst`.
10548 */
10549 function merge(dst) {
10550   return baseExtend(dst, slice.call(arguments, 1), true);
10551 }
10552
10553
10554
10555 function toInt(str) {
10556   return parseInt(str, 10);
10557 }
10558
10559 var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
10560   // eslint-disable-next-line no-self-compare
10561   return num !== num;
10562 };
10563
10564
10565 function inherit(parent, extra) {
10566   return extend(Object.create(parent), extra);
10567 }
10568
10569 /**
10570  * @ngdoc function
10571  * @name angular.noop
10572  * @module ng
10573  * @kind function
10574  *
10575  * @description
10576  * A function that performs no operations. This function can be useful when writing code in the
10577  * functional style.
10578    ```js
10579      function foo(callback) {
10580        var result = calculateResult();
10581        (callback || angular.noop)(result);
10582      }
10583    ```
10584  */
10585 function noop() {}
10586 noop.$inject = [];
10587
10588
10589 /**
10590  * @ngdoc function
10591  * @name angular.identity
10592  * @module ng
10593  * @kind function
10594  *
10595  * @description
10596  * A function that returns its first argument. This function is useful when writing code in the
10597  * functional style.
10598  *
10599    ```js
10600    function transformer(transformationFn, value) {
10601      return (transformationFn || angular.identity)(value);
10602    };
10603
10604    // E.g.
10605    function getResult(fn, input) {
10606      return (fn || angular.identity)(input);
10607    };
10608
10609    getResult(function(n) { return n * 2; }, 21);   // returns 42
10610    getResult(null, 21);                            // returns 21
10611    getResult(undefined, 21);                       // returns 21
10612    ```
10613  *
10614  * @param {*} value to be returned.
10615  * @returns {*} the value passed in.
10616  */
10617 function identity($) {return $;}
10618 identity.$inject = [];
10619
10620
10621 function valueFn(value) {return function valueRef() {return value;};}
10622
10623 function hasCustomToString(obj) {
10624   return isFunction(obj.toString) && obj.toString !== toString;
10625 }
10626
10627
10628 /**
10629  * @ngdoc function
10630  * @name angular.isUndefined
10631  * @module ng
10632  * @kind function
10633  *
10634  * @description
10635  * Determines if a reference is undefined.
10636  *
10637  * @param {*} value Reference to check.
10638  * @returns {boolean} True if `value` is undefined.
10639  */
10640 function isUndefined(value) {return typeof value === 'undefined';}
10641
10642
10643 /**
10644  * @ngdoc function
10645  * @name angular.isDefined
10646  * @module ng
10647  * @kind function
10648  *
10649  * @description
10650  * Determines if a reference is defined.
10651  *
10652  * @param {*} value Reference to check.
10653  * @returns {boolean} True if `value` is defined.
10654  */
10655 function isDefined(value) {return typeof value !== 'undefined';}
10656
10657
10658 /**
10659  * @ngdoc function
10660  * @name angular.isObject
10661  * @module ng
10662  * @kind function
10663  *
10664  * @description
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.
10667  *
10668  * @param {*} value Reference to check.
10669  * @returns {boolean} True if `value` is an `Object` but not `null`.
10670  */
10671 function isObject(value) {
10672   // http://jsperf.com/isobject4
10673   return value !== null && typeof value === 'object';
10674 }
10675
10676
10677 /**
10678  * Determine if a value is an object with a null prototype
10679  *
10680  * @returns {boolean} True if `value` is an `Object` with a null prototype
10681  */
10682 function isBlankObject(value) {
10683   return value !== null && typeof value === 'object' && !getPrototypeOf(value);
10684 }
10685
10686
10687 /**
10688  * @ngdoc function
10689  * @name angular.isString
10690  * @module ng
10691  * @kind function
10692  *
10693  * @description
10694  * Determines if a reference is a `String`.
10695  *
10696  * @param {*} value Reference to check.
10697  * @returns {boolean} True if `value` is a `String`.
10698  */
10699 function isString(value) {return typeof value === 'string';}
10700
10701
10702 /**
10703  * @ngdoc function
10704  * @name angular.isNumber
10705  * @module ng
10706  * @kind function
10707  *
10708  * @description
10709  * Determines if a reference is a `Number`.
10710  *
10711  * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
10712  *
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)
10715  * method.
10716  *
10717  * @param {*} value Reference to check.
10718  * @returns {boolean} True if `value` is a `Number`.
10719  */
10720 function isNumber(value) {return typeof value === 'number';}
10721
10722
10723 /**
10724  * @ngdoc function
10725  * @name angular.isDate
10726  * @module ng
10727  * @kind function
10728  *
10729  * @description
10730  * Determines if a value is a date.
10731  *
10732  * @param {*} value Reference to check.
10733  * @returns {boolean} True if `value` is a `Date`.
10734  */
10735 function isDate(value) {
10736   return toString.call(value) === '[object Date]';
10737 }
10738
10739
10740 /**
10741  * @ngdoc function
10742  * @name angular.isArray
10743  * @module ng
10744  * @kind function
10745  *
10746  * @description
10747  * Determines if a reference is an `Array`. Alias of Array.isArray.
10748  *
10749  * @param {*} value Reference to check.
10750  * @returns {boolean} True if `value` is an `Array`.
10751  */
10752 var isArray = Array.isArray;
10753
10754 /**
10755  * @ngdoc function
10756  * @name angular.isFunction
10757  * @module ng
10758  * @kind function
10759  *
10760  * @description
10761  * Determines if a reference is a `Function`.
10762  *
10763  * @param {*} value Reference to check.
10764  * @returns {boolean} True if `value` is a `Function`.
10765  */
10766 function isFunction(value) {return typeof value === 'function';}
10767
10768
10769 /**
10770  * Determines if a value is a regular expression object.
10771  *
10772  * @private
10773  * @param {*} value Reference to check.
10774  * @returns {boolean} True if `value` is a `RegExp`.
10775  */
10776 function isRegExp(value) {
10777   return toString.call(value) === '[object RegExp]';
10778 }
10779
10780
10781 /**
10782  * Checks if `obj` is a window object.
10783  *
10784  * @private
10785  * @param {*} obj Object to check
10786  * @returns {boolean} True if `obj` is a window obj.
10787  */
10788 function isWindow(obj) {
10789   return obj && obj.window === obj;
10790 }
10791
10792
10793 function isScope(obj) {
10794   return obj && obj.$evalAsync && obj.$watch;
10795 }
10796
10797
10798 function isFile(obj) {
10799   return toString.call(obj) === '[object File]';
10800 }
10801
10802
10803 function isFormData(obj) {
10804   return toString.call(obj) === '[object FormData]';
10805 }
10806
10807
10808 function isBlob(obj) {
10809   return toString.call(obj) === '[object Blob]';
10810 }
10811
10812
10813 function isBoolean(value) {
10814   return typeof value === 'boolean';
10815 }
10816
10817
10818 function isPromiseLike(obj) {
10819   return obj && isFunction(obj.then);
10820 }
10821
10822
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));
10826 }
10827
10828 function isArrayBuffer(obj) {
10829   return toString.call(obj) === '[object ArrayBuffer]';
10830 }
10831
10832
10833 var trim = function(value) {
10834   return isString(value) ? value.trim() : value;
10835 };
10836
10837 // Copied from:
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) {
10841   return s
10842     .replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1')
10843     // eslint-disable-next-line no-control-regex
10844     .replace(/\x08/g, '\\x08');
10845 };
10846
10847
10848 /**
10849  * @ngdoc function
10850  * @name angular.isElement
10851  * @module ng
10852  * @kind function
10853  *
10854  * @description
10855  * Determines if a reference is a DOM element (or wrapped jQuery element).
10856  *
10857  * @param {*} value Reference to check.
10858  * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
10859  */
10860 function isElement(node) {
10861   return !!(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.
10864 }
10865
10866 /**
10867  * @param str 'key1,key2,...'
10868  * @returns {object} in the form of {key1:true, key2:true, ...}
10869  */
10870 function makeMap(str) {
10871   var obj = {}, items = str.split(','), i;
10872   for (i = 0; i < items.length; i++) {
10873     obj[items[i]] = true;
10874   }
10875   return obj;
10876 }
10877
10878
10879 function nodeName_(element) {
10880   return lowercase(element.nodeName || (element[0] && element[0].nodeName));
10881 }
10882
10883 function includes(array, obj) {
10884   return Array.prototype.indexOf.call(array, obj) !== -1;
10885 }
10886
10887 function arrayRemove(array, value) {
10888   var index = array.indexOf(value);
10889   if (index >= 0) {
10890     array.splice(index, 1);
10891   }
10892   return index;
10893 }
10894
10895 /**
10896  * @ngdoc function
10897  * @name angular.copy
10898  * @module ng
10899  * @kind function
10900  *
10901  * @description
10902  * Creates a deep copy of `source`, which should be an object or an array.
10903  *
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.
10909  *
10910  * <br />
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.
10914  * </div>
10915  *
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.
10921  *
10922  * @example
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>
10933         </form>
10934         <pre>form = {{user | json}}</pre>
10935         <pre>master = {{master | json}}</pre>
10936       </div>
10937     </file>
10938     <file name="script.js">
10939       // Module: copyExample
10940       angular.
10941         module('copyExample', []).
10942         controller('ExampleController', ['$scope', function($scope) {
10943           $scope.master = {};
10944
10945           $scope.reset = function() {
10946             // Example with 1 argument
10947             $scope.user = angular.copy($scope.master);
10948           };
10949
10950           $scope.update = function(user) {
10951             // Example with 2 arguments
10952             angular.copy(user, $scope.master);
10953           };
10954
10955           $scope.reset();
10956         }]);
10957     </file>
10958   </example>
10959  */
10960 function copy(source, destination) {
10961   var stackSource = [];
10962   var stackDest = [];
10963
10964   if (destination) {
10965     if (isTypedArray(destination) || isArrayBuffer(destination)) {
10966       throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
10967     }
10968     if (source === destination) {
10969       throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
10970     }
10971
10972     // Empty the destination object
10973     if (isArray(destination)) {
10974       destination.length = 0;
10975     } else {
10976       forEach(destination, function(value, key) {
10977         if (key !== '$$hashKey') {
10978           delete destination[key];
10979         }
10980       });
10981     }
10982
10983     stackSource.push(source);
10984     stackDest.push(destination);
10985     return copyRecurse(source, destination);
10986   }
10987
10988   return copyElement(source);
10989
10990   function copyRecurse(source, destination) {
10991     var h = destination.$$hashKey;
10992     var key;
10993     if (isArray(source)) {
10994       for (var i = 0, ii = source.length; i < ii; i++) {
10995         destination.push(copyElement(source[i]));
10996       }
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]);
11001       }
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]);
11007         }
11008       }
11009     } else {
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]);
11014         }
11015       }
11016     }
11017     setHashKey(destination, h);
11018     return destination;
11019   }
11020
11021   function copyElement(source) {
11022     // Simple values
11023     if (!isObject(source)) {
11024       return source;
11025     }
11026
11027     // Already copied values
11028     var index = stackSource.indexOf(source);
11029     if (index !== -1) {
11030       return stackDest[index];
11031     }
11032
11033     if (isWindow(source) || isScope(source)) {
11034       throw ngMinErr('cpws',
11035         'Can\'t copy! Making copies of Window or Scope instances is not supported.');
11036     }
11037
11038     var needsRecurse = false;
11039     var destination = copyType(source);
11040
11041     if (destination === undefined) {
11042       destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
11043       needsRecurse = true;
11044     }
11045
11046     stackSource.push(source);
11047     stackDest.push(destination);
11048
11049     return needsRecurse
11050       ? copyRecurse(source, destination)
11051       : destination;
11052   }
11053
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);
11066
11067       case '[object ArrayBuffer]':
11068         // Support: IE10
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 */
11075           return copied;
11076         }
11077         return source.slice(0);
11078
11079       case '[object Boolean]':
11080       case '[object Number]':
11081       case '[object String]':
11082       case '[object Date]':
11083         return new source.constructor(source.valueOf());
11084
11085       case '[object RegExp]':
11086         var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);
11087         re.lastIndex = source.lastIndex;
11088         return re;
11089
11090       case '[object Blob]':
11091         return new source.constructor([source], {type: source.type});
11092     }
11093
11094     if (isFunction(source.cloneNode)) {
11095       return source.cloneNode(true);
11096     }
11097   }
11098 }
11099
11100
11101 /**
11102  * @ngdoc function
11103  * @name angular.equals
11104  * @module ng
11105  * @kind function
11106  *
11107  * @description
11108  * Determines if two objects or two values are equivalent. Supports value types, regular
11109  * expressions, arrays and objects.
11110  *
11111  * Two objects or values are considered equivalent if at least one of the following is true:
11112  *
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).
11120  *
11121  * During a property comparison, properties of `function` type and properties with names
11122  * that begin with `$` are ignored.
11123  *
11124  * Scope and DOMWindow objects are being compared only by identify (`===`).
11125  *
11126  * @param {*} o1 Object or value to compare.
11127  * @param {*} o2 Object or value to compare.
11128  * @returns {boolean} True if arguments are equal.
11129  *
11130  * @example
11131    <example module="equalsExample" name="equalsExample">
11132      <file name="index.html">
11133       <div ng-controller="ExampleController">
11134         <form novalidate>
11135           <h3>User 1</h3>
11136           Name: <input type="text" ng-model="user1.name">
11137           Age: <input type="number" ng-model="user1.age">
11138
11139           <h3>User 2</h3>
11140           Name: <input type="text" ng-model="user2.name">
11141           Age: <input type="number" ng-model="user2.age">
11142
11143           <div>
11144             <br/>
11145             <input type="button" value="Compare" ng-click="compare()">
11146           </div>
11147           User 1: <pre>{{user1 | json}}</pre>
11148           User 2: <pre>{{user2 | json}}</pre>
11149           Equal: <pre>{{result}}</pre>
11150         </form>
11151       </div>
11152     </file>
11153     <file name="script.js">
11154         angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
11155           $scope.user1 = {};
11156           $scope.user2 = {};
11157           $scope.compare = function() {
11158             $scope.result = angular.equals($scope.user1, $scope.user2);
11159           };
11160         }]);
11161     </file>
11162   </example>
11163  */
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') {
11171     if (isArray(o1)) {
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;
11176         }
11177         return true;
11178       }
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();
11185     } else {
11186       if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
11187         isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
11188       keySet = createMap();
11189       for (key in o1) {
11190         if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
11191         if (!equals(o1[key], o2[key])) return false;
11192         keySet[key] = true;
11193       }
11194       for (key in o2) {
11195         if (!(key in keySet) &&
11196             key.charAt(0) !== '$' &&
11197             isDefined(o2[key]) &&
11198             !isFunction(o2[key])) return false;
11199       }
11200       return true;
11201     }
11202   }
11203   return false;
11204 }
11205
11206 var csp = function() {
11207   if (!isDefined(csp.rules)) {
11208
11209
11210     var ngCspElement = (window.document.querySelector('[ng-csp]') ||
11211                     window.document.querySelector('[data-ng-csp]'));
11212
11213     if (ngCspElement) {
11214       var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
11215                     ngCspElement.getAttribute('data-ng-csp');
11216       csp.rules = {
11217         noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
11218         noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
11219       };
11220     } else {
11221       csp.rules = {
11222         noUnsafeEval: noUnsafeEval(),
11223         noInlineStyle: false
11224       };
11225     }
11226   }
11227
11228   return csp.rules;
11229
11230   function noUnsafeEval() {
11231     try {
11232       // eslint-disable-next-line no-new, no-new-func
11233       new Function('');
11234       return false;
11235     } catch (e) {
11236       return true;
11237     }
11238   }
11239 };
11240
11241 /**
11242  * @ngdoc directive
11243  * @module ng
11244  * @name ngJq
11245  *
11246  * @element ANY
11247  * @param {string=} ngJq the name of the library available under `window`
11248  * to be used for angular.element
11249  * @description
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).
11253  *
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
11257  * others ignored.
11258  *
11259  * @example
11260  * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
11261  ```html
11262  <!doctype html>
11263  <html ng-app ng-jq>
11264  ...
11265  ...
11266  </html>
11267  ```
11268  * @example
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'.
11271  ```html
11272  <!doctype html>
11273  <html ng-app ng-jq="jQueryLib">
11274  ...
11275  ...
11276  </html>
11277  ```
11278  */
11279 var jq = function() {
11280   if (isDefined(jq.name_)) return jq.name_;
11281   var el;
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]');
11286     if (el) {
11287       name = el.getAttribute(prefix + 'jq');
11288       break;
11289     }
11290   }
11291
11292   return (jq.name_ = name);
11293 };
11294
11295 function concat(array1, array2, index) {
11296   return array1.concat(slice.call(array2, index));
11297 }
11298
11299 function sliceArgs(args, startIndex) {
11300   return slice.call(args, startIndex || 0);
11301 }
11302
11303
11304 /**
11305  * @ngdoc function
11306  * @name angular.bind
11307  * @module ng
11308  * @kind function
11309  *
11310  * @description
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).
11315  *
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.
11320  */
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
11325       ? function() {
11326           return arguments.length
11327             ? fn.apply(self, concat(curryArgs, arguments, 0))
11328             : fn.apply(self, curryArgs);
11329         }
11330       : function() {
11331           return arguments.length
11332             ? fn.apply(self, arguments)
11333             : fn.call(self);
11334         };
11335   } else {
11336     // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
11337     return fn;
11338   }
11339 }
11340
11341
11342 function toJsonReplacer(key, value) {
11343   var val = value;
11344
11345   if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
11346     val = undefined;
11347   } else if (isWindow(value)) {
11348     val = '$WINDOW';
11349   } else if (value &&  window.document === value) {
11350     val = '$DOCUMENT';
11351   } else if (isScope(value)) {
11352     val = '$SCOPE';
11353   }
11354
11355   return val;
11356 }
11357
11358
11359 /**
11360  * @ngdoc function
11361  * @name angular.toJson
11362  * @module ng
11363  * @kind function
11364  *
11365  * @description
11366  * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
11367  * stripped since angular uses this notation internally.
11368  *
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`.
11373  * @knownIssue
11374  *
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:
11378  *
11379  * ```
11380  * var _DatetoJSON = Date.prototype.toJSON;
11381  * Date.prototype.toJSON = function() {
11382  *   try {
11383  *     return _DatetoJSON.call(this);
11384  *   } catch(e) {
11385  *     if (e instanceof RangeError) {
11386  *       return null;
11387  *     }
11388  *     throw e;
11389  *   }
11390  * };
11391  * ```
11392  *
11393  * See https://github.com/angular/angular.js/pull/14221 for more information.
11394  */
11395 function toJson(obj, pretty) {
11396   if (isUndefined(obj)) return undefined;
11397   if (!isNumber(pretty)) {
11398     pretty = pretty ? 2 : null;
11399   }
11400   return JSON.stringify(obj, toJsonReplacer, pretty);
11401 }
11402
11403
11404 /**
11405  * @ngdoc function
11406  * @name angular.fromJson
11407  * @module ng
11408  * @kind function
11409  *
11410  * @description
11411  * Deserializes a JSON string.
11412  *
11413  * @param {string} json JSON string to deserialize.
11414  * @returns {Object|Array|string|number} Deserialized JSON string.
11415  */
11416 function fromJson(json) {
11417   return isString(json)
11418       ? JSON.parse(json)
11419       : json;
11420 }
11421
11422
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;
11429 }
11430
11431
11432 function addDateMinutes(date, minutes) {
11433   date = new Date(date.getTime());
11434   date.setMinutes(date.getMinutes() + minutes);
11435   return date;
11436 }
11437
11438
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));
11444 }
11445
11446
11447 /**
11448  * @returns {string} Returns the string representation of the element.
11449  */
11450 function startingTag(element) {
11451   element = jqLite(element).clone();
11452   try {
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.
11455     element.empty();
11456   } catch (e) { /* empty */ }
11457   var elemHtml = jqLite('<div>').append(element).html();
11458   try {
11459     return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
11460         elemHtml.
11461           match(/^(<[^>]+>)/)[1].
11462           replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
11463   } catch (e) {
11464     return lowercase(elemHtml);
11465   }
11466
11467 }
11468
11469
11470 /////////////////////////////////////////////////
11471
11472 /**
11473  * Tries to decode the URI component without throwing an exception.
11474  *
11475  * @private
11476  * @param str value potential URI component to check.
11477  * @returns {boolean} True if `value` can be decoded
11478  * with the decodeURIComponent function.
11479  */
11480 function tryDecodeURIComponent(value) {
11481   try {
11482     return decodeURIComponent(value);
11483   } catch (e) {
11484     // Ignore any invalid uri component.
11485   }
11486 }
11487
11488
11489 /**
11490  * Parses an escaped url query string into key-value pairs.
11491  * @returns {Object.<string,boolean|Array>}
11492  */
11493 function parseKeyValue(/**string*/keyValue) {
11494   var obj = {};
11495   forEach((keyValue || '').split('&'), function(keyValue) {
11496     var splitPoint, key, val;
11497     if (keyValue) {
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);
11503       }
11504       key = tryDecodeURIComponent(key);
11505       if (isDefined(key)) {
11506         val = isDefined(val) ? tryDecodeURIComponent(val) : true;
11507         if (!hasOwnProperty.call(obj, key)) {
11508           obj[key] = val;
11509         } else if (isArray(obj[key])) {
11510           obj[key].push(val);
11511         } else {
11512           obj[key] = [obj[key],val];
11513         }
11514       }
11515     }
11516   });
11517   return obj;
11518 }
11519
11520 function toKeyValue(obj) {
11521   var parts = [];
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)));
11527       });
11528     } else {
11529     parts.push(encodeUriQuery(key, true) +
11530                (value === true ? '' : '=' + encodeUriQuery(value, true)));
11531     }
11532   });
11533   return parts.length ? parts.join('&') : '';
11534 }
11535
11536
11537 /**
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
11540  * segments:
11541  *    segment       = *pchar
11542  *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
11543  *    pct-encoded   = "%" HEXDIG HEXDIG
11544  *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
11545  *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
11546  *                     / "*" / "+" / "," / ";" / "="
11547  */
11548 function encodeUriSegment(val) {
11549   return encodeUriQuery(val, true).
11550              replace(/%26/gi, '&').
11551              replace(/%3D/gi, '=').
11552              replace(/%2B/gi, '+');
11553 }
11554
11555
11556 /**
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  *                     / "*" / "+" / "," / ";" / "="
11566  */
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' : '+'));
11575 }
11576
11577 var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
11578
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))) {
11584       return attr;
11585     }
11586   }
11587   return null;
11588 }
11589
11590 function allowAutoBootstrap(document) {
11591   var script = document.currentScript;
11592   var src = script && script.getAttribute('src');
11593
11594   if (!src) {
11595     return true;
11596   }
11597
11598   var link = document.createElement('a');
11599   link.href = src;
11600
11601   if (document.location.origin === link.origin) {
11602     // Same-origin resources are always allowed, even for non-whitelisted schemes.
11603     return true;
11604   }
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) {
11609     case 'http:':
11610     case 'https:':
11611     case 'ftp:':
11612     case 'blob:':
11613     case 'file:':
11614     case 'data:':
11615       return true;
11616     default:
11617       return false;
11618   }
11619 }
11620
11621 // Cached as it has to run during loading so that document.currentScript is available.
11622 var isAutoBootstrapAllowed = allowAutoBootstrap(window.document);
11623
11624 /**
11625  * @ngdoc directive
11626  * @name ngApp
11627  * @module ng
11628  *
11629  * @element ANY
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.
11637  *
11638  * @description
11639  *
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.
11643  *
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.
11655  *
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.
11660  *
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`.
11664  *
11665  * `ngApp` is the easiest, and most common way to bootstrap an application.
11666  *
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 }}
11671    </div>
11672    </file>
11673    <file name="script.js">
11674    angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
11675      $scope.a = 1;
11676      $scope.b = 2;
11677    });
11678    </file>
11679  </example>
11680  *
11681  * Using `ngStrictDi`, you would see something like this:
11682  *
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 }}
11688
11689            <p>This renders because the controller does not fail to
11690               instantiate, by using explicit annotation style (see
11691               script.js for details)
11692            </p>
11693        </div>
11694
11695        <div ng-controller="GoodController2">
11696            Name: <input ng-model="name"><br />
11697            Hello, {{name}}!
11698
11699            <p>This renders because the controller does not fail to
11700               instantiate, by using explicit annotation style
11701               (see script.js for details)
11702            </p>
11703        </div>
11704
11705        <div ng-controller="BadController">
11706            I can add: {{a}} + {{b}} =  {{ a+b }}
11707
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.
11712            </p>
11713        </div>
11714    </div>
11715    </file>
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) {
11721        $scope.a = 1;
11722        $scope.b = 2;
11723      })
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) {
11727        $scope.a = 1;
11728        $scope.b = 2;
11729      }])
11730      .controller('GoodController2', GoodController2);
11731      function GoodController2($scope) {
11732        $scope.name = 'World';
11733      }
11734      GoodController2.$inject = ['$scope'];
11735    </file>
11736    <file name="style.css">
11737    div[ng-controller] {
11738        margin-bottom: 1em;
11739        -webkit-border-radius: 4px;
11740        border-radius: 4px;
11741        border: 1px solid;
11742        padding: .5em;
11743    }
11744    div[ng-controller^=Good] {
11745        border-color: #d6e9c6;
11746        background-color: #dff0d8;
11747        color: #3c763d;
11748    }
11749    div[ng-controller^=Bad] {
11750        border-color: #ebccd1;
11751        background-color: #f2dede;
11752        color: #a94442;
11753        margin-bottom: 0;
11754    }
11755    </file>
11756  </example>
11757  */
11758 function angularInit(element, bootstrap) {
11759   var appElement,
11760       module,
11761       config = {};
11762
11763   // The element `element` has priority over any other element.
11764   forEach(ngAttrPrefixes, function(prefix) {
11765     var name = prefix + 'app';
11766
11767     if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
11768       appElement = element;
11769       module = element.getAttribute(name);
11770     }
11771   });
11772   forEach(ngAttrPrefixes, function(prefix) {
11773     var name = prefix + 'app';
11774     var candidate;
11775
11776     if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
11777       appElement = candidate;
11778       module = candidate.getAttribute(name);
11779     }
11780   });
11781   if (appElement) {
11782     if (!isAutoBootstrapAllowed) {
11783       window.console.error('Angular: disabling automatic bootstrap. <script> protocol indicates ' +
11784           'an extension, document.location.href does not match.');
11785       return;
11786     }
11787     config.strictDi = getNgAttribute(appElement, 'strict-di') !== null;
11788     bootstrap(appElement, module ? [module] : [], config);
11789   }
11790 }
11791
11792 /**
11793  * @ngdoc function
11794  * @name angular.bootstrap
11795  * @module ng
11796  * @description
11797  * Use this function to manually start up angular application.
11798  *
11799  * For more information, see the {@link guide/bootstrap Bootstrap guide}.
11800  *
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.
11805  *
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}.
11809  * </div>
11810  *
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.
11816  * </div>
11817  *
11818  * ```html
11819  * <!doctype html>
11820  * <html>
11821  * <body>
11822  * <div ng-controller="WelcomeController">
11823  *   {{greeting}}
11824  * </div>
11825  *
11826  * <script src="angular.js"></script>
11827  * <script>
11828  *   var app = angular.module('demo', [])
11829  *   .controller('WelcomeController', function($scope) {
11830  *       $scope.greeting = 'Welcome!';
11831  *   });
11832  *   angular.bootstrap(document, ['demo']);
11833  * </script>
11834  * </body>
11835  * </html>
11836  * ```
11837  *
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:
11845  *
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`.
11848  *
11849  * @returns {auto.$injector} Returns the newly created injector for this app.
11850  */
11851 function bootstrap(element, modules, config) {
11852   if (!isObject(config)) config = {};
11853   var defaultConfig = {
11854     strictDi: false
11855   };
11856   config = extend(defaultConfig, config);
11857   var doBootstrap = function() {
11858     element = jqLite(element);
11859
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.
11863       throw ngMinErr(
11864           'btstrpd',
11865           'App already bootstrapped with this element \'{0}\'',
11866           tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
11867     }
11868
11869     modules = modules || [];
11870     modules.unshift(['$provide', function($provide) {
11871       $provide.value('$rootElement', element);
11872     }]);
11873
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);
11878       }]);
11879     }
11880
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);
11888         });
11889       }]
11890     );
11891     return injector;
11892   };
11893
11894   var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
11895   var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
11896
11897   if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
11898     config.debugInfoEnabled = true;
11899     window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
11900   }
11901
11902   if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
11903     return doBootstrap();
11904   }
11905
11906   window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
11907   angular.resumeBootstrap = function(extraModules) {
11908     forEach(extraModules, function(module) {
11909       modules.push(module);
11910     });
11911     return doBootstrap();
11912   };
11913
11914   if (isFunction(angular.resumeDeferredBootstrap)) {
11915     angular.resumeDeferredBootstrap();
11916   }
11917 }
11918
11919 /**
11920  * @ngdoc function
11921  * @name angular.reloadWithDebugInfo
11922  * @module ng
11923  * @description
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)`.
11926  *
11927  * See {@link ng.$compileProvider#debugInfoEnabled} for more.
11928  */
11929 function reloadWithDebugInfo() {
11930   window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
11931   window.location.reload();
11932 }
11933
11934 /**
11935  * @name angular.getTestability
11936  * @module ng
11937  * @description
11938  * Get the testability service for the instance of Angular on the given
11939  * element.
11940  * @param {DOMElement} element DOM element which is the root of angular application.
11941  */
11942 function getTestability(rootElement) {
11943   var injector = angular.element(rootElement).injector();
11944   if (!injector) {
11945     throw ngMinErr('test',
11946       'no injector found for element argument to getTestability');
11947   }
11948   return injector.get('$$testability');
11949 }
11950
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();
11956   });
11957 }
11958
11959 var bindJQueryFired = false;
11960 function bindJQuery() {
11961   var originalCleanData;
11962
11963   if (bindJQueryFired) {
11964     return;
11965   }
11966
11967   // bind to jQuery if present;
11968   var jqName = jq();
11969   jQuery = isUndefined(jqName) ? window.jQuery :   // use jQuery (if present)
11970            !jqName             ? undefined     :   // use jqLite
11971                                  window[jqName];   // use jQuery specified by `ngJq`
11972
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) {
11978     jqLite = jQuery;
11979     extend(jQuery.fn, {
11980       scope: JQLitePrototype.scope,
11981       isolateScope: JQLitePrototype.isolateScope,
11982       controller: JQLitePrototype.controller,
11983       injector: JQLitePrototype.injector,
11984       inheritedData: JQLitePrototype.inheritedData
11985     });
11986
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) {
11992       var events;
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');
11997         }
11998       }
11999       originalCleanData(elems);
12000     };
12001   } else {
12002     jqLite = JQLite;
12003   }
12004
12005   angular.element = jqLite;
12006
12007   // Prevent double-proxying.
12008   bindJQueryFired = true;
12009 }
12010
12011 /**
12012  * throw error if the argument is falsy.
12013  */
12014 function assertArg(arg, name, reason) {
12015   if (!arg) {
12016     throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
12017   }
12018   return arg;
12019 }
12020
12021 function assertArgFn(arg, name, acceptArrayAnnotation) {
12022   if (acceptArrayAnnotation && isArray(arg)) {
12023       arg = arg[arg.length - 1];
12024   }
12025
12026   assertArg(isFunction(arg), name, 'not a function, got ' +
12027       (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
12028   return arg;
12029 }
12030
12031 /**
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
12035  */
12036 function assertNotHasOwnProperty(name, context) {
12037   if (name === 'hasOwnProperty') {
12038     throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
12039   }
12040 }
12041
12042 /**
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
12048  */
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('.');
12053   var key;
12054   var lastInstance = obj;
12055   var len = keys.length;
12056
12057   for (var i = 0; i < len; i++) {
12058     key = keys[i];
12059     if (obj) {
12060       obj = (lastInstance = obj)[key];
12061     }
12062   }
12063   if (!bindFnToScope && isFunction(obj)) {
12064     return bind(lastInstance, obj);
12065   }
12066   return obj;
12067 }
12068
12069 /**
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
12073  */
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];
12078   var blockNodes;
12079
12080   for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
12081     if (blockNodes || nodes[i] !== node) {
12082       if (!blockNodes) {
12083         blockNodes = jqLite(slice.call(nodes, 0, i));
12084       }
12085       blockNodes.push(node);
12086     }
12087   }
12088
12089   return blockNodes || nodes;
12090 }
12091
12092
12093 /**
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.
12096  *
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
12101  *
12102  * @returns {Object}
12103  */
12104 function createMap() {
12105   return Object.create(null);
12106 }
12107
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;
12114
12115 /**
12116  * @ngdoc type
12117  * @name angular.Module
12118  * @module ng
12119  * @description
12120  *
12121  * Interface for configuring angular {@link angular.module modules}.
12122  */
12123
12124 function setupModuleLoader(window) {
12125
12126   var $injectorMinErr = minErr('$injector');
12127   var ngMinErr = minErr('ng');
12128
12129   function ensure(obj, name, factory) {
12130     return obj[name] || (obj[name] = factory());
12131   }
12132
12133   var angular = ensure(window, 'angular', Object);
12134
12135   // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
12136   angular.$$minErr = angular.$$minErr || minErr;
12137
12138   return ensure(angular, 'module', function() {
12139     /** @type {Object.<string, angular.Module>} */
12140     var modules = {};
12141
12142     /**
12143      * @ngdoc function
12144      * @name angular.module
12145      * @module ng
12146      * @description
12147      *
12148      * The `angular.module` is a global place for creating, registering and retrieving Angular
12149      * modules.
12150      * All modules (angular core or 3rd party) that should be available to an application must be
12151      * registered using this mechanism.
12152      *
12153      * Passing one argument retrieves an existing {@link angular.Module},
12154      * whereas passing more than one argument creates a new {@link angular.Module}
12155      *
12156      *
12157      * # Module
12158      *
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}.
12161      *
12162      * ```js
12163      * // Create a new module
12164      * var myModule = angular.module('myModule', []);
12165      *
12166      * // register a new service
12167      * myModule.value('appName', 'MyCoolApp');
12168      *
12169      * // configure existing services inside initialization blocks.
12170      * myModule.config(['$locationProvider', function($locationProvider) {
12171      *   // Configure existing providers
12172      *   $locationProvider.hashPrefix('!');
12173      * }]);
12174      * ```
12175      *
12176      * Then you can create an injector and load your modules like this:
12177      *
12178      * ```js
12179      * var injector = angular.injector(['ng', 'myModule'])
12180      * ```
12181      *
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.
12185      *
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.
12192      */
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);
12197         }
12198       };
12199
12200       assertNotHasOwnProperty(name, 'module');
12201       if (requires && modules.hasOwnProperty(name)) {
12202         modules[name] = null;
12203       }
12204       return ensure(modules, name, function() {
12205         if (!requires) {
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);
12209         }
12210
12211         /** @type {!Array.<Array.<*>>} */
12212         var invokeQueue = [];
12213
12214         /** @type {!Array.<Function>} */
12215         var configBlocks = [];
12216
12217         /** @type {!Array.<Function>} */
12218         var runBlocks = [];
12219
12220         var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
12221
12222         /** @type {angular.Module} */
12223         var moduleInstance = {
12224           // Private state
12225           _invokeQueue: invokeQueue,
12226           _configBlocks: configBlocks,
12227           _runBlocks: runBlocks,
12228
12229           /**
12230            * @ngdoc property
12231            * @name angular.Module#requires
12232            * @module ng
12233            *
12234            * @description
12235            * Holds the list of modules which the injector will load before the current module is
12236            * loaded.
12237            */
12238           requires: requires,
12239
12240           /**
12241            * @ngdoc property
12242            * @name angular.Module#name
12243            * @module ng
12244            *
12245            * @description
12246            * Name of the module.
12247            */
12248           name: name,
12249
12250
12251           /**
12252            * @ngdoc method
12253            * @name angular.Module#provider
12254            * @module ng
12255            * @param {string} name service name
12256            * @param {Function} providerType Construction function for creating new instance of the
12257            *                                service.
12258            * @description
12259            * See {@link auto.$provide#provider $provide.provider()}.
12260            */
12261           provider: invokeLaterAndSetModuleName('$provide', 'provider'),
12262
12263           /**
12264            * @ngdoc method
12265            * @name angular.Module#factory
12266            * @module ng
12267            * @param {string} name service name
12268            * @param {Function} providerFunction Function for creating new instance of the service.
12269            * @description
12270            * See {@link auto.$provide#factory $provide.factory()}.
12271            */
12272           factory: invokeLaterAndSetModuleName('$provide', 'factory'),
12273
12274           /**
12275            * @ngdoc method
12276            * @name angular.Module#service
12277            * @module ng
12278            * @param {string} name service name
12279            * @param {Function} constructor A constructor function that will be instantiated.
12280            * @description
12281            * See {@link auto.$provide#service $provide.service()}.
12282            */
12283           service: invokeLaterAndSetModuleName('$provide', 'service'),
12284
12285           /**
12286            * @ngdoc method
12287            * @name angular.Module#value
12288            * @module ng
12289            * @param {string} name service name
12290            * @param {*} object Service instance object.
12291            * @description
12292            * See {@link auto.$provide#value $provide.value()}.
12293            */
12294           value: invokeLater('$provide', 'value'),
12295
12296           /**
12297            * @ngdoc method
12298            * @name angular.Module#constant
12299            * @module ng
12300            * @param {string} name constant name
12301            * @param {*} object Constant value.
12302            * @description
12303            * Because the constants are fixed, they get applied before other provide methods.
12304            * See {@link auto.$provide#constant $provide.constant()}.
12305            */
12306           constant: invokeLater('$provide', 'constant', 'unshift'),
12307
12308            /**
12309            * @ngdoc method
12310            * @name angular.Module#decorator
12311            * @module ng
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.
12315            * @description
12316            * See {@link auto.$provide#decorator $provide.decorator()}.
12317            */
12318           decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
12319
12320           /**
12321            * @ngdoc method
12322            * @name angular.Module#animation
12323            * @module ng
12324            * @param {string} name animation name
12325            * @param {Function} animationFactory Factory function for creating new instance of an
12326            *                                    animation.
12327            * @description
12328            *
12329            * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
12330            *
12331            *
12332            * Defines an animation hook that can be later used with
12333            * {@link $animate $animate} service and directives that use this service.
12334            *
12335            * ```js
12336            * module.animation('.animation-name', function($inject1, $inject2) {
12337            *   return {
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
12343            *       }
12344            *     }
12345            *   }
12346            * })
12347            * ```
12348            *
12349            * See {@link ng.$animateProvider#register $animateProvider.register()} and
12350            * {@link ngAnimate ngAnimate module} for more information.
12351            */
12352           animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
12353
12354           /**
12355            * @ngdoc method
12356            * @name angular.Module#filter
12357            * @module ng
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.
12360            * @description
12361            * See {@link ng.$filterProvider#register $filterProvider.register()}.
12362            *
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`).
12368            * </div>
12369            */
12370           filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
12371
12372           /**
12373            * @ngdoc method
12374            * @name angular.Module#controller
12375            * @module ng
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.
12379            * @description
12380            * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
12381            */
12382           controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
12383
12384           /**
12385            * @ngdoc method
12386            * @name angular.Module#directive
12387            * @module ng
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
12391            * directives.
12392            * @description
12393            * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
12394            */
12395           directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
12396
12397           /**
12398            * @ngdoc method
12399            * @name angular.Module#component
12400            * @module ng
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})
12404            *
12405            * @description
12406            * See {@link ng.$compileProvider#component $compileProvider.component()}.
12407            */
12408           component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
12409
12410           /**
12411            * @ngdoc method
12412            * @name angular.Module#config
12413            * @module ng
12414            * @param {Function} configFn Execute this function on module load. Useful for service
12415            *    configuration.
12416            * @description
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}.
12420            */
12421           config: config,
12422
12423           /**
12424            * @ngdoc method
12425            * @name angular.Module#run
12426            * @module ng
12427            * @param {Function} initializationFn Execute this function after injector creation.
12428            *    Useful for application initialization.
12429            * @description
12430            * Use this method to register work which should be performed when the injector is done
12431            * loading all modules.
12432            */
12433           run: function(block) {
12434             runBlocks.push(block);
12435             return this;
12436           }
12437         };
12438
12439         if (configFn) {
12440           config(configFn);
12441         }
12442
12443         return moduleInstance;
12444
12445         /**
12446          * @param {string} provider
12447          * @param {string} method
12448          * @param {String=} insertMethod
12449          * @returns {angular.Module}
12450          */
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;
12456           };
12457         }
12458
12459         /**
12460          * @param {string} provider
12461          * @param {string} method
12462          * @returns {angular.Module}
12463          */
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;
12469           };
12470         }
12471       });
12472     };
12473   });
12474
12475 }
12476
12477 /* global shallowCopy: true */
12478
12479 /**
12480  * Creates a shallow copy of an object, an array or a primitive.
12481  *
12482  * Assumes that there are no proto properties for objects.
12483  */
12484 function shallowCopy(src, dst) {
12485   if (isArray(src)) {
12486     dst = dst || [];
12487
12488     for (var i = 0, ii = src.length; i < ii; i++) {
12489       dst[i] = src[i];
12490     }
12491   } else if (isObject(src)) {
12492     dst = dst || {};
12493
12494     for (var key in src) {
12495       if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
12496         dst[key] = src[key];
12497       }
12498     }
12499   }
12500
12501   return dst || src;
12502 }
12503
12504 /* global toDebugString: true */
12505
12506 function serializeObject(obj) {
12507   var seen = [];
12508
12509   return JSON.stringify(obj, function(key, val) {
12510     val = toJsonReplacer(key, val);
12511     if (isObject(val)) {
12512
12513       if (seen.indexOf(val) >= 0) return '...';
12514
12515       seen.push(val);
12516     }
12517     return val;
12518   });
12519 }
12520
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);
12528   }
12529   return obj;
12530 }
12531
12532 /* global angularModule: true,
12533   version: true,
12534
12535   $CompileProvider,
12536
12537   htmlAnchorDirective,
12538   inputDirective,
12539   inputDirective,
12540   formDirective,
12541   scriptDirective,
12542   selectDirective,
12543   optionDirective,
12544   ngBindDirective,
12545   ngBindHtmlDirective,
12546   ngBindTemplateDirective,
12547   ngClassDirective,
12548   ngClassEvenDirective,
12549   ngClassOddDirective,
12550   ngCloakDirective,
12551   ngControllerDirective,
12552   ngFormDirective,
12553   ngHideDirective,
12554   ngIfDirective,
12555   ngIncludeDirective,
12556   ngIncludeFillContentDirective,
12557   ngInitDirective,
12558   ngNonBindableDirective,
12559   ngPluralizeDirective,
12560   ngRepeatDirective,
12561   ngShowDirective,
12562   ngStyleDirective,
12563   ngSwitchDirective,
12564   ngSwitchWhenDirective,
12565   ngSwitchDefaultDirective,
12566   ngOptionsDirective,
12567   ngTranscludeDirective,
12568   ngModelDirective,
12569   ngListDirective,
12570   ngChangeDirective,
12571   patternDirective,
12572   patternDirective,
12573   requiredDirective,
12574   requiredDirective,
12575   minlengthDirective,
12576   minlengthDirective,
12577   maxlengthDirective,
12578   maxlengthDirective,
12579   ngValueDirective,
12580   ngModelOptionsDirective,
12581   ngAttributeAliasDirectives,
12582   ngEventDirectives,
12583
12584   $AnchorScrollProvider,
12585   $AnimateProvider,
12586   $CoreAnimateCssProvider,
12587   $$CoreAnimateJsProvider,
12588   $$CoreAnimateQueueProvider,
12589   $$AnimateRunnerFactoryProvider,
12590   $$AnimateAsyncRunFactoryProvider,
12591   $BrowserProvider,
12592   $CacheFactoryProvider,
12593   $ControllerProvider,
12594   $DateProvider,
12595   $DocumentProvider,
12596   $ExceptionHandlerProvider,
12597   $FilterProvider,
12598   $$ForceReflowProvider,
12599   $InterpolateProvider,
12600   $IntervalProvider,
12601   $$HashMapProvider,
12602   $HttpProvider,
12603   $HttpParamSerializerProvider,
12604   $HttpParamSerializerJQLikeProvider,
12605   $HttpBackendProvider,
12606   $xhrFactoryProvider,
12607   $jsonpCallbacksProvider,
12608   $LocationProvider,
12609   $LogProvider,
12610   $ParseProvider,
12611   $RootScopeProvider,
12612   $QProvider,
12613   $$QProvider,
12614   $$SanitizeUriProvider,
12615   $SceProvider,
12616   $SceDelegateProvider,
12617   $SnifferProvider,
12618   $TemplateCacheProvider,
12619   $TemplateRequestProvider,
12620   $$TestabilityProvider,
12621   $TimeoutProvider,
12622   $$RAFProvider,
12623   $WindowProvider,
12624   $$jqLiteProvider,
12625   $$CookieReaderProvider
12626 */
12627
12628
12629 /**
12630  * @ngdoc object
12631  * @name angular.version
12632  * @module ng
12633  * @description
12634  * An object that contains information about the current AngularJS version.
12635  *
12636  * This object has the following properties:
12637  *
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".
12643  */
12644 var version = {
12645   // These placeholder strings will be replaced by grunt's `build` task.
12646   // They need to be double- or single-quoted.
12647   full: '1.5.11',
12648   major: 1,
12649   minor: 5,
12650   dot: 11,
12651   codeName: 'princely-quest'
12652 };
12653
12654
12655 function publishExternalAPI(angular) {
12656   extend(angular, {
12657     'bootstrap': bootstrap,
12658     'copy': copy,
12659     'extend': extend,
12660     'merge': merge,
12661     'equals': equals,
12662     'element': jqLite,
12663     'forEach': forEach,
12664     'injector': createInjector,
12665     'noop': noop,
12666     'bind': bind,
12667     'toJson': toJson,
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,
12679     'isDate': isDate,
12680     'lowercase': lowercase,
12681     'uppercase': uppercase,
12682     'callbacks': {$$counter: 0},
12683     'getTestability': getTestability,
12684     '$$minErr': minErr,
12685     '$$csp': csp,
12686     'reloadWithDebugInfo': reloadWithDebugInfo
12687   });
12688
12689   angularModule = setupModuleLoader(window);
12690
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
12696       });
12697       $provide.provider('$compile', $CompileProvider).
12698         directive({
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
12742         }).
12743         directive({
12744           ngInclude: ngIncludeFillContentDirective
12745         }).
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,
12775         $q: $QProvider,
12776         $$q: $$QProvider,
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
12789       });
12790     }
12791   ]);
12792 }
12793
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.                          *
12799  *                                                                         *
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  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
12804
12805 /* global JQLitePrototype: true,
12806   addEventListenerFn: true,
12807   removeEventListenerFn: true,
12808   BOOLEAN_ATTR: true,
12809   ALIASED_ATTR: true
12810 */
12811
12812 //////////////////////////////////
12813 //JQLite
12814 //////////////////////////////////
12815
12816 /**
12817  * @ngdoc function
12818  * @name angular.element
12819  * @module ng
12820  * @kind function
12821  *
12822  * @description
12823  * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
12824  *
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**.
12828  *
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.
12832  *
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.
12836  *
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>
12839  *
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>
12843  *
12844  * ## Angular's jqLite
12845  * jqLite provides only the following jQuery methods:
12846  *
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/)
12883  *
12884  * ## jQuery/jqLite Extras
12885  * Angular also provides the following additional methods and events to both jQuery and jqLite:
12886  *
12887  * ### Events
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.
12891  *
12892  * ### Methods
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.
12896  *   `'ngModel'`).
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
12900  *   be enabled.
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.
12907  *
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.
12910  *
12911  * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
12912  * @returns {Object} jQuery object.
12913  */
12914
12915 JQLite.expando = 'ng339';
12916
12917 var jqCache = JQLite.cache = {},
12918     jqId = 1,
12919     addEventListenerFn = function(element, type, fn) {
12920       element.addEventListener(type, fn, false);
12921     },
12922     removeEventListenerFn = function(element, type, fn) {
12923       element.removeEventListener(type, fn, false);
12924     };
12925
12926 /*
12927  * !!! This is an undocumented "private" function !!!
12928  */
12929 JQLite._data = function(node) {
12930   //jQuery always returns an object on cache miss
12931   return this.cache[node[this.expando]] || {};
12932 };
12933
12934 function jqNextId() { return ++jqId; }
12935
12936
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');
12941
12942 /**
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
12946  */
12947 function camelCase(name) {
12948   return name.
12949     replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
12950       return offset ? letter.toUpperCase() : letter;
12951     }).
12952     replace(MOZ_HACK_REGEXP, 'Moz$1');
12953 }
12954
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;
12959
12960 var wrapMap = {
12961   'option': [1, '<select multiple="multiple">', '</select>'],
12962
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, '', '']
12968 };
12969
12970 wrapMap.optgroup = wrapMap.option;
12971 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
12972 wrapMap.th = wrapMap.td;
12973
12974
12975 function jqLiteIsTextNode(html) {
12976   return !HTML_REGEXP.test(html);
12977 }
12978
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;
12984 }
12985
12986 function jqLiteHasData(node) {
12987   for (var key in jqCache[node.ng339]) {
12988     return true;
12989   }
12990   return false;
12991 }
12992
12993 function jqLiteCleanData(nodes) {
12994   for (var i = 0, ii = nodes.length; i < ii; i++) {
12995     jqLiteRemoveData(nodes[i]);
12996   }
12997 }
12998
12999 function jqLiteBuildFragment(html, context) {
13000   var tmp, tag, wrap,
13001       fragment = context.createDocumentFragment(),
13002       nodes = [], i;
13003
13004   if (jqLiteIsTextNode(html)) {
13005     // Convert non-html into a text node
13006     nodes.push(context.createTextNode(html));
13007   } else {
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];
13013
13014     // Descend through wrappers to the right content
13015     i = wrap[0];
13016     while (i--) {
13017       tmp = tmp.lastChild;
13018     }
13019
13020     nodes = concat(nodes, tmp.childNodes);
13021
13022     tmp = fragment.firstChild;
13023     tmp.textContent = '';
13024   }
13025
13026   // Remove wrapper from fragment
13027   fragment.textContent = '';
13028   fragment.innerHTML = ''; // Clear inner HTML
13029   forEach(nodes, function(node) {
13030     fragment.appendChild(node);
13031   });
13032
13033   return fragment;
13034 }
13035
13036 function jqLiteParseHTML(html, context) {
13037   context = context || window.document;
13038   var parsed;
13039
13040   if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
13041     return [context.createElement(parsed[1])];
13042   }
13043
13044   if ((parsed = jqLiteBuildFragment(html, context))) {
13045     return parsed.childNodes;
13046   }
13047
13048   return [];
13049 }
13050
13051 function jqLiteWrapNode(node, wrapper) {
13052   var parent = node.parentNode;
13053
13054   if (parent) {
13055     parent.replaceChild(wrapper, node);
13056   }
13057
13058   wrapper.appendChild(node);
13059 }
13060
13061
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);
13066 };
13067
13068 /////////////////////////////////////////////
13069 function JQLite(element) {
13070   if (element instanceof JQLite) {
13071     return element;
13072   }
13073
13074   var argIsString;
13075
13076   if (isString(element)) {
13077     element = trim(element);
13078     argIsString = true;
13079   }
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');
13083     }
13084     return new JQLite(element);
13085   }
13086
13087   if (argIsString) {
13088     jqLiteAddNodes(this, jqLiteParseHTML(element));
13089   } else {
13090     jqLiteAddNodes(this, element);
13091   }
13092 }
13093
13094 function jqLiteClone(element) {
13095   return element.cloneNode(true);
13096 }
13097
13098 function jqLiteDealoc(element, onlyDescendants) {
13099   if (!onlyDescendants) jqLiteRemoveData(element);
13100
13101   if (element.querySelectorAll) {
13102     var descendants = element.querySelectorAll('*');
13103     for (var i = 0, l = descendants.length; i < l; i++) {
13104       jqLiteRemoveData(descendants[i]);
13105     }
13106   }
13107 }
13108
13109 function jqLiteOff(element, type, fn, unsupported) {
13110   if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
13111
13112   var expandoStore = jqLiteExpandoStore(element);
13113   var events = expandoStore && expandoStore.events;
13114   var handle = expandoStore && expandoStore.handle;
13115
13116   if (!handle) return; //no listeners registered
13117
13118   if (!type) {
13119     for (type in events) {
13120       if (type !== '$destroy') {
13121         removeEventListenerFn(element, type, handle);
13122       }
13123       delete events[type];
13124     }
13125   } else {
13126
13127     var removeHandler = function(type) {
13128       var listenerFns = events[type];
13129       if (isDefined(fn)) {
13130         arrayRemove(listenerFns || [], fn);
13131       }
13132       if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
13133         removeEventListenerFn(element, type, handle);
13134         delete events[type];
13135       }
13136     };
13137
13138     forEach(type.split(' '), function(type) {
13139       removeHandler(type);
13140       if (MOUSE_EVENT_MAP[type]) {
13141         removeHandler(MOUSE_EVENT_MAP[type]);
13142       }
13143     });
13144   }
13145 }
13146
13147 function jqLiteRemoveData(element, name) {
13148   var expandoId = element.ng339;
13149   var expandoStore = expandoId && jqCache[expandoId];
13150
13151   if (expandoStore) {
13152     if (name) {
13153       delete expandoStore.data[name];
13154       return;
13155     }
13156
13157     if (expandoStore.handle) {
13158       if (expandoStore.events.$destroy) {
13159         expandoStore.handle({}, '$destroy');
13160       }
13161       jqLiteOff(element);
13162     }
13163     delete jqCache[expandoId];
13164     element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
13165   }
13166 }
13167
13168
13169 function jqLiteExpandoStore(element, createIfNecessary) {
13170   var expandoId = element.ng339,
13171       expandoStore = expandoId && jqCache[expandoId];
13172
13173   if (createIfNecessary && !expandoStore) {
13174     element.ng339 = expandoId = jqNextId();
13175     expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
13176   }
13177
13178   return expandoStore;
13179 }
13180
13181
13182 function jqLiteData(element, key, value) {
13183   if (jqLiteAcceptsData(element)) {
13184
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;
13190
13191     if (isSimpleSetter) { // data('key', value)
13192       data[key] = value;
13193     } else {
13194       if (massGetter) {  // data()
13195         return data;
13196       } else {
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})
13201           extend(data, key);
13202         }
13203       }
13204     }
13205   }
13206 }
13207
13208 function jqLiteHasClass(element, selector) {
13209   if (!element.getAttribute) return false;
13210   return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
13211       indexOf(' ' + selector + ' ') > -1);
13212 }
13213
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) + ' ', ' '))
13221       );
13222     });
13223   }
13224 }
13225
13226 function jqLiteAddClass(element, cssClasses) {
13227   if (cssClasses && element.setAttribute) {
13228     var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
13229                             .replace(/[\n\t]/g, ' ');
13230
13231     forEach(cssClasses.split(' '), function(cssClass) {
13232       cssClass = trim(cssClass);
13233       if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
13234         existingClasses += cssClass + ' ';
13235       }
13236     });
13237
13238     element.setAttribute('class', trim(existingClasses));
13239   }
13240 }
13241
13242
13243 function jqLiteAddNodes(root, elements) {
13244   // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
13245
13246   if (elements) {
13247
13248     // if a Node (the most common case)
13249     if (elements.nodeType) {
13250       root[root.length++] = elements;
13251     } else {
13252       var length = elements.length;
13253
13254       // if an Array or NodeList and not a Window
13255       if (typeof length === 'number' && elements.window !== elements) {
13256         if (length) {
13257           for (var i = 0; i < length; i++) {
13258             root[root.length++] = elements[i];
13259           }
13260         }
13261       } else {
13262         root[root.length++] = elements;
13263       }
13264     }
13265   }
13266 }
13267
13268
13269 function jqLiteController(element, name) {
13270   return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
13271 }
13272
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;
13278   }
13279   var names = isArray(name) ? name : [name];
13280
13281   while (element) {
13282     for (var i = 0, ii = names.length; i < ii; i++) {
13283       if (isDefined(value = jqLite.data(element, names[i]))) return value;
13284     }
13285
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);
13290   }
13291 }
13292
13293 function jqLiteEmpty(element) {
13294   jqLiteDealoc(element, true);
13295   while (element.firstChild) {
13296     element.removeChild(element.firstChild);
13297   }
13298 }
13299
13300 function jqLiteRemove(element, keepData) {
13301   if (!keepData) jqLiteDealoc(element);
13302   var parent = element.parentNode;
13303   if (parent) parent.removeChild(element);
13304 }
13305
13306
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);
13314   } else {
13315     // No need to unbind this handler as load is only ever called once
13316     jqLite(win).on('load', action);
13317   }
13318 }
13319
13320 //////////////////////////////////////////
13321 // Functions which are declared directly.
13322 //////////////////////////////////////////
13323 var JQLitePrototype = JQLite.prototype = {
13324   ready: function(fn) {
13325     var fired = false;
13326
13327     function trigger() {
13328       if (fired) return;
13329       fired = true;
13330       fn();
13331     }
13332
13333     // check if document is already loaded
13334     if (window.document.readyState === 'complete') {
13335       window.setTimeout(trigger);
13336     } else {
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
13341     }
13342   },
13343   toString: function() {
13344     var value = [];
13345     forEach(this, function(e) { value.push('' + e);});
13346     return '[' + value.join(', ') + ']';
13347   },
13348
13349   eq: function(index) {
13350       return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
13351   },
13352
13353   length: 0,
13354   push: push,
13355   sort: [].sort,
13356   splice: [].splice
13357 };
13358
13359 //////////////////////////////////////////
13360 // Functions iterating getter/setters.
13361 // these functions return self on setter and
13362 // value on get.
13363 //////////////////////////////////////////
13364 var BOOLEAN_ATTR = {};
13365 forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
13366   BOOLEAN_ATTR[lowercase(value)] = value;
13367 });
13368 var BOOLEAN_ELEMENTS = {};
13369 forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
13370   BOOLEAN_ELEMENTS[value] = true;
13371 });
13372 var ALIASED_ATTR = {
13373   'ngMinlength': 'minlength',
13374   'ngMaxlength': 'maxlength',
13375   'ngMin': 'min',
13376   'ngMax': 'max',
13377   'ngPattern': 'pattern'
13378 };
13379
13380 function getBooleanAttrName(element, name) {
13381   // check dom last since we will most likely fail on name
13382   var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
13383
13384   // booleanAttr is here twice to minimize DOM access
13385   return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
13386 }
13387
13388 function getAliasedAttrName(name) {
13389   return ALIASED_ATTR[name];
13390 }
13391
13392 forEach({
13393   data: jqLiteData,
13394   removeData: jqLiteRemoveData,
13395   hasData: jqLiteHasData,
13396   cleanData: jqLiteCleanData
13397 }, function(fn, name) {
13398   JQLite[name] = fn;
13399 });
13400
13401 forEach({
13402   data: jqLiteData,
13403   inheritedData: jqLiteInheritedData,
13404
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']);
13408   },
13409
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');
13413   },
13414
13415   controller: jqLiteController,
13416
13417   injector: function(element) {
13418     return jqLiteInheritedData(element, '$injector');
13419   },
13420
13421   removeAttr: function(element, name) {
13422     element.removeAttribute(name);
13423   },
13424
13425   hasClass: jqLiteHasClass,
13426
13427   css: function(element, name, value) {
13428     name = camelCase(name);
13429
13430     if (isDefined(value)) {
13431       element.style[name] = value;
13432     } else {
13433       return element.style[name];
13434     }
13435   },
13436
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) {
13440       return;
13441     }
13442     var lowercasedName = lowercase(name);
13443     if (BOOLEAN_ATTR[lowercasedName]) {
13444       if (isDefined(value)) {
13445         if (value) {
13446           element[name] = true;
13447           element.setAttribute(name, lowercasedName);
13448         } else {
13449           element[name] = false;
13450           element.removeAttribute(lowercasedName);
13451         }
13452       } else {
13453         return (element[name] ||
13454                  (element.attributes.getNamedItem(name) || noop).specified)
13455                ? lowercasedName
13456                : undefined;
13457       }
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;
13466     }
13467   },
13468
13469   prop: function(element, name, value) {
13470     if (isDefined(value)) {
13471       element[name] = value;
13472     } else {
13473       return element[name];
13474     }
13475   },
13476
13477   text: (function() {
13478     getText.$dv = '';
13479     return getText;
13480
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 : '';
13485       }
13486       element.textContent = value;
13487     }
13488   })(),
13489
13490   val: function(element, value) {
13491     if (isUndefined(value)) {
13492       if (element.multiple && nodeName_(element) === 'select') {
13493         var result = [];
13494         forEach(element.options, function(option) {
13495           if (option.selected) {
13496             result.push(option.value || option.text);
13497           }
13498         });
13499         return result.length === 0 ? null : result;
13500       }
13501       return element.value;
13502     }
13503     element.value = value;
13504   },
13505
13506   html: function(element, value) {
13507     if (isUndefined(value)) {
13508       return element.innerHTML;
13509     }
13510     jqLiteDealoc(element, true);
13511     element.innerHTML = value;
13512   },
13513
13514   empty: jqLiteEmpty
13515 }, function(fn, name) {
13516   /**
13517    * Properties: writes return selection, reads return first value
13518    */
13519   JQLite.prototype[name] = function(arg1, arg2) {
13520     var i, key;
13521     var nodeCount = this.length;
13522
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)) {
13529
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
13534             fn(this[i], arg1);
13535           } else {
13536             for (key in arg1) {
13537               fn(this[i], key, arg1[key]);
13538             }
13539           }
13540         }
13541         // return self for chaining
13542         return this;
13543       } else {
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;
13552         }
13553         return value;
13554       }
13555     } else {
13556       // we are a write, so apply to all children
13557       for (i = 0; i < nodeCount; i++) {
13558         fn(this[i], arg1, arg2);
13559       }
13560       // return self for chaining
13561       return this;
13562     }
13563   };
13564 });
13565
13566 function createEventHandler(element, events) {
13567   var eventHandler = function(event, type) {
13568     // jQuery specific api
13569     event.isDefaultPrevented = function() {
13570       return event.defaultPrevented;
13571     };
13572
13573     var eventFns = events[type || event.type];
13574     var eventFnsLength = eventFns ? eventFns.length : 0;
13575
13576     if (!eventFnsLength) return;
13577
13578     if (isUndefined(event.immediatePropagationStopped)) {
13579       var originalStopImmediatePropagation = event.stopImmediatePropagation;
13580       event.stopImmediatePropagation = function() {
13581         event.immediatePropagationStopped = true;
13582
13583         if (event.stopPropagation) {
13584           event.stopPropagation();
13585         }
13586
13587         if (originalStopImmediatePropagation) {
13588           originalStopImmediatePropagation.call(event);
13589         }
13590       };
13591     }
13592
13593     event.isImmediatePropagationStopped = function() {
13594       return event.immediatePropagationStopped === true;
13595     };
13596
13597     // Some events have special handlers that wrap the real handler
13598     var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
13599
13600     // Copy event handlers in case event handlers array is modified during execution.
13601     if ((eventFnsLength > 1)) {
13602       eventFns = shallowCopy(eventFns);
13603     }
13604
13605     for (var i = 0; i < eventFnsLength; i++) {
13606       if (!event.isImmediatePropagationStopped()) {
13607         handlerWrapper(element, event, eventFns[i]);
13608       }
13609     }
13610   };
13611
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;
13616 }
13617
13618 function defaultHandlerWrapper(element, event, handler) {
13619   handler.call(element, event);
13620 }
13621
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);
13631   }
13632 }
13633
13634 //////////////////////////////////////////
13635 // Functions iterating traversal.
13636 // These functions chain results into a single
13637 // selector.
13638 //////////////////////////////////////////
13639 forEach({
13640   removeData: jqLiteRemoveData,
13641
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');
13644
13645     // Do not add event handlers to non-elements because they will not be cleaned up.
13646     if (!jqLiteAcceptsData(element)) {
13647       return;
13648     }
13649
13650     var expandoStore = jqLiteExpandoStore(element, true);
13651     var events = expandoStore.events;
13652     var handle = expandoStore.handle;
13653
13654     if (!handle) {
13655       handle = expandoStore.handle = createEventHandler(element, events);
13656     }
13657
13658     // http://jsperf.com/string-indexof-vs-split
13659     var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
13660     var i = types.length;
13661
13662     var addHandler = function(type, specialHandlerWrapper, noEventListener) {
13663       var eventFns = events[type];
13664
13665       if (!eventFns) {
13666         eventFns = events[type] = [];
13667         eventFns.specialHandlerWrapper = specialHandlerWrapper;
13668         if (type !== '$destroy' && !noEventListener) {
13669           addEventListenerFn(element, type, handle);
13670         }
13671       }
13672
13673       eventFns.push(fn);
13674     };
13675
13676     while (i--) {
13677       type = types[i];
13678       if (MOUSE_EVENT_MAP[type]) {
13679         addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
13680         addHandler(type, undefined, true);
13681       } else {
13682         addHandler(type);
13683       }
13684     }
13685   },
13686
13687   off: jqLiteOff,
13688
13689   one: function(element, type, fn) {
13690     element = jqLite(element);
13691
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);
13698     });
13699     element.on(type, fn);
13700   },
13701
13702   replaceWith: function(element, replaceNode) {
13703     var index, parent = element.parentNode;
13704     jqLiteDealoc(element);
13705     forEach(new JQLite(replaceNode), function(node) {
13706       if (index) {
13707         parent.insertBefore(node, index.nextSibling);
13708       } else {
13709         parent.replaceChild(node, element);
13710       }
13711       index = node;
13712     });
13713   },
13714
13715   children: function(element) {
13716     var children = [];
13717     forEach(element.childNodes, function(element) {
13718       if (element.nodeType === NODE_TYPE_ELEMENT) {
13719         children.push(element);
13720       }
13721     });
13722     return children;
13723   },
13724
13725   contents: function(element) {
13726     return element.contentDocument || element.childNodes || [];
13727   },
13728
13729   append: function(element, node) {
13730     var nodeType = element.nodeType;
13731     if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
13732
13733     node = new JQLite(node);
13734
13735     for (var i = 0, ii = node.length; i < ii; i++) {
13736       var child = node[i];
13737       element.appendChild(child);
13738     }
13739   },
13740
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);
13746       });
13747     }
13748   },
13749
13750   wrap: function(element, wrapNode) {
13751     jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
13752   },
13753
13754   remove: jqLiteRemove,
13755
13756   detach: function(element) {
13757     jqLiteRemove(element, true);
13758   },
13759
13760   after: function(element, newElement) {
13761     var index = element, parent = element.parentNode;
13762
13763     if (parent) {
13764       newElement = new JQLite(newElement);
13765
13766       for (var i = 0, ii = newElement.length; i < ii; i++) {
13767         var node = newElement[i];
13768         parent.insertBefore(node, index.nextSibling);
13769         index = node;
13770       }
13771     }
13772   },
13773
13774   addClass: jqLiteAddClass,
13775   removeClass: jqLiteRemoveClass,
13776
13777   toggleClass: function(element, selector, condition) {
13778     if (selector) {
13779       forEach(selector.split(' '), function(className) {
13780         var classCondition = condition;
13781         if (isUndefined(classCondition)) {
13782           classCondition = !jqLiteHasClass(element, className);
13783         }
13784         (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
13785       });
13786     }
13787   },
13788
13789   parent: function(element) {
13790     var parent = element.parentNode;
13791     return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
13792   },
13793
13794   next: function(element) {
13795     return element.nextElementSibling;
13796   },
13797
13798   find: function(element, selector) {
13799     if (element.getElementsByTagName) {
13800       return element.getElementsByTagName(selector);
13801     } else {
13802       return [];
13803     }
13804   },
13805
13806   clone: jqLiteClone,
13807
13808   triggerHandler: function(element, event, extraParameters) {
13809
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];
13815
13816     if (eventFns) {
13817       // Create a dummy event to pass to the handlers
13818       dummyEvent = {
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,
13824         type: eventName,
13825         target: element
13826       };
13827
13828       // If a custom event was provided then extend our dummy event with it
13829       if (event.type) {
13830         dummyEvent = extend(dummyEvent, event);
13831       }
13832
13833       // Copy event handlers in case event handlers array is modified during execution.
13834       eventFnsCopy = shallowCopy(eventFns);
13835       handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
13836
13837       forEach(eventFnsCopy, function(fn) {
13838         if (!dummyEvent.isImmediatePropagationStopped()) {
13839           fn.apply(element, handlerArgs);
13840         }
13841       });
13842     }
13843   }
13844 }, function(fn, name) {
13845   /**
13846    * chaining functions
13847    */
13848   JQLite.prototype[name] = function(arg1, arg2, arg3) {
13849     var value;
13850
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);
13857         }
13858       } else {
13859         jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
13860       }
13861     }
13862     return isDefined(value) ? value : this;
13863   };
13864 });
13865
13866 // bind legacy bind/unbind to on/off
13867 JQLite.prototype.bind = JQLite.prototype.on;
13868 JQLite.prototype.unbind = JQLite.prototype.off;
13869
13870
13871 // Provider for private $$jqLite service
13872 /** @this */
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);
13879       },
13880       addClass: function(node, classes) {
13881         if (node.attr) node = node[0];
13882         return jqLiteAddClass(node, classes);
13883       },
13884       removeClass: function(node, classes) {
13885         if (node.attr) node = node[0];
13886         return jqLiteRemoveClass(node, classes);
13887       }
13888     });
13889   };
13890 }
13891
13892 /**
13893  * Computes a hash of an 'obj'.
13894  * Hash of a:
13895  *  string is string
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.
13899  *
13900  * @param obj
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.
13903  */
13904 function hashKey(obj, nextUidFn) {
13905   var key = obj && obj.$$hashKey;
13906
13907   if (key) {
13908     if (typeof key === 'function') {
13909       key = obj.$$hashKey();
13910     }
13911     return key;
13912   }
13913
13914   var objType = typeof obj;
13915   if (objType === 'function' || (objType === 'object' && obj !== null)) {
13916     key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
13917   } else {
13918     key = objType + ':' + obj;
13919   }
13920
13921   return key;
13922 }
13923
13924 /**
13925  * HashMap which can use objects as keys
13926  */
13927 function HashMap(array, isolatedUid) {
13928   if (isolatedUid) {
13929     var uid = 0;
13930     this.nextUid = function() {
13931       return ++uid;
13932     };
13933   }
13934   forEach(array, this.put, this);
13935 }
13936 HashMap.prototype = {
13937   /**
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
13941    */
13942   put: function(key, value) {
13943     this[hashKey(key, this.nextUid)] = value;
13944   },
13945
13946   /**
13947    * @param key
13948    * @returns {Object} the value for the key
13949    */
13950   get: function(key) {
13951     return this[hashKey(key, this.nextUid)];
13952   },
13953
13954   /**
13955    * Remove the key/value pair
13956    * @param key
13957    */
13958   remove: function(key) {
13959     var value = this[key = hashKey(key, this.nextUid)];
13960     delete this[key];
13961     return value;
13962   }
13963 };
13964
13965 var $$HashMapProvider = [/** @this */function() {
13966   this.$get = [function() {
13967     return HashMap;
13968   }];
13969 }];
13970
13971 /**
13972  * @ngdoc function
13973  * @module ng
13974  * @name angular.injector
13975  * @kind function
13976  *
13977  * @description
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}).
13980  *
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}.
13986  *
13987  * @example
13988  * Typical usage
13989  * ```js
13990  *   // create an injector
13991  *   var $injector = angular.injector(['ng']);
13992  *
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();
13998  *   });
13999  * ```
14000  *
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}.
14005  *
14006  * *This is fairly rare but could be the case if a third party library is injecting the
14007  * markup.*
14008  *
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.
14012  *
14013  * ```js
14014  * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
14015  * $(document.body).append($div);
14016  *
14017  * angular.element(document).injector().invoke(function($compile) {
14018  *   var scope = angular.element($div).scope();
14019  *   $compile($div)(scope);
14020  * });
14021  * ```
14022  */
14023
14024
14025 /**
14026  * @ngdoc module
14027  * @name auto
14028  * @installation
14029  * @description
14030  *
14031  * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
14032  */
14033
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');
14040
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) + ' ';
14047 }
14048
14049 function extractArgs(fn) {
14050   var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
14051       args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
14052   return args;
14053 }
14054
14055 function anonFn(fn) {
14056   // For anonymous functions, showing at the very least the function signature can help in
14057   // debugging.
14058   var args = extractArgs(fn);
14059   if (args) {
14060     return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
14061   }
14062   return 'fn';
14063 }
14064
14065 function annotate(fn, strictDi, name) {
14066   var $inject,
14067       argDecl,
14068       last;
14069
14070   if (typeof fn === 'function') {
14071     if (!($inject = fn.$inject)) {
14072       $inject = [];
14073       if (fn.length) {
14074         if (strictDi) {
14075           if (!isString(name) || !name) {
14076             name = fn.name || anonFn(fn);
14077           }
14078           throw $injectorMinErr('strictdi',
14079             '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
14080         }
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);
14085           });
14086         });
14087       }
14088       fn.$inject = $inject;
14089     }
14090   } else if (isArray(fn)) {
14091     last = fn.length - 1;
14092     assertArgFn(fn[last], 'fn');
14093     $inject = fn.slice(0, last);
14094   } else {
14095     assertArgFn(fn, 'fn', true);
14096   }
14097   return $inject;
14098 }
14099
14100 ///////////////////////////////////////
14101
14102 /**
14103  * @ngdoc service
14104  * @name $injector
14105  *
14106  * @description
14107  *
14108  * `$injector` is used to retrieve object instances as defined by
14109  * {@link auto.$provide provider}, instantiate types, invoke methods,
14110  * and load modules.
14111  *
14112  * The following always holds true:
14113  *
14114  * ```js
14115  *   var $injector = angular.injector();
14116  *   expect($injector.get('$injector')).toBe($injector);
14117  *   expect($injector.invoke(function($injector) {
14118  *     return $injector;
14119  *   })).toBe($injector);
14120  * ```
14121  *
14122  * # Injection Function Annotation
14123  *
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.
14126  *
14127  * ```js
14128  *   // inferred (only works if code not minified/obfuscated)
14129  *   $injector.invoke(function(serviceA){});
14130  *
14131  *   // annotated
14132  *   function explicit(serviceA) {};
14133  *   explicit.$inject = ['serviceA'];
14134  *   $injector.invoke(explicit);
14135  *
14136  *   // inline
14137  *   $injector.invoke(['serviceA', function(serviceA){}]);
14138  * ```
14139  *
14140  * ## Inference
14141  *
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
14146  * argument names.
14147  *
14148  * ## `$inject` Annotation
14149  * By adding an `$inject` property onto a function the injection parameters can be specified.
14150  *
14151  * ## Inline
14152  * As an array of injection names, where the last item in the array is the function to call.
14153  */
14154
14155 /**
14156  * @ngdoc method
14157  * @name $injector#get
14158  *
14159  * @description
14160  * Return an instance of the service.
14161  *
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.
14165  */
14166
14167 /**
14168  * @ngdoc method
14169  * @name $injector#invoke
14170  *
14171  * @description
14172  * Invoke the method and supply the method arguments from the `$injector`.
14173  *
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.
14180  */
14181
14182 /**
14183  * @ngdoc method
14184  * @name $injector#has
14185  *
14186  * @description
14187  * Allows the user to query if the particular service exists.
14188  *
14189  * @param {string} name Name of the service to query.
14190  * @returns {boolean} `true` if injector has given service.
14191  */
14192
14193 /**
14194  * @ngdoc method
14195  * @name $injector#instantiate
14196  * @description
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.
14200  *
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`.
14205  */
14206
14207 /**
14208  * @ngdoc method
14209  * @name $injector#annotate
14210  *
14211  * @description
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
14215  * dependencies.
14216  *
14217  * # Argument names
14218  *
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
14221  * names.
14222  * ```js
14223  *   // Given
14224  *   function MyController($scope, $route) {
14225  *     // ...
14226  *   }
14227  *
14228  *   // Then
14229  *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
14230  * ```
14231  *
14232  * You can disallow this method by using strict injection mode.
14233  *
14234  * This method does not work with code minification / obfuscation. For this reason the following
14235  * annotation strategies are supported.
14236  *
14237  * # The `$inject` property
14238  *
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.
14241  * ```js
14242  *   // Given
14243  *   var MyController = function(obfuscatedScope, obfuscatedRoute) {
14244  *     // ...
14245  *   }
14246  *   // Define function dependencies
14247  *   MyController['$inject'] = ['$scope', '$route'];
14248  *
14249  *   // Then
14250  *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
14251  * ```
14252  *
14253  * # The array notation
14254  *
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:
14258  *
14259  * ```js
14260  *   // We wish to write this (not minification / obfuscation safe)
14261  *   injector.invoke(function($compile, $rootScope) {
14262  *     // ...
14263  *   });
14264  *
14265  *   // We are forced to write break inlining
14266  *   var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
14267  *     // ...
14268  *   };
14269  *   tmpFn.$inject = ['$compile', '$rootScope'];
14270  *   injector.invoke(tmpFn);
14271  *
14272  *   // To better support inline function the inline annotation is supported
14273  *   injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
14274  *     // ...
14275  *   }]);
14276  *
14277  *   // Therefore
14278  *   expect(injector.annotate(
14279  *      ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
14280  *    ).toEqual(['$compile', '$rootScope']);
14281  * ```
14282  *
14283  * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
14284  * be retrieved as described above.
14285  *
14286  * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
14287  *
14288  * @returns {Array.<string>} The names of the services which the function requires.
14289  */
14290
14291
14292
14293 /**
14294  * @ngdoc service
14295  * @name $provide
14296  *
14297  * @description
14298  *
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}.
14302  *
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.
14307  *
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**.
14311  *
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.
14316  *
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.
14331  *
14332  * See the individual methods for more information and examples.
14333  */
14334
14335 /**
14336  * @ngdoc method
14337  * @name $provide#provider
14338  * @description
14339  *
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
14342  * service.
14343  *
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}.
14347  *
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
14353  * console or not.
14354  *
14355  * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
14356                         'Provider'` key.
14357  * @param {(Object|function())} provider If the provider is:
14358  *
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`.
14363  *
14364  * @returns {Object} registered provider instance
14365
14366  * @example
14367  *
14368  * The following example shows how to create a simple event tracking service and register it using
14369  * {@link auto.$provide#provider $provide.provider()}.
14370  *
14371  * ```js
14372  *  // Define the eventTracker provider
14373  *  function EventTrackerProvider() {
14374  *    var trackingUrl = '/track';
14375  *
14376  *    // A provider method for configuring where the tracked events should been saved
14377  *    this.setTrackingUrl = function(url) {
14378  *      trackingUrl = url;
14379  *    };
14380  *
14381  *    // The service factory function
14382  *    this.$get = ['$http', function($http) {
14383  *      var trackedEvents = {};
14384  *      return {
14385  *        // Call this to track an event
14386  *        event: function(event) {
14387  *          var count = trackedEvents[event] || 0;
14388  *          count += 1;
14389  *          trackedEvents[event] = count;
14390  *          return count;
14391  *        },
14392  *        // Call this to save the tracked events to the trackingUrl
14393  *        save: function() {
14394  *          $http.post(trackingUrl, trackedEvents);
14395  *        }
14396  *      };
14397  *    }];
14398  *  }
14399  *
14400  *  describe('eventTracker', function() {
14401  *    var postSpy;
14402  *
14403  *    beforeEach(module(function($provide) {
14404  *      // Register the eventTracker provider
14405  *      $provide.provider('eventTracker', EventTrackerProvider);
14406  *    }));
14407  *
14408  *    beforeEach(module(function(eventTrackerProvider) {
14409  *      // Configure eventTracker provider
14410  *      eventTrackerProvider.setTrackingUrl('/custom-track');
14411  *    }));
14412  *
14413  *    it('tracks events', inject(function(eventTracker) {
14414  *      expect(eventTracker.event('login')).toEqual(1);
14415  *      expect(eventTracker.event('login')).toEqual(2);
14416  *    }));
14417  *
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 });
14426  *    }));
14427  *  });
14428  * ```
14429  */
14430
14431 /**
14432  * @ngdoc method
14433  * @name $provide#factory
14434  * @description
14435  *
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.
14441  *
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
14446  *
14447  * @example
14448  * Here is an example of registering a service
14449  * ```js
14450  *   $provide.factory('ping', ['$http', function($http) {
14451  *     return function ping() {
14452  *       return $http.send('/ping');
14453  *     };
14454  *   }]);
14455  * ```
14456  * You would then inject and use this service like this:
14457  * ```js
14458  *   someModule.controller('Ctrl', ['ping', function(ping) {
14459  *     ping();
14460  *   }]);
14461  * ```
14462  */
14463
14464
14465 /**
14466  * @ngdoc method
14467  * @name $provide#service
14468  * @description
14469  *
14470  * Register a **service constructor**, which will be invoked with `new` to create the service
14471  * instance.
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
14474  * function.
14475  *
14476  * Internally it looks a bit like this:
14477  *
14478  * ```
14479  * {
14480  *   $get: function() {
14481  *     return $injector.instantiate(constructor);
14482  *   }
14483  * }
14484  * ```
14485  *
14486  *
14487  * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
14488  * as a type/class.
14489  *
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
14494  *
14495  * @example
14496  * Here is an example of registering a service using
14497  * {@link auto.$provide#service $provide.service(class)}.
14498  * ```js
14499  *   var Ping = function($http) {
14500  *     this.$http = $http;
14501  *   };
14502  *
14503  *   Ping.$inject = ['$http'];
14504  *
14505  *   Ping.prototype.send = function() {
14506  *     return this.$http.get('/ping');
14507  *   };
14508  *   $provide.service('ping', Ping);
14509  * ```
14510  * You would then inject and use this service like this:
14511  * ```js
14512  *   someModule.controller('Ctrl', ['ping', function(ping) {
14513  *     ping.send();
14514  *   }]);
14515  * ```
14516  */
14517
14518
14519 /**
14520  * @ngdoc method
14521  * @name $provide#value
14522  * @description
14523  *
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.
14528  *
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}.
14532  *
14533  * @param {string} name The name of the instance.
14534  * @param {*} value The value.
14535  * @returns {Object} registered provider instance
14536  *
14537  * @example
14538  * Here are some examples of creating value services.
14539  * ```js
14540  *   $provide.value('ADMIN_USER', 'admin');
14541  *
14542  *   $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
14543  *
14544  *   $provide.value('halfOf', function(value) {
14545  *     return value / 2;
14546  *   });
14547  * ```
14548  */
14549
14550
14551 /**
14552  * @ngdoc method
14553  * @name $provide#constant
14554  * @description
14555  *
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.
14559  *
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}.
14563  *
14564  * @param {string} name The name of the constant.
14565  * @param {*} value The constant value.
14566  * @returns {Object} registered instance
14567  *
14568  * @example
14569  * Here a some examples of creating constants:
14570  * ```js
14571  *   $provide.constant('SHARD_HEIGHT', 306);
14572  *
14573  *   $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
14574  *
14575  *   $provide.constant('double', function(value) {
14576  *     return value * 2;
14577  *   });
14578  * ```
14579  */
14580
14581
14582 /**
14583  * @ngdoc method
14584  * @name $provide#decorator
14585  * @description
14586  *
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.
14591  *
14592  * You can find out more about using decorators in the {@link guide/decorators} guide.
14593  *
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:
14599  *
14600  *    * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
14601  *      decorated or delegated to.
14602  *
14603  * @example
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()}.
14606  * ```js
14607  *   $provide.decorator('$log', ['$delegate', function($delegate) {
14608  *     $delegate.warn = $delegate.error;
14609  *     return $delegate;
14610  *   }]);
14611  * ```
14612  */
14613
14614
14615 function createInjector(modulesToLoad, strictDi) {
14616   strictDi = (strictDi === true);
14617   var INSTANTIATING = {},
14618       providerSuffix = 'Provider',
14619       path = [],
14620       loadedModules = new HashMap([], true),
14621       providerCache = {
14622         $provide: {
14623             provider: supportObject(provider),
14624             factory: supportObject(factory),
14625             service: supportObject(service),
14626             value: supportObject(value),
14627             constant: supportObject(constant),
14628             decorator: decorator
14629           }
14630       },
14631       providerInjector = (providerCache.$injector =
14632           createInternalInjector(providerCache, function(serviceName, caller) {
14633             if (angular.isString(caller)) {
14634               path.push(caller);
14635             }
14636             throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
14637           })),
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);
14644           }),
14645       instanceInjector = protoInstanceInjector;
14646
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); });
14652
14653   return instanceInjector;
14654
14655   ////////////////////////////////////
14656   // $provider
14657   ////////////////////////////////////
14658
14659   function supportObject(delegate) {
14660     return function(key, value) {
14661       if (isObject(key)) {
14662         forEach(key, reverseParams(delegate));
14663       } else {
14664         return delegate(key, value);
14665       }
14666     };
14667   }
14668
14669   function provider(name, provider_) {
14670     assertNotHasOwnProperty(name, 'service');
14671     if (isFunction(provider_) || isArray(provider_)) {
14672       provider_ = providerInjector.instantiate(provider_);
14673     }
14674     if (!provider_.$get) {
14675       throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
14676     }
14677     return (providerCache[name + providerSuffix] = provider_);
14678   }
14679
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);
14685       }
14686       return result;
14687     };
14688   }
14689
14690   function factory(name, factoryFn, enforce) {
14691     return provider(name, {
14692       $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
14693     });
14694   }
14695
14696   function service(name, constructor) {
14697     return factory(name, ['$injector', function($injector) {
14698       return $injector.instantiate(constructor);
14699     }]);
14700   }
14701
14702   function value(name, val) { return factory(name, valueFn(val), false); }
14703
14704   function constant(name, value) {
14705     assertNotHasOwnProperty(name, 'constant');
14706     providerCache[name] = value;
14707     instanceCache[name] = value;
14708   }
14709
14710   function decorator(serviceName, decorFn) {
14711     var origProvider = providerInjector.get(serviceName + providerSuffix),
14712         orig$get = origProvider.$get;
14713
14714     origProvider.$get = function() {
14715       var origInstance = instanceInjector.invoke(orig$get, origProvider);
14716       return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
14717     };
14718   }
14719
14720   ////////////////////////////////////
14721   // Module Loading
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);
14729
14730       function runInvokeQueue(queue) {
14731         var i, ii;
14732         for (i = 0, ii = queue.length; i < ii; i++) {
14733           var invokeArgs = queue[i],
14734               provider = providerInjector.get(invokeArgs[0]);
14735
14736           provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
14737         }
14738       }
14739
14740       try {
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));
14750         } else {
14751           assertArgFn(module, 'module');
14752         }
14753       } catch (e) {
14754         if (isArray(module)) {
14755           module = module[module.length - 1];
14756         }
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;
14764         }
14765         throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
14766                   module, e.stack || e.message || e);
14767       }
14768     });
14769     return runBlocks;
14770   }
14771
14772   ////////////////////////////////////
14773   // internal Injector
14774   ////////////////////////////////////
14775
14776   function createInternalInjector(cache, factory) {
14777
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(' <- '));
14783         }
14784         return cache[serviceName];
14785       } else {
14786         try {
14787           path.unshift(serviceName);
14788           cache[serviceName] = INSTANTIATING;
14789           cache[serviceName] = factory(serviceName, caller);
14790           return cache[serviceName];
14791         } catch (err) {
14792           if (cache[serviceName] === INSTANTIATING) {
14793             delete cache[serviceName];
14794           }
14795           throw err;
14796         } finally {
14797           path.shift();
14798         }
14799       }
14800     }
14801
14802
14803     function injectionArgs(fn, locals, serviceName) {
14804       var args = [],
14805           $inject = createInjector.$$annotate(fn, strictDi, serviceName);
14806
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);
14812         }
14813         args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
14814                                                          getService(key, serviceName));
14815       }
14816       return args;
14817     }
14818
14819     function isClass(func) {
14820       // IE 9-11 do not support classes and IE9 leaks with the code below.
14821       if (msie <= 11) {
14822         return false;
14823       }
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));
14828     }
14829
14830     function invoke(fn, self, locals, serviceName) {
14831       if (typeof locals === 'string') {
14832         serviceName = locals;
14833         locals = null;
14834       }
14835
14836       var args = injectionArgs(fn, locals, serviceName);
14837       if (isArray(fn)) {
14838         fn = fn[fn.length - 1];
14839       }
14840
14841       if (!isClass(fn)) {
14842         // http://jsperf.com/angularjs-invoke-apply-vs-switch
14843         // #5388
14844         return fn.apply(self, args);
14845       } else {
14846         args.unshift(null);
14847         return new (Function.prototype.bind.apply(fn, args))();
14848       }
14849     }
14850
14851
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))();
14860     }
14861
14862
14863     return {
14864       invoke: invoke,
14865       instantiate: instantiate,
14866       get: getService,
14867       annotate: createInjector.$$annotate,
14868       has: function(name) {
14869         return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
14870       }
14871     };
14872   }
14873 }
14874
14875 createInjector.$$annotate = annotate;
14876
14877 /**
14878  * @ngdoc provider
14879  * @name $anchorScrollProvider
14880  * @this
14881  *
14882  * @description
14883  * Use `$anchorScrollProvider` to disable automatic scrolling whenever
14884  * {@link ng.$location#hash $location.hash()} changes.
14885  */
14886 function $AnchorScrollProvider() {
14887
14888   var autoScrollingEnabled = true;
14889
14890   /**
14891    * @ngdoc method
14892    * @name $anchorScrollProvider#disableAutoScrolling
14893    *
14894    * @description
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.
14898    *
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
14901    * current hash.
14902    */
14903   this.disableAutoScrolling = function() {
14904     autoScrollingEnabled = false;
14905   };
14906
14907   /**
14908    * @ngdoc service
14909    * @name $anchorScroll
14910    * @kind function
14911    * @requires $window
14912    * @requires $location
14913    * @requires $rootScope
14914    *
14915    * @description
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
14918    * in the
14919    * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
14920    *
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()}.
14924    *
14925    * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
14926    * vertical scroll-offset (either fixed or dynamic).
14927    *
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.
14930    *
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.
14934    *
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.
14944    *
14945    * <br />
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.
14949    * </div>
14950    *
14951    * @example
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!
14957          </div>
14958        </file>
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');
14967
14968                  // call $anchorScroll()
14969                  $anchorScroll();
14970                };
14971              }]);
14972        </file>
14973        <file name="style.css">
14974          #scrollArea {
14975            height: 280px;
14976            overflow: auto;
14977          }
14978
14979          #bottom {
14980            display: block;
14981            margin-top: 2000px;
14982          }
14983        </file>
14984      </example>
14985    *
14986    * <hr />
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.
14989    *
14990    * @example
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]">
14995              Go to anchor {{x}}
14996            </a>
14997          </div>
14998          <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
14999            Anchor {{x}} of 5
15000          </div>
15001        </file>
15002        <file name="script.js">
15003          angular.module('anchorScrollOffsetExample', [])
15004            .run(['$anchorScroll', function($anchorScroll) {
15005              $anchorScroll.yOffset = 50;   // always scroll by 50 extra pixels
15006            }])
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);
15015                  } else {
15016                    // call $anchorScroll() explicitly,
15017                    // since $location.hash hasn't changed
15018                    $anchorScroll();
15019                  }
15020                };
15021              }
15022            ]);
15023        </file>
15024        <file name="style.css">
15025          body {
15026            padding-top: 50px;
15027          }
15028
15029          .anchor {
15030            border: 2px dashed DarkOrchid;
15031            padding: 10px 10px 200px 10px;
15032          }
15033
15034          .fixed-header {
15035            background-color: rgba(0, 0, 0, 0.2);
15036            height: 50px;
15037            position: fixed;
15038            top: 0; left: 0; right: 0;
15039          }
15040
15041          .fixed-header > a {
15042            display: inline-block;
15043            margin: 5px 15px;
15044          }
15045        </file>
15046      </example>
15047    */
15048   this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
15049     var document = $window.document;
15050
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) {
15055       var result = null;
15056       Array.prototype.some.call(list, function(element) {
15057         if (nodeName_(element) === 'a') {
15058           result = element;
15059           return true;
15060         }
15061       });
15062       return result;
15063     }
15064
15065     function getYOffset() {
15066
15067       var offset = scroll.yOffset;
15068
15069       if (isFunction(offset)) {
15070         offset = offset();
15071       } else if (isElement(offset)) {
15072         var elem = offset[0];
15073         var style = $window.getComputedStyle(elem);
15074         if (style.position !== 'fixed') {
15075           offset = 0;
15076         } else {
15077           offset = elem.getBoundingClientRect().bottom;
15078         }
15079       } else if (!isNumber(offset)) {
15080         offset = 0;
15081       }
15082
15083       return offset;
15084     }
15085
15086     function scrollTo(elem) {
15087       if (elem) {
15088         elem.scrollIntoView();
15089
15090         var offset = getYOffset();
15091
15092         if (offset) {
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.
15096           //
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.
15100           //
15101           // This is often the case for elements near the bottom of the page.
15102           //
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);
15108         }
15109       } else {
15110         $window.scrollTo(0, 0);
15111       }
15112     }
15113
15114     function scroll(hash) {
15115       // Allow numeric hashes
15116       hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();
15117       var elm;
15118
15119       // empty hash, scroll to the top of the page
15120       if (!hash) scrollTo(null);
15121
15122       // element with given id
15123       else if ((elm = document.getElementById(hash))) scrollTo(elm);
15124
15125       // first anchor with given name :-D
15126       else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
15127
15128       // no element and hash === 'top', scroll to the top of the page
15129       else if (hash === 'top') scrollTo(null);
15130     }
15131
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;
15139
15140           jqLiteDocumentLoaded(function() {
15141             $rootScope.$evalAsync(scroll);
15142           });
15143         });
15144     }
15145
15146     return scroll;
15147   }];
15148 }
15149
15150 var $animateMinErr = minErr('$animate');
15151 var ELEMENT_NODE = 1;
15152 var NG_ANIMATE_CLASSNAME = 'ng-animate';
15153
15154 function mergeClasses(a,b) {
15155   if (!a && !b) return '';
15156   if (!a) return b;
15157   if (!b) return a;
15158   if (isArray(a)) a = a.join(' ');
15159   if (isArray(b)) b = b.join(' ');
15160   return a + ' ' + b;
15161 }
15162
15163 function extractElementNode(element) {
15164   for (var i = 0; i < element.length; i++) {
15165     var elm = element[i];
15166     if (elm.nodeType === ELEMENT_NODE) {
15167       return elm;
15168     }
15169   }
15170 }
15171
15172 function splitClasses(classes) {
15173   if (isString(classes)) {
15174     classes = classes.split(' ');
15175   }
15176
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) {
15184       obj[klass] = true;
15185     }
15186   });
15187   return obj;
15188 }
15189
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)
15199       ? options
15200       : {};
15201 }
15202
15203 var $$CoreAnimateJsProvider = /** @this */ function() {
15204   this.$get = noop;
15205 };
15206
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 = [];
15212
15213   this.$get = ['$$AnimateRunner', '$rootScope',
15214        function($$AnimateRunner,   $rootScope) {
15215     return {
15216       enabled: noop,
15217       on: noop,
15218       off: noop,
15219       pin: noop,
15220
15221       push: function(element, event, options, domOperation) {
15222         if (domOperation) {
15223           domOperation();
15224         }
15225
15226         options = options || {};
15227         if (options.from) {
15228           element.css(options.from);
15229         }
15230         if (options.to) {
15231           element.css(options.to);
15232         }
15233
15234         if (options.addClass || options.removeClass) {
15235           addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
15236         }
15237
15238         var runner = new $$AnimateRunner();
15239
15240         // since there are no animations to run the runner needs to be
15241         // notified that the animation call is complete.
15242         runner.complete();
15243         return runner;
15244       }
15245     };
15246
15247
15248     function updateData(data, classes, value) {
15249       var changed = false;
15250       if (classes) {
15251         classes = isString(classes) ? classes.split(' ') :
15252                   isArray(classes) ? classes : [];
15253         forEach(classes, function(className) {
15254           if (className) {
15255             changed = true;
15256             data[className] = value;
15257           }
15258         });
15259       }
15260       return changed;
15261     }
15262
15263     function handleCSSClassChanges() {
15264       forEach(postDigestElements, function(element) {
15265         var data = postDigestQueue.get(element);
15266         if (data) {
15267           var existing = splitClasses(element.attr('class'));
15268           var toAdd = '';
15269           var toRemove = '';
15270           forEach(data, function(status, className) {
15271             var hasClass = !!existing[className];
15272             if (status !== hasClass) {
15273               if (status) {
15274                 toAdd += (toAdd.length ? ' ' : '') + className;
15275               } else {
15276                 toRemove += (toRemove.length ? ' ' : '') + className;
15277               }
15278             }
15279           });
15280
15281           forEach(element, function(elm) {
15282             if (toAdd) {
15283               jqLiteAddClass(elm, toAdd);
15284             }
15285             if (toRemove) {
15286               jqLiteRemoveClass(elm, toRemove);
15287             }
15288           });
15289           postDigestQueue.remove(element);
15290         }
15291       });
15292       postDigestElements.length = 0;
15293     }
15294
15295
15296     function addRemoveClassesPostDigest(element, add, remove) {
15297       var data = postDigestQueue.get(element) || {};
15298
15299       var classesAdded = updateData(data, add, true);
15300       var classesRemoved = updateData(data, remove, false);
15301
15302       if (classesAdded || classesRemoved) {
15303
15304         postDigestQueue.put(element, data);
15305         postDigestElements.push(element);
15306
15307         if (postDigestElements.length === 1) {
15308           $rootScope.$$postDigest(handleCSSClassChanges);
15309         }
15310       }
15311     }
15312   }];
15313 };
15314
15315 /**
15316  * @ngdoc provider
15317  * @name $animateProvider
15318  *
15319  * @description
15320  * Default implementation of $animate that doesn't perform any animations, instead just
15321  * synchronously performs DOM updates and resolves the returned runner promise.
15322  *
15323  * In order to enable animations the `ngAnimate` module has to be loaded.
15324  *
15325  * To see the functional implementation check out `src/ngAnimate/animate.js`.
15326  */
15327 var $AnimateProvider = ['$provide', /** @this */ function($provide) {
15328   var provider = this;
15329
15330   this.$$registeredAnimations = Object.create(null);
15331
15332    /**
15333    * @ngdoc method
15334    * @name $animateProvider#register
15335    *
15336    * @description
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
15339    * animated.
15340    *
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:
15345    *
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)
15351    *
15352    *   Make sure to trigger the `doneFunction` once the animation is fully complete.
15353    *
15354    * ```js
15355    *   return {
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
15362    *       }
15363    *     }
15364    *   }
15365    * ```
15366    *
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
15369    *                           object.
15370    */
15371   this.register = function(name, factory) {
15372     if (name && name.charAt(0) !== '.') {
15373       throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
15374     }
15375
15376     var key = name + '-animation';
15377     provider.$$registeredAnimations[name.substr(1)] = key;
15378     $provide.factory(key, factory);
15379   };
15380
15381   /**
15382    * @ngdoc method
15383    * @name $animateProvider#classNameFilter
15384    *
15385    * @description
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
15394    */
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);
15402
15403         }
15404       }
15405     }
15406     return this.$$classNameFilter;
15407   };
15408
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;
15418         }
15419       }
15420       if (afterElement) {
15421         afterElement.after(element);
15422       } else {
15423         parentElement.prepend(element);
15424       }
15425     }
15426
15427     /**
15428      * @ngdoc service
15429      * @name $animate
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.
15434      *
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.
15440      *
15441      * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
15442      *
15443      * To learn more about enabling animation support, click here to visit the
15444      * {@link ngAnimate ngAnimate module page}.
15445      */
15446     return {
15447       // we don't call it directly since non-existant arguments may
15448       // be interpreted as null within the sub enabled function
15449
15450       /**
15451        *
15452        * @ngdoc method
15453        * @name $animate#on
15454        * @kind function
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:
15458        *
15459        * ```js
15460        * $animate.on('enter', container,
15461        *    function callback(element, phase) {
15462        *      // cool we detected an enter animation within the container
15463        *    }
15464        * );
15465        * ```
15466        *
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
15471        *
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).
15475        */
15476       on: $$animateQueue.on,
15477
15478       /**
15479        *
15480        * @ngdoc method
15481        * @name $animate#off
15482        * @kind function
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:
15485        *
15486        * ```js
15487        * // remove all the animation event listeners listening for `enter`
15488        * $animate.off('enter');
15489        *
15490        * // remove listeners for all animation events from the container element
15491        * $animate.off(container);
15492        *
15493        * // remove all the animation event listeners listening for `enter` on the given element and its children
15494        * $animate.off('enter', container);
15495        *
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);
15499        * ```
15500        *
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
15506        */
15507       off: $$animateQueue.off,
15508
15509       /**
15510        * @ngdoc method
15511        * @name $animate#pin
15512        * @kind function
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.
15519        *
15520        *    Note that this feature is only active when the `ngAnimate` module is used.
15521        *
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
15524        */
15525       pin: $$animateQueue.pin,
15526
15527       /**
15528        *
15529        * @ngdoc method
15530        * @name $animate#enabled
15531        * @kind function
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:
15534        *
15535        * ```js
15536        * // returns true or false
15537        * $animate.enabled();
15538        *
15539        * // changes the enabled state for all animations
15540        * $animate.enabled(false);
15541        * $animate.enabled(true);
15542        *
15543        * // returns true or false if animations are enabled for an element
15544        * $animate.enabled(element);
15545        *
15546        * // changes the enabled state for an element and its children
15547        * $animate.enabled(element, true);
15548        * $animate.enabled(element, false);
15549        * ```
15550        *
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
15553        *
15554        * @return {boolean} whether or not animations are enabled
15555        */
15556       enabled: $$animateQueue.enabled,
15557
15558       /**
15559        * @ngdoc method
15560        * @name $animate#cancel
15561        * @kind function
15562        * @description Cancels the provided animation.
15563        *
15564        * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
15565        */
15566       cancel: function(runner) {
15567         if (runner.end) {
15568           runner.end();
15569         }
15570       },
15571
15572       /**
15573        *
15574        * @ngdoc method
15575        * @name $animate#enter
15576        * @kind function
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
15580        *   has completed.
15581        *
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:
15588        *
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`
15593        *
15594        * @return {Promise} the animation callback promise
15595        */
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));
15602       },
15603
15604       /**
15605        *
15606        * @ngdoc method
15607        * @name $animate#move
15608        * @kind function
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.
15613        *
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:
15620        *
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`
15625        *
15626        * @return {Promise} the animation callback promise
15627        */
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));
15634       },
15635
15636       /**
15637        * @ngdoc method
15638        * @name $animate#leave
15639        * @kind function
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.
15643        *
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:
15647        *
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`
15652        *
15653        * @return {Promise} the animation callback promise
15654        */
15655       leave: function(element, options) {
15656         return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
15657           element.remove();
15658         });
15659       },
15660
15661       /**
15662        * @ngdoc method
15663        * @name $animate#addClass
15664        * @kind function
15665        *
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.
15672        *
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:
15677        *
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`
15682        *
15683        * @return {Promise} the animation callback promise
15684        */
15685       addClass: function(element, className, options) {
15686         options = prepareAnimateOptions(options);
15687         options.addClass = mergeClasses(options.addclass, className);
15688         return $$animateQueue.push(element, 'addClass', options);
15689       },
15690
15691       /**
15692        * @ngdoc method
15693        * @name $animate#removeClass
15694        * @kind function
15695        *
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.
15702        *
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:
15707        *
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`
15712        *
15713        * @return {Promise} the animation callback promise
15714        */
15715       removeClass: function(element, className, options) {
15716         options = prepareAnimateOptions(options);
15717         options.removeClass = mergeClasses(options.removeClass, className);
15718         return $$animateQueue.push(element, 'removeClass', options);
15719       },
15720
15721       /**
15722        * @ngdoc method
15723        * @name $animate#setClass
15724        * @kind function
15725        *
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.
15732        *
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:
15738        *
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`
15743        *
15744        * @return {Promise} the animation callback promise
15745        */
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);
15751       },
15752
15753       /**
15754        * @ngdoc method
15755        * @name $animate#animate
15756        * @kind function
15757        *
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):
15765        *
15766        * ```js
15767        * ngModule.animation('.my-inline-animation', function() {
15768        *   return {
15769        *     animate : function(element, from, to, done, options) {
15770        *       //animation
15771        *       done();
15772        *     }
15773        *   }
15774        * });
15775        * ```
15776        *
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:
15785        *
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`
15790        *
15791        * @return {Promise} the animation callback promise
15792        */
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;
15797
15798         className = className || 'ng-inline-animate';
15799         options.tempClasses = mergeClasses(options.tempClasses, className);
15800         return $$animateQueue.push(element, 'animate', options);
15801       }
15802     };
15803   }];
15804 }];
15805
15806 var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
15807   this.$get = ['$$rAF', function($$rAF) {
15808     var waitQueue = [];
15809
15810     function waitForTick(fn) {
15811       waitQueue.push(fn);
15812       if (waitQueue.length > 1) return;
15813       $$rAF(function() {
15814         for (var i = 0; i < waitQueue.length; i++) {
15815           waitQueue[i]();
15816         }
15817         waitQueue = [];
15818       });
15819     }
15820
15821     return function() {
15822       var passed = false;
15823       waitForTick(function() {
15824         passed = true;
15825       });
15826       return function(callback) {
15827         if (passed) {
15828           callback();
15829         } else {
15830           waitForTick(callback);
15831         }
15832       };
15833     };
15834   }];
15835 };
15836
15837 var $$AnimateRunnerFactoryProvider = /** @this */ function() {
15838   this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$document', '$timeout',
15839        function($q,   $sniffer,   $$animateAsyncRun,   $document,   $timeout) {
15840
15841     var INITIAL_STATE = 0;
15842     var DONE_PENDING_STATE = 1;
15843     var DONE_COMPLETE_STATE = 2;
15844
15845     AnimateRunner.chain = function(chain, callback) {
15846       var index = 0;
15847
15848       next();
15849       function next() {
15850         if (index === chain.length) {
15851           callback(true);
15852           return;
15853         }
15854
15855         chain[index](function(response) {
15856           if (response === false) {
15857             callback(false);
15858             return;
15859           }
15860           index++;
15861           next();
15862         });
15863       }
15864     };
15865
15866     AnimateRunner.all = function(runners, callback) {
15867       var count = 0;
15868       var status = true;
15869       forEach(runners, function(runner) {
15870         runner.done(onProgress);
15871       });
15872
15873       function onProgress(response) {
15874         status = status && response;
15875         if (++count === runners.length) {
15876           callback(status);
15877         }
15878       }
15879     };
15880
15881     function AnimateRunner(host) {
15882       this.setHost(host);
15883
15884       var rafTick = $$animateAsyncRun();
15885       var timeoutTick = function(fn) {
15886         $timeout(fn, 0, false);
15887       };
15888
15889       this._doneCallbacks = [];
15890       this._tick = function(fn) {
15891         var doc = $document[0];
15892
15893         // the document may not be ready or attached
15894         // to the module for some internal tests
15895         if (doc && doc.hidden) {
15896           timeoutTick(fn);
15897         } else {
15898           rafTick(fn);
15899         }
15900       };
15901       this._state = 0;
15902     }
15903
15904     AnimateRunner.prototype = {
15905       setHost: function(host) {
15906         this.host = host || {};
15907       },
15908
15909       done: function(fn) {
15910         if (this._state === DONE_COMPLETE_STATE) {
15911           fn();
15912         } else {
15913           this._doneCallbacks.push(fn);
15914         }
15915       },
15916
15917       progress: noop,
15918
15919       getPromise: function() {
15920         if (!this.promise) {
15921           var self = this;
15922           this.promise = $q(function(resolve, reject) {
15923             self.done(function(status) {
15924               if (status === false) {
15925                 reject();
15926               } else {
15927                 resolve();
15928               }
15929             });
15930           });
15931         }
15932         return this.promise;
15933       },
15934
15935       then: function(resolveHandler, rejectHandler) {
15936         return this.getPromise().then(resolveHandler, rejectHandler);
15937       },
15938
15939       'catch': function(handler) {
15940         return this.getPromise()['catch'](handler);
15941       },
15942
15943       'finally': function(handler) {
15944         return this.getPromise()['finally'](handler);
15945       },
15946
15947       pause: function() {
15948         if (this.host.pause) {
15949           this.host.pause();
15950         }
15951       },
15952
15953       resume: function() {
15954         if (this.host.resume) {
15955           this.host.resume();
15956         }
15957       },
15958
15959       end: function() {
15960         if (this.host.end) {
15961           this.host.end();
15962         }
15963         this._resolve(true);
15964       },
15965
15966       cancel: function() {
15967         if (this.host.cancel) {
15968           this.host.cancel();
15969         }
15970         this._resolve(false);
15971       },
15972
15973       complete: function(response) {
15974         var self = this;
15975         if (self._state === INITIAL_STATE) {
15976           self._state = DONE_PENDING_STATE;
15977           self._tick(function() {
15978             self._resolve(response);
15979           });
15980         }
15981       },
15982
15983       _resolve: function(response) {
15984         if (this._state !== DONE_COMPLETE_STATE) {
15985           forEach(this._doneCallbacks, function(fn) {
15986             fn(response);
15987           });
15988           this._doneCallbacks.length = 0;
15989           this._state = DONE_COMPLETE_STATE;
15990         }
15991       }
15992     };
15993
15994     return AnimateRunner;
15995   }];
15996 };
15997
15998 /* exported $CoreAnimateCssProvider */
15999
16000 /**
16001  * @ngdoc service
16002  * @name $animateCss
16003  * @kind object
16004  * @this
16005  *
16006  * @description
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.
16009  *
16010  * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
16011  */
16012 var $CoreAnimateCssProvider = function() {
16013   this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
16014
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);
16023       }
16024
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;
16030       }
16031
16032       if (options.from) {
16033         element.css(options.from);
16034         options.from = null;
16035       }
16036
16037       var closed, runner = new $$AnimateRunner();
16038       return {
16039         start: run,
16040         end: run
16041       };
16042
16043       function run() {
16044         $$rAF(function() {
16045           applyAnimationContents();
16046           if (!closed) {
16047             runner.complete();
16048           }
16049           closed = true;
16050         });
16051         return runner;
16052       }
16053
16054       function applyAnimationContents() {
16055         if (options.addClass) {
16056           element.addClass(options.addClass);
16057           options.addClass = null;
16058         }
16059         if (options.removeClass) {
16060           element.removeClass(options.removeClass);
16061           options.removeClass = null;
16062         }
16063         if (options.to) {
16064           element.css(options.to);
16065           options.to = null;
16066         }
16067       }
16068     };
16069   }];
16070 };
16071
16072 /* global stripHash: true */
16073
16074 /**
16075  * ! This is a private undocumented service !
16076  *
16077  * @name $browser
16078  * @requires $log
16079  * @description
16080  * This object has two goals:
16081  *
16082  * - hide all the global state in the browser caused by the window object
16083  * - abstract away all the browser specific features and inconsistencies
16084  *
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.
16088  */
16089 /**
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
16094  */
16095 function Browser(window, document, $log, $sniffer) {
16096   var self = this,
16097       location = window.location,
16098       history = window.history,
16099       setTimeout = window.setTimeout,
16100       clearTimeout = window.clearTimeout,
16101       pendingDeferIds = {};
16102
16103   self.isMock = false;
16104
16105   var outstandingRequestCount = 0;
16106   var outstandingRequestCallbacks = [];
16107
16108   // TODO(vojta): remove this temporary api
16109   self.$$completeOutstandingRequest = completeOutstandingRequest;
16110   self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
16111
16112   /**
16113    * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
16114    * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
16115    */
16116   function completeOutstandingRequest(fn) {
16117     try {
16118       fn.apply(null, sliceArgs(arguments, 1));
16119     } finally {
16120       outstandingRequestCount--;
16121       if (outstandingRequestCount === 0) {
16122         while (outstandingRequestCallbacks.length) {
16123           try {
16124             outstandingRequestCallbacks.pop()();
16125           } catch (e) {
16126             $log.error(e);
16127           }
16128         }
16129       }
16130     }
16131   }
16132
16133   function getHash(url) {
16134     var index = url.indexOf('#');
16135     return index === -1 ? '' : url.substr(index);
16136   }
16137
16138   /**
16139    * @private
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
16143    */
16144   self.notifyWhenNoOutstandingRequests = function(callback) {
16145     if (outstandingRequestCount === 0) {
16146       callback();
16147     } else {
16148       outstandingRequestCallbacks.push(callback);
16149     }
16150   };
16151
16152   //////////////////////////////////////////////////////////////
16153   // URL API
16154   //////////////////////////////////////////////////////////////
16155
16156   var cachedState, lastHistoryState,
16157       lastBrowserUrl = location.href,
16158       baseElement = document.find('base'),
16159       pendingLocation = null,
16160       getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
16161         try {
16162           return history.state;
16163         } catch (e) {
16164           // MSIE can reportedly throw when there is no state (UNCONFIRMED).
16165         }
16166       };
16167
16168   cacheState();
16169   lastHistoryState = cachedState;
16170
16171   /**
16172    * @name $browser#url
16173    *
16174    * @description
16175    * GETTER:
16176    * Without any argument, this method just returns current value of location.href.
16177    *
16178    * SETTER:
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
16183    *
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.
16186    *
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
16190    */
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)) {
16196       state = null;
16197     }
16198
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;
16202
16203     // setter
16204     if (url) {
16205       var sameState = lastHistoryState === state;
16206
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)) {
16211         return self;
16212       }
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);
16222         cacheState();
16223         // Do the assignment again so that those two variables are referentially identical.
16224         lastHistoryState = cachedState;
16225       } else {
16226         if (!sameBase) {
16227           pendingLocation = url;
16228         }
16229         if (replace) {
16230           location.replace(url);
16231         } else if (!sameBase) {
16232           location.href = url;
16233         } else {
16234           location.hash = getHash(url);
16235         }
16236         if (location.href !== url) {
16237           pendingLocation = url;
16238         }
16239       }
16240       if (pendingLocation) {
16241         pendingLocation = url;
16242       }
16243       return self;
16244     // getter
16245     } else {
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,'\'');
16251     }
16252   };
16253
16254   /**
16255    * @name $browser#state
16256    *
16257    * @description
16258    * This method is a getter.
16259    *
16260    * Return history.state or null if history.state is undefined.
16261    *
16262    * @returns {object} state
16263    */
16264   self.state = function() {
16265     return cachedState;
16266   };
16267
16268   var urlChangeListeners = [],
16269       urlChangeInit = false;
16270
16271   function cacheStateAndFireUrlChange() {
16272     pendingLocation = null;
16273     cacheState();
16274     fireUrlChange();
16275   }
16276
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;
16283
16284     // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
16285     if (equals(cachedState, lastCachedState)) {
16286       cachedState = lastCachedState;
16287     }
16288     lastCachedState = cachedState;
16289   }
16290
16291   function fireUrlChange() {
16292     if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
16293       return;
16294     }
16295
16296     lastBrowserUrl = self.url();
16297     lastHistoryState = cachedState;
16298     forEach(urlChangeListeners, function(listener) {
16299       listener(self.url(), cachedState);
16300     });
16301   }
16302
16303   /**
16304    * @name $browser#onUrlChange
16305    *
16306    * @description
16307    * Register callback function that will be called, when url changes.
16308    *
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
16313    *
16314    * It's not called when url is changed by $browser.url() method
16315    *
16316    * The listener gets called with new url as parameter.
16317    *
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.
16320    *
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.
16323    */
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
16330
16331       // html5 history api - popstate event
16332       if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
16333       // hashchange event
16334       jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
16335
16336       urlChangeInit = true;
16337     }
16338
16339     urlChangeListeners.push(callback);
16340     return callback;
16341   };
16342
16343   /**
16344    * @private
16345    * Remove popstate and hashchange handler from window.
16346    *
16347    * NOTE: this api is intended for use only by $rootScope.
16348    */
16349   self.$$applicationDestroyed = function() {
16350     jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
16351   };
16352
16353   /**
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.
16357    */
16358   self.$$checkUrlChange = fireUrlChange;
16359
16360   //////////////////////////////////////////////////////////////
16361   // Misc API
16362   //////////////////////////////////////////////////////////////
16363
16364   /**
16365    * @name $browser#baseHref
16366    *
16367    * @description
16368    * Returns current <base href>
16369    * (always relative - without domain)
16370    *
16371    * @returns {string} The current base href
16372    */
16373   self.baseHref = function() {
16374     var href = baseElement.attr('href');
16375     return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : '';
16376   };
16377
16378   /**
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()`.
16383    *
16384    * @description
16385    * Executes a fn asynchronously via `setTimeout(fn, delay)`.
16386    *
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()`.
16390    *
16391    */
16392   self.defer = function(fn, delay) {
16393     var timeoutId;
16394     outstandingRequestCount++;
16395     timeoutId = setTimeout(function() {
16396       delete pendingDeferIds[timeoutId];
16397       completeOutstandingRequest(fn);
16398     }, delay || 0);
16399     pendingDeferIds[timeoutId] = true;
16400     return timeoutId;
16401   };
16402
16403
16404   /**
16405    * @name $browser#defer.cancel
16406    *
16407    * @description
16408    * Cancels a deferred task identified with `deferId`.
16409    *
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
16412    *                    canceled.
16413    */
16414   self.defer.cancel = function(deferId) {
16415     if (pendingDeferIds[deferId]) {
16416       delete pendingDeferIds[deferId];
16417       clearTimeout(deferId);
16418       completeOutstandingRequest(noop);
16419       return true;
16420     }
16421     return false;
16422   };
16423
16424 }
16425
16426 /** @this */
16427 function $BrowserProvider() {
16428   this.$get = ['$window', '$log', '$sniffer', '$document',
16429       function($window, $log, $sniffer, $document) {
16430         return new Browser($window, $document, $log, $sniffer);
16431       }];
16432 }
16433
16434 /**
16435  * @ngdoc service
16436  * @name $cacheFactory
16437  * @this
16438  *
16439  * @description
16440  * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
16441  * them.
16442  *
16443  * ```js
16444  *
16445  *  var cache = $cacheFactory('cacheId');
16446  *  expect($cacheFactory.get('cacheId')).toBe(cache);
16447  *  expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
16448  *
16449  *  cache.put("key", "value");
16450  *  cache.put("another key", "another value");
16451  *
16452  *  // We've specified no options on creation
16453  *  expect(cache.info()).toEqual({id: 'cacheId', size: 2});
16454  *
16455  * ```
16456  *
16457  *
16458  * @param {string} cacheId Name or id of the newly created cache.
16459  * @param {object=} options Options object that specifies the cache behavior. Properties:
16460  *
16461  *   - `{number=}` `capacity` â€” turns the cache into LRU cache.
16462  *
16463  * @returns {object} Newly created cache object with the following set of methods:
16464  *
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
16467  *   it.
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.
16472  *
16473  * @example
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>
16480
16481          <p ng-if="keys.length">Cached Values</p>
16482          <div ng-repeat="key in keys">
16483            <span ng-bind="key"></span>
16484            <span>: </span>
16485            <b ng-bind="cache.get(key)"></b>
16486          </div>
16487
16488          <p>Cache Info</p>
16489          <div ng-repeat="(key, value) in cache.info()">
16490            <span ng-bind="key"></span>
16491            <span>: </span>
16492            <b ng-bind="value"></b>
16493          </div>
16494        </div>
16495      </file>
16496      <file name="script.js">
16497        angular.module('cacheExampleApp', []).
16498          controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
16499            $scope.keys = [];
16500            $scope.cache = $cacheFactory('cacheId');
16501            $scope.put = function(key, value) {
16502              if (angular.isUndefined($scope.cache.get(key))) {
16503                $scope.keys.push(key);
16504              }
16505              $scope.cache.put(key, angular.isUndefined(value) ? null : value);
16506            };
16507          }]);
16508      </file>
16509      <file name="style.css">
16510        p {
16511          margin: 10px 0 3px;
16512        }
16513      </file>
16514    </example>
16515  */
16516 function $CacheFactoryProvider() {
16517
16518   this.$get = function() {
16519     var caches = {};
16520
16521     function cacheFactory(cacheId, options) {
16522       if (cacheId in caches) {
16523         throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
16524       }
16525
16526       var size = 0,
16527           stats = extend({}, options, {id: cacheId}),
16528           data = createMap(),
16529           capacity = (options && options.capacity) || Number.MAX_VALUE,
16530           lruHash = createMap(),
16531           freshEnd = null,
16532           staleEnd = null;
16533
16534       /**
16535        * @ngdoc type
16536        * @name $cacheFactory.Cache
16537        *
16538        * @description
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.
16542        *
16543        * ```js
16544        *  angular.module('superCache')
16545        *    .factory('superCache', ['$cacheFactory', function($cacheFactory) {
16546        *      return $cacheFactory('super-cache');
16547        *    }]);
16548        * ```
16549        *
16550        * Example test:
16551        *
16552        * ```js
16553        *  it('should behave like a cache', inject(function(superCache) {
16554        *    superCache.put('key', 'value');
16555        *    superCache.put('another key', 'another value');
16556        *
16557        *    expect(superCache.info()).toEqual({
16558        *      id: 'super-cache',
16559        *      size: 2
16560        *    });
16561        *
16562        *    superCache.remove('another key');
16563        *    expect(superCache.get('another key')).toBeUndefined();
16564        *
16565        *    superCache.removeAll();
16566        *    expect(superCache.info()).toEqual({
16567        *      id: 'super-cache',
16568        *      size: 0
16569        *    });
16570        *  }));
16571        * ```
16572        */
16573       return (caches[cacheId] = {
16574
16575         /**
16576          * @ngdoc method
16577          * @name $cacheFactory.Cache#put
16578          * @kind function
16579          *
16580          * @description
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.
16585          *
16586          * It will not insert undefined values into the cache.
16587          *
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.
16592          */
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});
16597
16598             refresh(lruEntry);
16599           }
16600
16601           if (!(key in data)) size++;
16602           data[key] = value;
16603
16604           if (size > capacity) {
16605             this.remove(staleEnd.key);
16606           }
16607
16608           return value;
16609         },
16610
16611         /**
16612          * @ngdoc method
16613          * @name $cacheFactory.Cache#get
16614          * @kind function
16615          *
16616          * @description
16617          * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
16618          *
16619          * @param {string} key the key of the data to be retrieved
16620          * @returns {*} the value stored.
16621          */
16622         get: function(key) {
16623           if (capacity < Number.MAX_VALUE) {
16624             var lruEntry = lruHash[key];
16625
16626             if (!lruEntry) return;
16627
16628             refresh(lruEntry);
16629           }
16630
16631           return data[key];
16632         },
16633
16634
16635         /**
16636          * @ngdoc method
16637          * @name $cacheFactory.Cache#remove
16638          * @kind function
16639          *
16640          * @description
16641          * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
16642          *
16643          * @param {string} key the key of the entry to be removed
16644          */
16645         remove: function(key) {
16646           if (capacity < Number.MAX_VALUE) {
16647             var lruEntry = lruHash[key];
16648
16649             if (!lruEntry) return;
16650
16651             if (lruEntry === freshEnd) freshEnd = lruEntry.p;
16652             if (lruEntry === staleEnd) staleEnd = lruEntry.n;
16653             link(lruEntry.n,lruEntry.p);
16654
16655             delete lruHash[key];
16656           }
16657
16658           if (!(key in data)) return;
16659
16660           delete data[key];
16661           size--;
16662         },
16663
16664
16665         /**
16666          * @ngdoc method
16667          * @name $cacheFactory.Cache#removeAll
16668          * @kind function
16669          *
16670          * @description
16671          * Clears the cache object of any entries.
16672          */
16673         removeAll: function() {
16674           data = createMap();
16675           size = 0;
16676           lruHash = createMap();
16677           freshEnd = staleEnd = null;
16678         },
16679
16680
16681         /**
16682          * @ngdoc method
16683          * @name $cacheFactory.Cache#destroy
16684          * @kind function
16685          *
16686          * @description
16687          * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
16688          * removing it from the {@link $cacheFactory $cacheFactory} set.
16689          */
16690         destroy: function() {
16691           data = null;
16692           stats = null;
16693           lruHash = null;
16694           delete caches[cacheId];
16695         },
16696
16697
16698         /**
16699          * @ngdoc method
16700          * @name $cacheFactory.Cache#info
16701          * @kind function
16702          *
16703          * @description
16704          * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
16705          *
16706          * @returns {object} an object with the following properties:
16707          *   <ul>
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
16711          *       cache.</li>
16712          *   </ul>
16713          */
16714         info: function() {
16715           return extend({}, stats, {size: size});
16716         }
16717       });
16718
16719
16720       /**
16721        * makes the `entry` the freshEnd of the LRU linked list
16722        */
16723       function refresh(entry) {
16724         if (entry !== freshEnd) {
16725           if (!staleEnd) {
16726             staleEnd = entry;
16727           } else if (staleEnd === entry) {
16728             staleEnd = entry.n;
16729           }
16730
16731           link(entry.n, entry.p);
16732           link(entry, freshEnd);
16733           freshEnd = entry;
16734           freshEnd.n = null;
16735         }
16736       }
16737
16738
16739       /**
16740        * bidirectionally links two entries of the LRU linked list
16741        */
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
16746         }
16747       }
16748     }
16749
16750
16751   /**
16752    * @ngdoc method
16753    * @name $cacheFactory#info
16754    *
16755    * @description
16756    * Get information about all the caches that have been created
16757    *
16758    * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
16759    */
16760     cacheFactory.info = function() {
16761       var info = {};
16762       forEach(caches, function(cache, cacheId) {
16763         info[cacheId] = cache.info();
16764       });
16765       return info;
16766     };
16767
16768
16769   /**
16770    * @ngdoc method
16771    * @name $cacheFactory#get
16772    *
16773    * @description
16774    * Get access to a cache object by the `cacheId` used when it was created.
16775    *
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.
16778    */
16779     cacheFactory.get = function(cacheId) {
16780       return caches[cacheId];
16781     };
16782
16783
16784     return cacheFactory;
16785   };
16786 }
16787
16788 /**
16789  * @ngdoc service
16790  * @name $templateCache
16791  * @this
16792  *
16793  * @description
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.
16797  *
16798  * Adding via the `script` tag:
16799  *
16800  * ```html
16801  *   <script type="text/ng-template" id="templateId.html">
16802  *     <p>This is the content of the template</p>
16803  *   </script>
16804  * ```
16805  *
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.
16809  *
16810  * Adding via the `$templateCache` service:
16811  *
16812  * ```js
16813  * var myApp = angular.module('myApp', []);
16814  * myApp.run(function($templateCache) {
16815  *   $templateCache.put('templateId.html', 'This is the content of the template');
16816  * });
16817  * ```
16818  *
16819  * To retrieve the template later, simply use it in your component:
16820  * ```js
16821  * myApp.component('myComponent', {
16822  *    templateUrl: 'templateId.html'
16823  * });
16824  * ```
16825  *
16826  * or get it via the `$templateCache` service:
16827  * ```js
16828  * $templateCache.get('templateId.html')
16829  * ```
16830  *
16831  * See {@link ng.$cacheFactory $cacheFactory}.
16832  *
16833  */
16834 function $TemplateCacheProvider() {
16835   this.$get = ['$cacheFactory', function($cacheFactory) {
16836     return $cacheFactory('templates');
16837   }];
16838 }
16839
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.                          *
16845  *                                                                         *
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  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
16850
16851 /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
16852  *
16853  * DOM-related variables:
16854  *
16855  * - "node" - DOM Node
16856  * - "element" - DOM Element or Node
16857  * - "$node" or "$element" - jqLite-wrapped node or element
16858  *
16859  *
16860  * Compiler related stuff:
16861  *
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)
16866  */
16867
16868
16869 /**
16870  * @ngdoc service
16871  * @name $compile
16872  * @kind function
16873  *
16874  * @description
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.
16877  *
16878  * The compilation is a process of walking the DOM tree and matching DOM elements to
16879  * {@link ng.$compileProvider#directive directives}.
16880  *
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}.
16885  * </div>
16886  *
16887  * ## Comprehensive Directive API
16888  *
16889  * There are many different options for a directive.
16890  *
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).
16895  *
16896  * <div class="alert alert-success">
16897  * **Best Practice:** It's recommended to use the "directive definition object" form.
16898  * </div>
16899  *
16900  * Here's an example directive declared with a Directive Definition Object:
16901  *
16902  * ```js
16903  *   var myModule = angular.module(...);
16904  *
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) { ... },
16909  *       // or
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) {
16921  *         return {
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) { ... }
16924  *         }
16925  *         // or
16926  *         // return function postLink( ... ) { ... }
16927  *       },
16928  *       // or
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) { ... }
16932  *       // }
16933  *       // or
16934  *       // {@link $compile#-link- link}: function postLink( ... ) { ... }
16935  *     };
16936  *     return directiveDefinitionObject;
16937  *   });
16938  * ```
16939  *
16940  * <div class="alert alert-warning">
16941  * **Note:** Any unspecified options will use the default value. You can see the default values below.
16942  * </div>
16943  *
16944  * Therefore the above can be simplified as:
16945  *
16946  * ```js
16947  *   var myModule = angular.module(...);
16948  *
16949  *   myModule.directive('directiveName', function factory(injectables) {
16950  *     var directiveDefinitionObject = {
16951  *       link: function postLink(scope, iElement, iAttrs) { ... }
16952  *     };
16953  *     return directiveDefinitionObject;
16954  *     // or
16955  *     // return function postLink(scope, iElement, iAttrs) { ... }
16956  *   });
16957  * ```
16958  *
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
16961  * directive:
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 &amp; 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.
16984  *
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:
16988  *
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()`.
16998  *
16999  * #### Life-cycle hook examples
17000  *
17001  * This example shows how you can check for mutations to a Date object even though the identity of the object
17002  * has not changed.
17003  *
17004  * <example name="doCheckDateExample" module="do-check-module">
17005  *   <file name="app.js">
17006  *     angular.module('do-check-module', [])
17007  *       .component('app', {
17008  *         template:
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);
17017  *           };
17018  *         }
17019  *       })
17020  *       .component('test', {
17021  *         bindings: { date: '<' },
17022  *         template:
17023  *           '<pre>{{ $ctrl.log | json }}</pre>',
17024  *         controller: function() {
17025  *           var previousValue;
17026  *           this.log = [];
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;
17032  *             }
17033  *           };
17034  *         }
17035  *       });
17036  *   </file>
17037  *   <file name="index.html">
17038  *     <app></app>
17039  *   </file>
17040  * </example>
17041  *
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)
17045  *
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>
17053  *     </div>
17054  *   </file>
17055  *   <file name="app.js">
17056  *      angular.module('do-check-module', [])
17057  *        .component('test', {
17058  *          bindings: { items: '<' },
17059  *          template:
17060  *            '<pre>{{ $ctrl.log | json }}</pre>',
17061  *          controller: function() {
17062  *            this.log = [];
17063  *
17064  *            this.$doCheck = function() {
17065  *              if (this.items_ref !== this.items) {
17066  *                this.log.push('doCheck: items changed');
17067  *                this.items_ref = this.items;
17068  *              }
17069  *              if (!angular.equals(this.items_clone, this.items)) {
17070  *                this.log.push('doCheck: items mutated');
17071  *                this.items_clone = angular.copy(this.items);
17072  *              }
17073  *            };
17074  *          }
17075  *        });
17076  *   </file>
17077  * </example>
17078  *
17079  *
17080  * ### Directive Definition Object
17081  *
17082  * The directive definition object provides instructions to the {@link ng.$compile
17083  * compiler}. The attributes are:
17084  *
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}).
17091  *
17092  * #### `priority`
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`.
17099  *
17100  * #### `terminal`
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.
17105  *
17106  * #### `scope`
17107  * The scope property can be `false`, `true`, or an object:
17108  *
17109  * * **`false` (default):** No scope will be created for the directive. The directive will use its
17110  * parent's scope.
17111  *
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.
17115  *
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.
17120  *
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:
17125  *
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).
17133  *
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).
17150  *
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`.
17155  *
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
17160  *   two caveats:
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.
17171  *
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.
17174  *
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})`.
17183  *
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:
17187  *
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.
17197  *
17198  *
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.
17202  *
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.
17205  *
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
17209  * initialized.
17210  *
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.
17215  * </div>
17216  *
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).
17221  *
17222  * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
17223  *
17224  *
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:
17230  *
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).
17250  *
17251  * #### `require`
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
17259  * controllers.
17260  *
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:
17270  *
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.
17279  *
17280  *
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.
17287  *
17288  *
17289  * #### `restrict`
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.
17292  *
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 -->`
17297  *
17298  *
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>`.
17303  *
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>`).
17308  *
17309  * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
17310  *
17311  * #### `template`
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).
17316  *
17317  * Value may be:
17318  *
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.
17322  *
17323  *
17324  * #### `templateUrl`
17325  * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
17326  *
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.
17330  *
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`.
17334  *
17335  * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
17336  *
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}.
17341  *
17342  *
17343  * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
17344  * specify what the template should replace. Defaults to `false`.
17345  *
17346  * * `true` - the template will replace the directive's element.
17347  * * `false` - the template will replace the contents of the directive's element.
17348  *
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.
17352  *
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).
17356  *
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.
17361  *
17362  *
17363  * #### `compile`
17364  *
17365  * ```js
17366  *   function compile(tElement, tAttrs, transclude) { ... }
17367  * ```
17368  *
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:
17371  *
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.
17374  *
17375  *   * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
17376  *     between all directive compile functions.
17377  *
17378  *   * `transclude` -  [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
17379  *
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.
17385  * </div>
17386
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.
17391  *
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.
17395  * </div>
17396  *
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.
17401  * </div>
17402
17403  * A compile function can have a return value which can be either a function or an object.
17404  *
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.
17407  *
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.
17411  *
17412  *
17413  * #### `link`
17414  * This property is used only if the `compile` property is not defined.
17415  *
17416  * ```js
17417  *   function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
17418  * ```
17419  *
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
17422  * put.
17423  *
17424  *   * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
17425  *     directive for registering {@link ng.$rootScope.Scope#$watch watches}.
17426  *
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.
17430  *
17431  *   * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
17432  *     between all directive linking functions.
17433  *
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
17440  *
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.
17443  *
17444  *     Note that you can also require the directive's own controller - it will be made available like
17445  *     any other controller.
17446  *
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)`.
17451  *
17452  * #### Pre-linking function
17453  *
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.
17456  *
17457  * #### Post-linking function
17458  *
17459  * Executed after the child elements are linked.
17460  *
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.
17464  *
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.
17467  *
17468  *
17469  * ### Transclusion
17470  *
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.
17474  *
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}.
17481  *
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.
17484  *
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}.
17489  * </div>
17490  *
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:
17493  *
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.
17499  *
17500  * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
17501  *
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).
17505  *
17506  * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
17507  *
17508  * If the element selector is prefixed with a `?` then that slot is optional.
17509  *
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.
17512  *
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.
17517  *
17518  *
17519  * #### Transclusion Functions
17520  *
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.
17524  *
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.
17528  * </div>
17529  *
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.
17533  *
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.
17537  *
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.
17541  * </div>
17542  *
17543  * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
17544  * attach function**:
17545  *
17546  * ```js
17547  * var transcludedContent, transclusionScope;
17548  *
17549  * $transclude(function(clone, scope) {
17550  *   element.append(clone);
17551  *   transcludedContent = clone;
17552  *   transclusionScope = scope;
17553  * });
17554  * ```
17555  *
17556  * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
17557  * associated transclusion scope:
17558  *
17559  * ```js
17560  * transcludedContent.remove();
17561  * transclusionScope.$destroy();
17562  * ```
17563  *
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.
17568  * </div>
17569  *
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.
17573  *
17574  *
17575  * #### Transclusion Scopes
17576  *
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
17580  * was taken.
17581  *
17582  * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
17583  * like this:
17584  *
17585  * ```html
17586  * <div ng-app>
17587  *   <div isolate>
17588  *     <div transclusion>
17589  *     </div>
17590  *   </div>
17591  * </div>
17592  * ```
17593  *
17594  * The `$parent` scope hierarchy will look like this:
17595  *
17596    ```
17597    - $rootScope
17598      - isolate
17599        - transclusion
17600    ```
17601  *
17602  * but the scopes will inherit prototypically from different scopes to their `$parent`.
17603  *
17604    ```
17605    - $rootScope
17606      - transclusion
17607    - isolate
17608    ```
17609  *
17610  *
17611  * ### Attributes
17612  *
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.
17615  *
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.
17619  *
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
17622  *   communication.
17623  *
17624  * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
17625  *   allowing other directives to read the interpolated value.
17626  *
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`.
17631  *
17632  * ```js
17633  * function linkingFn(scope, elm, attrs, ctrl) {
17634  *   // get the attribute value
17635  *   console.log(attrs.ngModel);
17636  *
17637  *   // change the attribute
17638  *   attrs.$set('ngModel', 'new value');
17639  *
17640  *   // observe changes to interpolated attribute
17641  *   attrs.$observe('ngModel', function(value) {
17642  *     console.log('ngModel has changed value to ' + value);
17643  *   });
17644  * }
17645  * ```
17646  *
17647  * ## Example
17648  *
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.
17652  * </div>
17653  *
17654  <example module="compileExample" name="compile">
17655    <file name="index.html">
17656     <script>
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) {
17663             scope.$watch(
17664               function(scope) {
17665                  // watch the 'compile' expression for changes
17666                 return scope.$eval(attrs.compile);
17667               },
17668               function(value) {
17669                 // when the 'compile' expression changes
17670                 // assign it into the current DOM
17671                 element.html(value);
17672
17673                 // compile the new DOM and link it to the current
17674                 // scope.
17675                 // NOTE: we only compile .childNodes so that
17676                 // we don't get into infinite loop compiling ourselves
17677                 $compile(element.contents())(scope);
17678               }
17679             );
17680           };
17681         });
17682       })
17683       .controller('GreeterController', ['$scope', function($scope) {
17684         $scope.name = 'Angular';
17685         $scope.html = 'Hello {{name}}';
17686       }]);
17687     </script>
17688     <div ng-controller="GreeterController">
17689       <input ng-model="name"> <br/>
17690       <textarea ng-model="html"></textarea> <br/>
17691       <div compile="html"></div>
17692     </div>
17693    </file>
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');
17700        textarea.clear();
17701        textarea.sendKeys('{{name}}!');
17702        expect(output.getText()).toBe('Angular!');
17703      });
17704    </file>
17705  </example>
17706
17707  *
17708  *
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.
17711  *
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.
17716  * </div>
17717  *
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:
17722  *
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:
17728  *
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.
17731  *
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:
17734  *
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:
17741  *        ```
17742  *        {
17743  *          parent: {
17744  *            instance: parentControllerInstance
17745  *          }
17746  *        }
17747  *        ```
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.
17751  *
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.
17754  *
17755  * After linking the view is not updated until after a call to $digest which typically is done by
17756  * Angular automatically.
17757  *
17758  * If you need access to the bound view, there are two ways to do it:
17759  *
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.
17762  *   ```js
17763  *     var element = $compile('<p>{{total}}</p>')(scope);
17764  *   ```
17765  *
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:
17769  *   ```js
17770  *     var templateElement = angular.element('<p>{{total}}</p>'),
17771  *         scope = ....;
17772  *
17773  *     var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
17774  *       //attach the clone to DOM document at the right place
17775  *     });
17776  *
17777  *     //now we have reference to the cloned DOM via `clonedElement`
17778  *   ```
17779  *
17780  *
17781  * For information on how the compiler works, see the
17782  * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
17783  *
17784  * @knownIssue
17785  *
17786  * ### Double Compilation
17787  *
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.
17792  *
17793  */
17794
17795 var $compileMinErr = minErr('$compile');
17796
17797 function UNINITIALIZED_VALUE() {}
17798 var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
17799
17800 /**
17801  * @ngdoc provider
17802  * @name $compileProvider
17803  *
17804  * @description
17805  */
17806 $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
17807 /** @this */
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 = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
17815
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();
17821
17822   function parseIsolateBindings(scope, directiveName, isController) {
17823     var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*([\w$]*)\s*$/;
17824
17825     var bindings = createMap();
17826
17827     forEach(scope, function(definition, scopeName) {
17828       if (definition in bindingCache) {
17829         bindings[scopeName] = bindingCache[definition];
17830         return;
17831       }
17832       var match = definition.match(LOCAL_REGEXP);
17833
17834       if (!match) {
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'));
17841       }
17842
17843       bindings[scopeName] = {
17844         mode: match[1][0],
17845         collection: match[2] === '*',
17846         optional: match[3] === '?',
17847         attrName: match[4] || scopeName
17848       };
17849       if (match[4]) {
17850         bindingCache[definition] = bindings[scopeName];
17851       }
17852     });
17853
17854     return bindings;
17855   }
17856
17857   function parseDirectiveBindings(directive, directiveName) {
17858     var bindings = {
17859       isolateScope: null,
17860       bindToController: null
17861     };
17862     if (isObject(directive.scope)) {
17863       if (directive.bindToController === true) {
17864         bindings.bindToController = parseIsolateBindings(directive.scope,
17865                                                          directiveName, true);
17866         bindings.isolateScope = {};
17867       } else {
17868         bindings.isolateScope = parseIsolateBindings(directive.scope,
17869                                                      directiveName, false);
17870       }
17871     }
17872     if (isObject(directive.bindToController)) {
17873       bindings.bindToController =
17874           parseIsolateBindings(directive.bindToController, directiveName, true);
17875     }
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.',
17880             directiveName);
17881     }
17882     return bindings;
17883   }
17884
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);
17889     }
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',
17893             name);
17894     }
17895   }
17896
17897   function getDirectiveRequire(directive) {
17898     var require = directive.require || (directive.controller && directive.name);
17899
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;
17905       });
17906     }
17907
17908     return require;
17909   }
17910
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',
17915           restrict,
17916           name);
17917     }
17918
17919     return restrict || 'EA';
17920   }
17921
17922   /**
17923    * @ngdoc method
17924    * @name $compileProvider#directive
17925    * @kind function
17926    *
17927    * @description
17928    * Register a new directive with the compiler.
17929    *
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.
17936    */
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) {
17949               try {
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);
17955                 }
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);
17963               } catch (e) {
17964                 $exceptionHandler(e);
17965               }
17966             });
17967             return directives;
17968           }]);
17969       }
17970       hasDirectives[name].push(directiveFactory);
17971     } else {
17972       forEach(name, reverseParams(registerDirective));
17973     }
17974     return this;
17975   };
17976
17977   /**
17978    * @ngdoc method
17979    * @name $compileProvider#component
17980    * @module ng
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):
17985    *
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.
17995    *
17996    *      If `template` is a function, then it is {@link auto.$injector#invoke injected} with
17997    *      the following locals:
17998    *
17999    *      - `$element` - Current element
18000    *      - `$attrs` - Current attributes object for the element
18001    *
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.
18004    *
18005    *      If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
18006    *      the following locals:
18007    *
18008    *      - `$element` - Current element
18009    *      - `$attrs` - Current attributes object for the element
18010    *
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)
18021    *
18022    * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
18023    * @description
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'`).
18027    *
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.
18030    *
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.
18033    *
18034    * Here are a few examples of how you would usually define components:
18035    *
18036    * ```js
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';
18042    *     }
18043    *   });
18044    *
18045    *   myMod.component('myComp', {
18046    *     template: '<div>My name is {{$ctrl.name}}</div>',
18047    *     bindings: {name: '@'}
18048    *   });
18049    *
18050    *   myMod.component('myComp', {
18051    *     templateUrl: 'views/my-comp.html',
18052    *     controller: 'MyCtrl',
18053    *     controllerAs: 'ctrl',
18054    *     bindings: {name: '@'}
18055    *   });
18056    *
18057    * ```
18058    * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
18059    *
18060    * <br />
18061    * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
18062    */
18063   this.component = function registerComponent(name, options) {
18064     var controller = options.controller || function() {};
18065
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});
18071           };
18072         } else {
18073           return fn;
18074         }
18075       }
18076
18077       var template = (!options.template && !options.templateUrl ? '' : options.template);
18078       var ddo = {
18079         controller: controller,
18080         controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
18081         template: makeInjectable(template),
18082         templateUrl: makeInjectable(options.templateUrl),
18083         transclude: options.transclude,
18084         scope: {},
18085         bindToController: options.bindings || {},
18086         restrict: 'E',
18087         require: options.require
18088       };
18089
18090       // Copy annotations (starting with $) over to the DDO
18091       forEach(options, function(val, key) {
18092         if (key.charAt(0) === '$') ddo[key] = val;
18093       });
18094
18095       return ddo;
18096     }
18097
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.
18102
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;
18110       }
18111     });
18112
18113     factory.$inject = ['$injector'];
18114
18115     return this.directive(name, factory);
18116   };
18117
18118
18119   /**
18120    * @ngdoc method
18121    * @name $compileProvider#aHrefSanitizationWhitelist
18122    * @kind function
18123    *
18124    * @description
18125    * Retrieves or overrides the default regular expression that is used for whitelisting of safe
18126    * urls during a[href] sanitization.
18127    *
18128    * The sanitization is a security measure aimed at preventing XSS attacks via html links.
18129    *
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.
18134    *
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.
18138    */
18139   this.aHrefSanitizationWhitelist = function(regexp) {
18140     if (isDefined(regexp)) {
18141       $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
18142       return this;
18143     } else {
18144       return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
18145     }
18146   };
18147
18148
18149   /**
18150    * @ngdoc method
18151    * @name $compileProvider#imgSrcSanitizationWhitelist
18152    * @kind function
18153    *
18154    * @description
18155    * Retrieves or overrides the default regular expression that is used for whitelisting of safe
18156    * urls during img[src] sanitization.
18157    *
18158    * The sanitization is a security measure aimed at prevent XSS attacks via html links.
18159    *
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.
18164    *
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.
18168    */
18169   this.imgSrcSanitizationWhitelist = function(regexp) {
18170     if (isDefined(regexp)) {
18171       $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
18172       return this;
18173     } else {
18174       return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
18175     }
18176   };
18177
18178   /**
18179    * @ngdoc method
18180    * @name  $compileProvider#debugInfoEnabled
18181    *
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
18185    *
18186    * @kind function
18187    *
18188    * @description
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
18194    *
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.
18197    *
18198    * The default value is true.
18199    */
18200   var debugInfoEnabled = true;
18201   this.debugInfoEnabled = function(enabled) {
18202     if (isDefined(enabled)) {
18203       debugInfoEnabled = enabled;
18204       return this;
18205     }
18206     return debugInfoEnabled;
18207   };
18208
18209   /**
18210    * @ngdoc method
18211    * @name  $compileProvider#preAssignBindingsEnabled
18212    *
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
18216    *
18217    * @kind function
18218    *
18219    * @description
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.
18224    *
18225    * If disabled (false), the compiler calls the constructor first before assigning bindings.
18226    *
18227    * The default value is true in Angular 1.5.x but will switch to false in Angular 1.6.x.
18228    */
18229   var preAssignBindingsEnabled = true;
18230   this.preAssignBindingsEnabled = function(enabled) {
18231     if (isDefined(enabled)) {
18232       preAssignBindingsEnabled = enabled;
18233       return this;
18234     }
18235     return preAssignBindingsEnabled;
18236   };
18237
18238
18239   var TTL = 10;
18240   /**
18241    * @ngdoc method
18242    * @name $compileProvider#onChangesTtl
18243    * @description
18244    *
18245    * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
18246    * assuming that the model is unstable.
18247    *
18248    * The current default is 10 iterations.
18249    *
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.
18254    *
18255    * Increasing the TTL could have performance implications, so you should not change it without proper justification.
18256    *
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)
18259    */
18260   this.onChangesTtl = function(value) {
18261     if (arguments.length) {
18262       TTL = value;
18263       return this;
18264     }
18265     return TTL;
18266   };
18267
18268   var commentDirectivesEnabledConfig = true;
18269   /**
18270    * @ngdoc method
18271    * @name $compileProvider#commentDirectivesEnabled
18272    * @description
18273    *
18274    * It indicates to the compiler
18275    * whether or not directives on comments should be compiled.
18276    * Defaults to `true`.
18277    *
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).
18284    *
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)
18287    */
18288   this.commentDirectivesEnabled = function(value) {
18289     if (arguments.length) {
18290       commentDirectivesEnabledConfig = value;
18291       return this;
18292     }
18293     return commentDirectivesEnabledConfig;
18294   };
18295
18296
18297   var cssClassDirectivesEnabledConfig = true;
18298   /**
18299    * @ngdoc method
18300    * @name $compileProvider#cssClassDirectivesEnabled
18301    * @description
18302    *
18303    * It indicates to the compiler
18304    * whether or not directives on element classes should be compiled.
18305    * Defaults to `true`.
18306    *
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).
18313    *
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)
18316    */
18317   this.cssClassDirectivesEnabled = function(value) {
18318     if (arguments.length) {
18319       cssClassDirectivesEnabledConfig = value;
18320       return this;
18321     }
18322     return cssClassDirectivesEnabledConfig;
18323   };
18324
18325   this.$get = [
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) {
18330
18331     var SIMPLE_ATTR_NAME = /^\w/;
18332     var specialAttrHolder = window.document.createElement('div');
18333
18334
18335     var commentDirectivesEnabled = commentDirectivesEnabledConfig;
18336     var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;
18337
18338
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;
18343
18344     // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
18345     function flushOnChangesQueue() {
18346       try {
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);
18351         }
18352         // We must run this hook in an apply since the $$postDigest runs outside apply
18353         $rootScope.$apply(function() {
18354           var errors = [];
18355           for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
18356             try {
18357               onChangesQueue[i]();
18358             } catch (e) {
18359               errors.push(e);
18360             }
18361           }
18362           // Reset the queue to trigger a new schedule next time there is a change
18363           onChangesQueue = undefined;
18364           if (errors.length) {
18365             throw errors;
18366           }
18367         });
18368       } finally {
18369         onChangesTtl++;
18370       }
18371     }
18372
18373
18374     function Attributes(element, attributesToCopy) {
18375       if (attributesToCopy) {
18376         var keys = Object.keys(attributesToCopy);
18377         var i, l, key;
18378
18379         for (i = 0, l = keys.length; i < l; i++) {
18380           key = keys[i];
18381           this[key] = attributesToCopy[key];
18382         }
18383       } else {
18384         this.$attr = {};
18385       }
18386
18387       this.$$element = element;
18388     }
18389
18390     Attributes.prototype = {
18391       /**
18392        * @ngdoc method
18393        * @name $compile.directive.Attributes#$normalize
18394        * @kind function
18395        *
18396        * @description
18397        * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
18398        * `data-`) to its normalized, camelCase form.
18399        *
18400        * Also there is special case for Moz prefix starting with upper case letter.
18401        *
18402        * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
18403        *
18404        * @param {string} name Name to normalize
18405        */
18406       $normalize: directiveNormalize,
18407
18408
18409       /**
18410        * @ngdoc method
18411        * @name $compile.directive.Attributes#$addClass
18412        * @kind function
18413        *
18414        * @description
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.
18417        *
18418        * @param {string} classVal The className value that will be added to the element
18419        */
18420       $addClass: function(classVal) {
18421         if (classVal && classVal.length > 0) {
18422           $animate.addClass(this.$$element, classVal);
18423         }
18424       },
18425
18426       /**
18427        * @ngdoc method
18428        * @name $compile.directive.Attributes#$removeClass
18429        * @kind function
18430        *
18431        * @description
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.
18434        *
18435        * @param {string} classVal The className value that will be removed from the element
18436        */
18437       $removeClass: function(classVal) {
18438         if (classVal && classVal.length > 0) {
18439           $animate.removeClass(this.$$element, classVal);
18440         }
18441       },
18442
18443       /**
18444        * @ngdoc method
18445        * @name $compile.directive.Attributes#$updateClass
18446        * @kind function
18447        *
18448        * @description
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).
18451        *
18452        * @param {string} newClasses The current CSS className value
18453        * @param {string} oldClasses The former CSS className value
18454        */
18455       $updateClass: function(newClasses, oldClasses) {
18456         var toAdd = tokenDifference(newClasses, oldClasses);
18457         if (toAdd && toAdd.length) {
18458           $animate.addClass(this.$$element, toAdd);
18459         }
18460
18461         var toRemove = tokenDifference(oldClasses, newClasses);
18462         if (toRemove && toRemove.length) {
18463           $animate.removeClass(this.$$element, toRemove);
18464         }
18465       },
18466
18467       /**
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.
18475        */
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
18479         //become unstable.
18480
18481         var node = this.$$element[0],
18482             booleanKey = getBooleanAttrName(node, key),
18483             aliasedKey = getAliasedAttrName(key),
18484             observer = key,
18485             nodeName;
18486
18487         if (booleanKey) {
18488           this.$$element.prop(key, value);
18489           attrName = booleanKey;
18490         } else if (aliasedKey) {
18491           this[aliasedKey] = value;
18492           observer = aliasedKey;
18493         }
18494
18495         this[key] = value;
18496
18497         // translate normalized key to actual key
18498         if (attrName) {
18499           this.$attr[key] = attrName;
18500         } else {
18501           attrName = this.$attr[key];
18502           if (!attrName) {
18503             this.$attr[key] = attrName = snake_case(key, '-');
18504           }
18505         }
18506
18507         nodeName = nodeName_(this.$$element);
18508
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
18515           var result = '';
18516
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 : /(,)/;
18522
18523           // split srcset into tuple of uri and descriptor except for the last item
18524           var rawUris = trimmedSrcset.split(pattern);
18525
18526           // for each tuples
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]));
18534           }
18535
18536           // split the last item into uri and descriptor
18537           var lastTuple = trim(rawUris[i * 2]).split(/\s/);
18538
18539           // sanitize the last uri
18540           result += $$sanitizeUri(trim(lastTuple[0]), true);
18541
18542           // and add the last descriptor if any
18543           if (lastTuple.length === 2) {
18544             result += (' ' + trim(lastTuple[1]));
18545           }
18546           this[key] = value = result;
18547         }
18548
18549         if (writeAttr !== false) {
18550           if (value === null || isUndefined(value)) {
18551             this.$$element.removeAttr(attrName);
18552           } else {
18553             if (SIMPLE_ATTR_NAME.test(attrName)) {
18554               this.$$element.attr(attrName, value);
18555             } else {
18556               setSpecialAttr(this.$$element[0], attrName, value);
18557             }
18558           }
18559         }
18560
18561         // fire observers
18562         var $$observers = this.$$observers;
18563         if ($$observers) {
18564           forEach($$observers[observer], function(fn) {
18565             try {
18566               fn(value);
18567             } catch (e) {
18568               $exceptionHandler(e);
18569             }
18570           });
18571         }
18572       },
18573
18574
18575       /**
18576        * @ngdoc method
18577        * @name $compile.directive.Attributes#$observe
18578        * @kind function
18579        *
18580        * @description
18581        * Observes an interpolated attribute.
18582        *
18583        * The observer function will be invoked once during the next `$digest` following
18584        * compilation. The observer is then invoked whenever the interpolated value
18585        * changes.
18586        *
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.
18593        */
18594       $observe: function(key, fn) {
18595         var attrs = this,
18596             $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
18597             listeners = ($$observers[key] || ($$observers[key] = []));
18598
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
18603             fn(attrs[key]);
18604           }
18605         });
18606
18607         return function() {
18608           arrayRemove(listeners, fn);
18609         };
18610       }
18611     };
18612
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);
18624     }
18625
18626     function safeAddClass($element, className) {
18627       try {
18628         $element.addClass(className);
18629       } catch (e) {
18630         // ignore, since it means that we are trying to set class on
18631         // SVG element, where class name is read-only.
18632       }
18633     }
18634
18635
18636     var startSymbol = $interpolate.startSymbol(),
18637         endSymbol = $interpolate.endSymbol(),
18638         denormalizeTemplate = (startSymbol === '{{' && endSymbol  === '}}')
18639             ? identity
18640             : function denormalizeTemplate(template) {
18641               return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
18642         },
18643         NG_ATTR_BINDING = /^ngAttr[A-Z]/;
18644     var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
18645
18646     compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
18647       var bindings = $element.data('$binding') || [];
18648
18649       if (isArray(binding)) {
18650         bindings = bindings.concat(binding);
18651       } else {
18652         bindings.push(binding);
18653       }
18654
18655       $element.data('$binding', bindings);
18656     } : noop;
18657
18658     compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
18659       safeAddClass($element, 'ng-binding');
18660     } : noop;
18661
18662     compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
18663       var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
18664       $element.data(dataName, scope);
18665     } : noop;
18666
18667     compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
18668       safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
18669     } : noop;
18670
18671     compile.$$createComment = function(directiveName, comment) {
18672       var content = '';
18673       if (debugInfoEnabled) {
18674         content = ' ' + (directiveName || '') + ': ';
18675         if (comment) content += comment + ' ';
18676       }
18677       return window.document.createComment(content);
18678     };
18679
18680     return compile;
18681
18682     //================================
18683
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
18688         // modify it.
18689         $compileNodes = jqLite($compileNodes);
18690       }
18691
18692       var NOT_EMPTY = /\S+/;
18693
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];
18698
18699         if (domNode.nodeType === NODE_TYPE_TEXT && domNode.nodeValue.match(NOT_EMPTY) /* non-empty */) {
18700           jqLiteWrapNode(domNode, $compileNodes[i] = window.document.createElement('span'));
18701         }
18702       }
18703
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');
18711
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
18716           // here.
18717           scope = scope.$parent.$new();
18718         }
18719
18720         options = options || {};
18721         var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
18722           transcludeControllers = options.transcludeControllers,
18723           futureParentElement = options.futureParentElement;
18724
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;
18731         }
18732
18733         if (!namespace) {
18734           namespace = detectNamespaceForChildElements(futureParentElement);
18735         }
18736         var $linkNode;
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())
18745           );
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);
18750         } else {
18751           $linkNode = $compileNodes;
18752         }
18753
18754         if (transcludeControllers) {
18755           for (var controllerName in transcludeControllers) {
18756             $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
18757           }
18758         }
18759
18760         compile.$$addScopeInfo($linkNode, scope);
18761
18762         if (cloneConnectFn) cloneConnectFn($linkNode, scope);
18763         if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
18764         return $linkNode;
18765       };
18766     }
18767
18768     function detectNamespaceForChildElements(parentElement) {
18769       // TODO: Make this detect MathML as well...
18770       var node = parentElement && parentElement[0];
18771       if (!node) {
18772         return 'html';
18773       } else {
18774         return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
18775       }
18776     }
18777
18778     /**
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.
18783      *
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.
18792      */
18793     function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
18794                             previousCompileContext) {
18795       var linkFns = [],
18796           attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
18797
18798       for (var i = 0; i < nodeList.length; i++) {
18799         attrs = new Attributes();
18800
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,
18803                                         ignoreDirective);
18804
18805         nodeLinkFn = (directives.length)
18806             ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
18807                                       null, [], [], previousCompileContext)
18808             : null;
18809
18810         if (nodeLinkFn && nodeLinkFn.scope) {
18811           compile.$$addScopeClass(attrs.$$element);
18812         }
18813
18814         childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
18815                       !(childNodes = nodeList[i].childNodes) ||
18816                       !childNodes.length)
18817             ? null
18818             : compileNodes(childNodes,
18819                  nodeLinkFn ? (
18820                   (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
18821                      && nodeLinkFn.transclude) : transcludeFn);
18822
18823         if (nodeLinkFn || childLinkFn) {
18824           linkFns.push(i, nodeLinkFn, childLinkFn);
18825           linkFnFound = true;
18826           nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
18827         }
18828
18829         //use the previous context only for the first element in the virtual group
18830         previousCompileContext = null;
18831       }
18832
18833       // return a linking function if we have found anything, null otherwise
18834       return linkFnFound ? compositeLinkFn : null;
18835
18836       function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
18837         var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
18838         var stableNodeList;
18839
18840
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);
18846
18847           // create a sparse array by only copying the elements which have a linkFn
18848           for (i = 0; i < linkFns.length; i += 3) {
18849             idx = linkFns[i];
18850             stableNodeList[idx] = nodeList[idx];
18851           }
18852         } else {
18853           stableNodeList = nodeList;
18854         }
18855
18856         for (i = 0, ii = linkFns.length; i < ii;) {
18857           node = stableNodeList[linkFns[i++]];
18858           nodeLinkFn = linkFns[i++];
18859           childLinkFn = linkFns[i++];
18860
18861           if (nodeLinkFn) {
18862             if (nodeLinkFn.scope) {
18863               childScope = scope.$new();
18864               compile.$$addScopeInfo(jqLite(node), childScope);
18865             } else {
18866               childScope = scope;
18867             }
18868
18869             if (nodeLinkFn.transcludeOnThisElement) {
18870               childBoundTranscludeFn = createBoundTranscludeFn(
18871                   scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
18872
18873             } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
18874               childBoundTranscludeFn = parentBoundTranscludeFn;
18875
18876             } else if (!parentBoundTranscludeFn && transcludeFn) {
18877               childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
18878
18879             } else {
18880               childBoundTranscludeFn = null;
18881             }
18882
18883             nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
18884
18885           } else if (childLinkFn) {
18886             childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
18887           }
18888         }
18889       }
18890     }
18891
18892     function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
18893       function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
18894
18895         if (!transcludedScope) {
18896           transcludedScope = scope.$new(false, containingScope);
18897           transcludedScope.$$transcluded = true;
18898         }
18899
18900         return transcludeFn(transcludedScope, cloneFn, {
18901           parentBoundTranscludeFn: previousBoundTranscludeFn,
18902           transcludeControllers: controllers,
18903           futureParentElement: futureParentElement
18904         });
18905       }
18906
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);
18913         } else {
18914           boundSlots[slotName] = null;
18915         }
18916       }
18917
18918       return boundTranscludeFn;
18919     }
18920
18921     /**
18922      * Looks for directives on the given node and adds them to the directive collection which is
18923      * sorted.
18924      *
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.
18930      */
18931     function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
18932       var nodeType = node.nodeType,
18933           attrsMap = attrs.$attr,
18934           match,
18935           nodeName,
18936           className;
18937
18938       switch (nodeType) {
18939         case NODE_TYPE_ELEMENT: /* Element */
18940
18941           nodeName = nodeName_(node);
18942
18943           // use the node name: <directive>
18944           addDirective(directives,
18945               directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective);
18946
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;
18952
18953             attr = nAttrs[j];
18954             name = attr.name;
18955             value = trim(attr.value);
18956
18957             // support ngAttr attribute binding
18958             ngAttrName = directiveNormalize(name);
18959             isNgAttr = NG_ATTR_BINDING.test(ngAttrName);
18960             if (isNgAttr) {
18961               name = name.replace(PREFIX_REGEXP, '')
18962                 .substr(8).replace(/_(.)/g, function(match, letter) {
18963                   return letter.toUpperCase();
18964                 });
18965             }
18966
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);
18972             }
18973
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
18980                 }
18981             }
18982             addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
18983             addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
18984                           attrEndName);
18985           }
18986
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');
18991           }
18992
18993           // use class as directive
18994           if (!cssClassDirectivesEnabled) break;
18995           className = node.className;
18996           if (isObject(className)) {
18997               // Maybe SVGAnimatedString
18998               className = className.animVal;
18999           }
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]);
19005               }
19006               className = className.substr(match.index + match[0].length);
19007             }
19008           }
19009           break;
19010         case NODE_TYPE_TEXT: /* Text Node */
19011           if (msie === 11) {
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);
19016             }
19017           }
19018           addTextInterpolateDirective(directives, node.nodeValue);
19019           break;
19020         case NODE_TYPE_COMMENT: /* Comment */
19021           if (!commentDirectivesEnabled) break;
19022           collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);
19023           break;
19024       }
19025
19026       directives.sort(byPriority);
19027       return directives;
19028     }
19029
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
19033       try {
19034         var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
19035         if (match) {
19036           var nName = directiveNormalize(match[1]);
19037           if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
19038             attrs[nName] = trim(match[2]);
19039           }
19040         }
19041       } catch (e) {
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.)
19045       }
19046     }
19047
19048     /**
19049      * Given a node with a directive-start it collects all of the siblings until it finds
19050      * directive-end.
19051      * @param node
19052      * @param attrStart
19053      * @param attrEnd
19054      * @returns {*}
19055      */
19056     function groupScan(node, attrStart, attrEnd) {
19057       var nodes = [];
19058       var depth = 0;
19059       if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
19060         do {
19061           if (!node) {
19062             throw $compileMinErr('uterdir',
19063                       'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.',
19064                       attrStart, attrEnd);
19065           }
19066           if (node.nodeType === NODE_TYPE_ELEMENT) {
19067             if (node.hasAttribute(attrStart)) depth++;
19068             if (node.hasAttribute(attrEnd)) depth--;
19069           }
19070           nodes.push(node);
19071           node = node.nextSibling;
19072         } while (depth > 0);
19073       } else {
19074         nodes.push(node);
19075       }
19076
19077       return jqLite(nodes);
19078     }
19079
19080     /**
19081      * Wrapper for linking function which converts normal linking function into a grouped
19082      * linking function.
19083      * @param linkFn
19084      * @param attrStart
19085      * @param attrEnd
19086      * @returns {Function}
19087      */
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);
19092       };
19093     }
19094
19095     /**
19096      * A function generator that is used to support both eager and lazy compilation
19097      * linking function.
19098      * @param eager
19099      * @param $compileNodes
19100      * @param transcludeFn
19101      * @param maxPriority
19102      * @param ignoreDirective
19103      * @param previousCompileContext
19104      * @returns {Function}
19105      */
19106     function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
19107       var compiled;
19108
19109       if (eager) {
19110         return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
19111       }
19112       return /** @this */ function lazyCompilation() {
19113         if (!compiled) {
19114           compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
19115
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;
19119         }
19120         return compiled.apply(this, arguments);
19121       };
19122     }
19123
19124     /**
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.
19128      *
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
19138      *                              on it.
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
19144      *                                        node
19145      * @returns {Function} linkFn
19146      */
19147     function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
19148                                    jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
19149                                    previousCompileContext) {
19150       previousCompileContext = previousCompileContext || {};
19151
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),
19162           directive,
19163           directiveName,
19164           $template,
19165           replaceDirective = originalReplaceDirective,
19166           childTranscludeFn = transcludeFn,
19167           linkFn,
19168           didScanForMultipleTransclusion = false,
19169           mightHaveMultipleTransclusionError = false,
19170           directiveValue;
19171
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;
19177
19178         // collect multiblock sections
19179         if (attrStart) {
19180           $compileNode = groupScan(compileNode, attrStart, attrEnd);
19181         }
19182         $template = undefined;
19183
19184         if (terminalPriority > directive.priority) {
19185           break; // prevent further processing of directives
19186         }
19187
19188         directiveValue = directive.scope;
19189
19190         if (directiveValue) {
19191
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;
19201             } else {
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,
19205                                 $compileNode);
19206             }
19207           }
19208
19209           newScopeDirective = newScopeDirective || directive;
19210         }
19211
19212         directiveName = directive.name;
19213
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;
19223
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;
19228                         break;
19229                     }
19230                 }
19231
19232                 didScanForMultipleTransclusion = true;
19233         }
19234
19235         if (!directive.templateUrl && directive.controller) {
19236           controllerDirectives = controllerDirectives || createMap();
19237           assertNoDuplicate('\'' + directiveName + '\' controller',
19238               controllerDirectives[directiveName], directive, $compileNode);
19239           controllerDirectives[directiveName] = directive;
19240         }
19241
19242         directiveValue = directive.transclude;
19243
19244         if (directiveValue) {
19245           hasTranscludeDirective = true;
19246
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;
19253           }
19254
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);
19263
19264             // Support: Chrome < 50
19265             // https://github.com/angular/angular.js/issues/14041
19266
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
19271             // behavior.
19272             // TODO: remove this line after Chrome 50 has been released
19273             $template[0].$$parentNode = $template[0].parentNode;
19274
19275             childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
19276                                         replaceDirective && replaceDirective.name, {
19277                                           // Don't pass in:
19278                                           // - controllerDirectives - otherwise we'll create duplicates controllers
19279                                           // - newIsolateScopeDirective or templateDirective - combining templates with
19280                                           //   element transclusion doesn't make sense.
19281                                           //
19282                                           // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
19283                                           // on the same element more than once.
19284                                           nonTlbTranscludeDirective: nonTlbTranscludeDirective
19285                                         });
19286           } else {
19287
19288             var slots = createMap();
19289
19290             $template = jqLite(jqLiteClone(compileNode)).contents();
19291
19292             if (isObject(directiveValue)) {
19293
19294               // We have transclusion slots,
19295               // collect them up, compile them and store their transclusion functions
19296               $template = [];
19297
19298               var slotMap = createMap();
19299               var filledSlots = createMap();
19300
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;
19306
19307                 slotMap[elementSelector] = slotName;
19308
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;
19313
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;
19317               });
19318
19319               // Add the matching elements into their slot
19320               forEach($compileNode.contents(), function(node) {
19321                 var slotName = slotMap[directiveNormalize(nodeName_(node))];
19322                 if (slotName) {
19323                   filledSlots[slotName] = true;
19324                   slots[slotName] = slots[slotName] || [];
19325                   slots[slotName].push(node);
19326                 } else {
19327                   $template.push(node);
19328                 }
19329               });
19330
19331               // Check for required slots that were not filled
19332               forEach(filledSlots, function(filled, slotName) {
19333                 if (!filled) {
19334                   throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
19335                 }
19336               });
19337
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);
19342                 }
19343               }
19344             }
19345
19346             $compileNode.empty(); // clear contents
19347             childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
19348                 undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
19349             childTranscludeFn.$$slots = slots;
19350           }
19351         }
19352
19353         if (directive.template) {
19354           hasTemplate = true;
19355           assertNoDuplicate('template', templateDirective, directive, $compileNode);
19356           templateDirective = directive;
19357
19358           directiveValue = (isFunction(directive.template))
19359               ? directive.template($compileNode, templateAttrs)
19360               : directive.template;
19361
19362           directiveValue = denormalizeTemplate(directiveValue);
19363
19364           if (directive.replace) {
19365             replaceDirective = directive;
19366             if (jqLiteIsTextNode(directiveValue)) {
19367               $template = [];
19368             } else {
19369               $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
19370             }
19371             compileNode = $template[0];
19372
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, '');
19377             }
19378
19379             replaceWith(jqCollection, $compileNode, compileNode);
19380
19381             var newTemplateAttrs = {$attr: {}};
19382
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));
19390
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);
19396             }
19397             directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
19398             mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
19399
19400             ii = directives.length;
19401           } else {
19402             $compileNode.html(directiveValue);
19403           }
19404         }
19405
19406         if (directive.templateUrl) {
19407           hasTemplate = true;
19408           assertNoDuplicate('template', templateDirective, directive, $compileNode);
19409           templateDirective = directive;
19410
19411           if (directive.replace) {
19412             replaceDirective = directive;
19413           }
19414
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
19423               });
19424           ii = directives.length;
19425         } else if (directive.compile) {
19426           try {
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);
19433             }
19434           } catch (e) {
19435             $exceptionHandler(e, startingTag($compileNode));
19436           }
19437         }
19438
19439         if (directive.terminal) {
19440           nodeLinkFn.terminal = true;
19441           terminalPriority = Math.max(terminalPriority, directive.priority);
19442         }
19443
19444       }
19445
19446       nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
19447       nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
19448       nodeLinkFn.templateOnThisElement = hasTemplate;
19449       nodeLinkFn.transclude = childTranscludeFn;
19450
19451       previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
19452
19453       // might be normal or delayed nodeLinkFn depending on if templateUrl is present
19454       return nodeLinkFn;
19455
19456       ////////////////////
19457
19458       function addLinkFns(pre, post, attrStart, attrEnd) {
19459         if (pre) {
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});
19465           }
19466           preLinkFns.push(pre);
19467         }
19468         if (post) {
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});
19474           }
19475           postLinkFns.push(post);
19476         }
19477       }
19478
19479       function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
19480         var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
19481             attrs, scopeBindingInfo;
19482
19483         if (compileNode === linkNode) {
19484           attrs = templateAttrs;
19485           $element = templateAttrs.$$element;
19486         } else {
19487           $element = jqLite(linkNode);
19488           attrs = new Attributes($element, templateAttrs);
19489         }
19490
19491         controllerScope = scope;
19492         if (newIsolateScopeDirective) {
19493           isolateScope = scope.$new(true);
19494         } else if (newScopeDirective) {
19495           controllerScope = scope.$parent;
19496         }
19497
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];
19506           };
19507         }
19508
19509         if (controllerDirectives) {
19510           elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
19511         }
19512
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);
19525           }
19526         }
19527
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;
19533
19534           if (preAssignBindingsEnabled) {
19535             if (bindings) {
19536               controller.bindingInfo =
19537                 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
19538             } else {
19539               controller.bindingInfo = {};
19540             }
19541
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();
19550               }
19551               controller.bindingInfo =
19552                 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
19553             }
19554           } else {
19555             controller.instance = controller();
19556             $element.data('$' + controllerDirective.name + 'Controller', controller.instance);
19557             controller.bindingInfo =
19558               initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
19559           }
19560         }
19561
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));
19567           }
19568         });
19569
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)) {
19574             try {
19575               controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
19576             } catch (e) {
19577               $exceptionHandler(e);
19578             }
19579           }
19580           if (isFunction(controllerInstance.$onInit)) {
19581             try {
19582               controllerInstance.$onInit();
19583             } catch (e) {
19584               $exceptionHandler(e);
19585             }
19586           }
19587           if (isFunction(controllerInstance.$doCheck)) {
19588             controllerScope.$watch(function() { controllerInstance.$doCheck(); });
19589             controllerInstance.$doCheck();
19590           }
19591           if (isFunction(controllerInstance.$onDestroy)) {
19592             controllerScope.$on('$destroy', function callOnDestroyHook() {
19593               controllerInstance.$onDestroy();
19594             });
19595           }
19596         });
19597
19598         // PRELINKING
19599         for (i = 0, ii = preLinkFns.length; i < ii; i++) {
19600           linkFn = preLinkFns[i];
19601           invokeLinkFn(linkFn,
19602               linkFn.isolateScope ? isolateScope : scope,
19603               $element,
19604               attrs,
19605               linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
19606               transcludeFn
19607           );
19608         }
19609
19610         // RECURSION
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;
19616         }
19617         if (childLinkFn) {
19618           childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
19619         }
19620
19621         // POSTLINKING
19622         for (i = postLinkFns.length - 1; i >= 0; i--) {
19623           linkFn = postLinkFns[i];
19624           invokeLinkFn(linkFn,
19625               linkFn.isolateScope ? isolateScope : scope,
19626               $element,
19627               attrs,
19628               linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
19629               transcludeFn
19630           );
19631         }
19632
19633         // Trigger $postLink lifecycle hooks
19634         forEach(elementControllers, function(controller) {
19635           var controllerInstance = controller.instance;
19636           if (isFunction(controllerInstance.$postLink)) {
19637             controllerInstance.$postLink();
19638           }
19639         });
19640
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;
19650             scope = undefined;
19651           }
19652
19653           if (hasElementTranscludeDirective) {
19654             transcludeControllers = elementControllers;
19655           }
19656           if (!futureParentElement) {
19657             futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
19658           }
19659           if (slotName) {
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}". ' +
19670                'Element: {1}',
19671                slotName, startingTag($element));
19672             }
19673           } else {
19674             return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
19675           }
19676         }
19677       }
19678     }
19679
19680     function getControllers(directiveName, require, $element, elementControllers) {
19681       var value;
19682
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] === '?';
19688
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
19694         } else {
19695           value = elementControllers && elementControllers[name];
19696           value = value && value.instance;
19697         }
19698
19699         if (!value) {
19700           var dataName = '$' + name + 'Controller';
19701           value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
19702         }
19703
19704         if (!value && !optional) {
19705           throw $compileMinErr('ctreq',
19706               'Controller \'{0}\', required by directive \'{1}\', can\'t be found!',
19707               name, directiveName);
19708         }
19709       } else if (isArray(require)) {
19710         value = [];
19711         for (var i = 0, ii = require.length; i < ii; i++) {
19712           value[i] = getControllers(directiveName, require[i], $element, elementControllers);
19713         }
19714       } else if (isObject(require)) {
19715         value = {};
19716         forEach(require, function(controller, property) {
19717           value[property] = getControllers(directiveName, controller, $element, elementControllers);
19718         });
19719       }
19720
19721       return value || null;
19722     }
19723
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];
19728         var locals = {
19729           $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
19730           $element: $element,
19731           $attrs: attrs,
19732           $transclude: transcludeFn
19733         };
19734
19735         var controller = directive.controller;
19736         if (controller === '@') {
19737           controller = attrs[directive.name];
19738         }
19739
19740         var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
19741
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);
19748       }
19749       return elementControllers;
19750     }
19751
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});
19761       }
19762     }
19763
19764     /**
19765      * looks up the directive and decorates it with exception handling and proper parameters. We
19766      * call this the boundDirective.
19767      *
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:
19771      *
19772      *   * `E`: element name
19773      *   * `A': attribute
19774      *   * `C`: class
19775      *   * `M`: comment
19776      * @returns {boolean} true if directive was added.
19777      */
19778     function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
19779                           endAttrName) {
19780       if (name === ignoreDirective) return null;
19781       var match = 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});
19790             }
19791             if (!directive.$$bindings) {
19792               var bindings = directive.$$bindings =
19793                   parseDirectiveBindings(directive, directive.name);
19794               if (isObject(bindings.isolateScope)) {
19795                 directive.$$isolateBindings = bindings.isolateScope;
19796               }
19797             }
19798             tDirectives.push(directive);
19799             match = directive;
19800           }
19801         }
19802       }
19803       return match;
19804     }
19805
19806
19807     /**
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
19810      * together.
19811      *
19812      * @param {string} name name of the directive to look up.
19813      * @returns true if directive was registered as multi-element.
19814      */
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) {
19821             return true;
19822           }
19823         }
19824       }
19825       return false;
19826     }
19827
19828     /**
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.
19832      *
19833      * @param {object} dst destination attributes (original DOM)
19834      * @param {object} src source attributes (from the directive template)
19835      */
19836     function mergeTemplateAttributes(dst, src) {
19837       var srcAttr = src.$attr,
19838           dstAttr = dst.$attr;
19839
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];
19845           }
19846           dst.$set(key, value, true, srcAttr[key]);
19847         }
19848       });
19849
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) !== '$') {
19857           dst[key] = value;
19858
19859           if (key !== 'class' && key !== 'style') {
19860             dstAttr[key] = srcAttr[key];
19861           }
19862         }
19863       });
19864     }
19865
19866
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
19876           }),
19877           templateUrl = (isFunction(origAsyncDirective.templateUrl))
19878               ? origAsyncDirective.templateUrl($compileNode, tAttrs)
19879               : origAsyncDirective.templateUrl,
19880           templateNamespace = origAsyncDirective.templateNamespace;
19881
19882       $compileNode.empty();
19883
19884       $templateRequest(templateUrl)
19885         .then(function(content) {
19886           var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
19887
19888           content = denormalizeTemplate(content);
19889
19890           if (origAsyncDirective.replace) {
19891             if (jqLiteIsTextNode(content)) {
19892               $template = [];
19893             } else {
19894               $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
19895             }
19896             compileNode = $template[0];
19897
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);
19902             }
19903
19904             tempTemplateAttrs = {$attr: {}};
19905             replaceWith($rootElement, $compileNode, compileNode);
19906             var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
19907
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);
19912             }
19913             directives = templateDirectives.concat(directives);
19914             mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
19915           } else {
19916             compileNode = beforeTemplateCompileNode;
19917             $compileNode.html(content);
19918           }
19919
19920           directives.unshift(derivedSyncDirective);
19921
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];
19928             }
19929           });
19930           afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
19931
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];
19938
19939             if (scope.$$destroyed) continue;
19940
19941             if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
19942               var oldClasses = beforeTemplateLinkNode.className;
19943
19944               if (!(previousCompileContext.hasElementTranscludeDirective &&
19945                   origAsyncDirective.replace)) {
19946                 // it was cloned therefore we have to clone as well.
19947                 linkNode = jqLiteClone(compileNode);
19948               }
19949               replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
19950
19951               // Copy in CSS classes from original node
19952               safeAddClass(jqLite(linkNode), oldClasses);
19953             }
19954             if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
19955               childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
19956             } else {
19957               childBoundTranscludeFn = boundTranscludeFn;
19958             }
19959             afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
19960               childBoundTranscludeFn);
19961           }
19962           linkQueue = null;
19963         });
19964
19965       return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
19966         var childBoundTranscludeFn = boundTranscludeFn;
19967         if (scope.$$destroyed) return;
19968         if (linkQueue) {
19969           linkQueue.push(scope,
19970                          node,
19971                          rootElement,
19972                          childBoundTranscludeFn);
19973         } else {
19974           if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
19975             childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
19976           }
19977           afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
19978         }
19979       };
19980     }
19981
19982
19983     /**
19984      * Sorting function for bound directives.
19985      */
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;
19991     }
19992
19993     function assertNoDuplicate(what, previousDirective, directive, element) {
19994
19995       function wrapModuleNameIfDefined(moduleName) {
19996         return moduleName ?
19997           (' (module: ' + moduleName + ')') :
19998           '';
19999       }
20000
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));
20005       }
20006     }
20007
20008
20009     function addTextInterpolateDirective(directives, text) {
20010       var interpolateFn = $interpolate(text, true);
20011       if (interpolateFn) {
20012         directives.push({
20013           priority: 0,
20014           compile: function textInterpolateCompileFn(templateNode) {
20015             var templateNodeParent = templateNode.parent(),
20016                 hasCompileParent = !!templateNodeParent.length;
20017
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);
20021
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;
20028               });
20029             };
20030           }
20031         });
20032       }
20033     }
20034
20035
20036     function wrapTemplate(type, template) {
20037       type = lowercase(type || 'html');
20038       switch (type) {
20039       case 'svg':
20040       case 'math':
20041         var wrapper = window.document.createElement('div');
20042         wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
20043         return wrapper.childNodes[0].childNodes;
20044       default:
20045         return template;
20046       }
20047     }
20048
20049
20050     function getTrustedContext(node, attrNormalizedName) {
20051       if (attrNormalizedName === 'srcdoc') {
20052         return $sce.HTML;
20053       }
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;
20060         }
20061       // maction[xlink:href] can source SVG.  It's not limited to <maction>.
20062       } else if (attrNormalizedName === 'xlinkHref' ||
20063           (tag === 'form' && attrNormalizedName === 'action')
20064       ) {
20065         return $sce.RESOURCE_URL;
20066       }
20067     }
20068
20069
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;
20074
20075       var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing);
20076
20077       // no interpolation found -> ignore
20078       if (!interpolateFn) return;
20079
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));
20084       }
20085
20086       directives.push({
20087         priority: 100,
20088         compile: function() {
20089             return {
20090               pre: function attrInterpolatePreLinkFn(scope, element, attr) {
20091                 var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
20092
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.');
20097                 }
20098
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);
20106                   value = newValue;
20107                 }
20108
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;
20112
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);
20117
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);
20129                     } else {
20130                       attr.$set(name, newValue);
20131                     }
20132                   });
20133               }
20134             };
20135           }
20136       });
20137     }
20138
20139
20140     /**
20141      * This is a special jqLite.replaceWith, which can replace items which
20142      * have no parents, provided that the containing jqLite collection is provided.
20143      *
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.
20149      */
20150     function replaceWith($rootElement, elementsToRemove, newNode) {
20151       var firstElementToRemove = elementsToRemove[0],
20152           removeCount = elementsToRemove.length,
20153           parent = firstElementToRemove.parentNode,
20154           i, ii;
20155
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++) {
20163               if (j2 < jj) {
20164                 $rootElement[j] = $rootElement[j2];
20165               } else {
20166                 delete $rootElement[j];
20167               }
20168             }
20169             $rootElement.length -= removeCount - 1;
20170
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;
20176             }
20177             break;
20178           }
20179         }
20180       }
20181
20182       if (parent) {
20183         parent.replaceChild(newNode, firstElementToRemove);
20184       }
20185
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]);
20193       }
20194
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));
20200
20201         // Remove $destroy event listeners from `firstElementToRemove`
20202         jqLite(firstElementToRemove).off('$destroy');
20203       }
20204
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('*'));
20208
20209       // Update the jqLite collection to only contain the `newNode`
20210       for (i = 1; i < removeCount; i++) {
20211         delete elementsToRemove[i];
20212       }
20213       elementsToRemove[0] = newNode;
20214       elementsToRemove.length = 1;
20215     }
20216
20217
20218     function cloneAndAnnotateFn(fn, annotation) {
20219       return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
20220     }
20221
20222
20223     function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
20224       try {
20225         linkFn(scope, $element, attrs, controllers, transcludeFn);
20226       } catch (e) {
20227         $exceptionHandler(e, startingTag($element));
20228       }
20229     }
20230
20231
20232     // Set up $watches for isolate scope and controller bindings.
20233     function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
20234       var removeWatchCollection = [];
20235       var initialChanges = {};
20236       var changes;
20237       forEach(bindings, function initializeBinding(definition, scopeName) {
20238         var attrName = definition.attrName,
20239         optional = definition.optional,
20240         mode = definition.mode, // @, =, <, or &
20241         lastValue,
20242         parentGet, parentSet, compare, removeWatch;
20243
20244         switch (mode) {
20245
20246           case '@':
20247             if (!optional && !hasOwnProperty.call(attrs, attrName)) {
20248               destination[scopeName] = attrs[attrName] = undefined;
20249             }
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;
20255               }
20256             });
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;
20267             }
20268             initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
20269             removeWatchCollection.push(removeWatch);
20270             break;
20271
20272           case '=':
20273             if (!hasOwnProperty.call(attrs, attrName)) {
20274               if (optional) break;
20275               attrs[attrName] = undefined;
20276             }
20277             if (optional && !attrs[attrName]) break;
20278
20279             parentGet = $parse(attrs[attrName]);
20280             if (parentGet.literal) {
20281               compare = equals;
20282             } else {
20283               // eslint-disable-next-line no-self-compare
20284               compare = function simpleCompare(a, b) { return a === b || (a !== a && b !== b); };
20285             }
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);
20292             };
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;
20300                 } else {
20301                   // if the parent can be assigned then do so
20302                   parentSet(scope, parentValue = destination[scopeName]);
20303                 }
20304               }
20305               lastValue = parentValue;
20306               return lastValue;
20307             };
20308             parentValueWatch.$stateful = true;
20309             if (definition.collection) {
20310               removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
20311             } else {
20312               removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
20313             }
20314             removeWatchCollection.push(removeWatch);
20315             break;
20316
20317           case '<':
20318             if (!hasOwnProperty.call(attrs, attrName)) {
20319               if (optional) break;
20320               attrs[attrName] = undefined;
20321             }
20322             if (optional && !attrs[attrName]) break;
20323
20324             parentGet = $parse(attrs[attrName]);
20325             var deepWatch = parentGet.literal;
20326
20327             var initialValue = destination[scopeName] = parentGet(scope);
20328             initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
20329
20330             removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) {
20331               if (oldValue === newValue) {
20332                 if (oldValue === initialValue || (deepWatch && equals(oldValue, initialValue))) {
20333                   return;
20334                 }
20335                 oldValue = initialValue;
20336               }
20337               recordChanges(scopeName, newValue, oldValue);
20338               destination[scopeName] = newValue;
20339             }, deepWatch);
20340
20341             removeWatchCollection.push(removeWatch);
20342             break;
20343
20344           case '&':
20345             // Don't assign Object.prototype method to scope
20346             parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
20347
20348             // Don't assign noop to destination if expression is not valid
20349             if (parentGet === noop && optional) break;
20350
20351             destination[scopeName] = function(locals) {
20352               return parentGet(scope, locals);
20353             };
20354             break;
20355         }
20356       });
20357
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 = [];
20366           }
20367           // If we have not already queued a trigger of onChanges for this controller then do so now
20368           if (!changes) {
20369             changes = {};
20370             onChangesQueue.push(triggerOnChangesHook);
20371           }
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;
20375           }
20376           // Store this change
20377           changes[key] = new SimpleChange(previousValue, currentValue);
20378         }
20379       }
20380
20381       function triggerOnChangesHook() {
20382         destination.$onChanges(changes);
20383         // Now clear the changes so that we schedule onChanges when more changes arrive
20384         changes = undefined;
20385       }
20386
20387       return {
20388         initialChanges: initialChanges,
20389         removeWatches: removeWatchCollection.length && function removeWatches() {
20390           for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
20391             removeWatchCollection[i]();
20392           }
20393         }
20394       };
20395     }
20396   }];
20397 }
20398
20399 function SimpleChange(previous, current) {
20400   this.previousValue = previous;
20401   this.currentValue = current;
20402 }
20403 SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
20404
20405
20406 var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i;
20407 /**
20408  * Converts all accepted directives format into proper directive name.
20409  * @param name Name to normalize
20410  */
20411 function directiveNormalize(name) {
20412   return camelCase(name.replace(PREFIX_REGEXP, ''));
20413 }
20414
20415 /**
20416  * @ngdoc type
20417  * @name $compile.directive.Attributes
20418  *
20419  * @description
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:
20423  *
20424  * ```
20425  *    <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
20426  * ```
20427  */
20428
20429 /**
20430  * @ngdoc property
20431  * @name $compile.directive.Attributes#$attr
20432  *
20433  * @description
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.
20436  */
20437
20438
20439 /**
20440  * @ngdoc method
20441  * @name $compile.directive.Attributes#$set
20442  * @kind function
20443  *
20444  * @description
20445  * Set DOM element attribute value.
20446  *
20447  *
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.
20452  */
20453
20454
20455
20456 /**
20457  * Closure compiler type information
20458  */
20459
20460 function nodesetLinkingFn(
20461   /* angular.Scope */ scope,
20462   /* NodeList */ nodeList,
20463   /* Element */ rootElement,
20464   /* function(Function) */ boundTranscludeFn
20465 ) {}
20466
20467 function directiveLinkingFn(
20468   /* nodesetLinkingFn */ nodesetLinkingFn,
20469   /* angular.Scope */ scope,
20470   /* Node */ node,
20471   /* Element */ rootElement,
20472   /* function(Function) */ boundTranscludeFn
20473 ) {}
20474
20475 function tokenDifference(str1, str2) {
20476   var values = '',
20477       tokens1 = str1.split(/\s+/),
20478       tokens2 = str2.split(/\s+/);
20479
20480   outer:
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;
20485     }
20486     values += (values.length > 0 ? ' ' : '') + token;
20487   }
20488   return values;
20489 }
20490
20491 function removeComments(jqNodes) {
20492   jqNodes = jqLite(jqNodes);
20493   var i = jqNodes.length;
20494
20495   if (i <= 1) {
20496     return jqNodes;
20497   }
20498
20499   while (i--) {
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);
20504     }
20505   }
20506   return jqNodes;
20507 }
20508
20509 var $controllerMinErr = minErr('$controller');
20510
20511
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];
20518   }
20519 }
20520
20521
20522 /**
20523  * @ngdoc provider
20524  * @name $controllerProvider
20525  * @this
20526  *
20527  * @description
20528  * The {@link ng.$controller $controller service} is used by Angular to create new
20529  * controllers.
20530  *
20531  * This provider allows controller registration via the
20532  * {@link ng.$controllerProvider#register register} method.
20533  */
20534 function $ControllerProvider() {
20535   var controllers = {},
20536       globals = false;
20537
20538   /**
20539    * @ngdoc method
20540    * @name $controllerProvider#has
20541    * @param {string} name Controller name to check.
20542    */
20543   this.has = function(name) {
20544     return controllers.hasOwnProperty(name);
20545   };
20546
20547   /**
20548    * @ngdoc method
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).
20554    */
20555   this.register = function(name, constructor) {
20556     assertNotHasOwnProperty(name, 'controller');
20557     if (isObject(name)) {
20558       extend(controllers, name);
20559     } else {
20560       controllers[name] = constructor;
20561     }
20562   };
20563
20564   /**
20565    * @ngdoc method
20566    * @name $controllerProvider#allowGlobals
20567    *
20568    * @deprecated
20569    * sinceVersion="v1.3.0"
20570    * removeVersion="v1.7.0"
20571    * This method of finding controllers has been deprecated.
20572    *
20573    * @description If called, allows `$controller` to find controller constructors on `window`   *
20574    */
20575   this.allowGlobals = function() {
20576     globals = true;
20577   };
20578
20579
20580   this.$get = ['$injector', '$window', function($injector, $window) {
20581
20582     /**
20583      * @ngdoc service
20584      * @name $controller
20585      * @requires $injector
20586      *
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:
20590      *
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)
20595      *
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.
20599      *
20600      * @param {Object} locals Injection locals for Controller.
20601      * @return {Object} Instance of given controller.
20602      *
20603      * @description
20604      * `$controller` service is responsible for instantiating controllers.
20605      *
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).
20608      */
20609     return function $controller(expression, locals, later, ident) {
20610       // PRIVATE API:
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;
20621       }
20622
20623       if (isString(expression)) {
20624         match = expression.match(CNTRL_REG);
20625         if (!match) {
20626           throw $controllerMinErr('ctrlfmt',
20627             'Badly formed controller string \'{0}\'. ' +
20628             'Must match `__name__ as __id__` or `__name__`.', expression);
20629         }
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);
20636
20637         if (!expression) {
20638           throw $controllerMinErr('ctrlreg',
20639             'The controller with the name \'{0}\' is not registered.', constructor);
20640         }
20641
20642         assertArgFn(expression, constructor, true);
20643       }
20644
20645       if (later) {
20646         // Instantiate controller later:
20647         // This machinery is used to create an instance of the object before calling the
20648         // controller's constructor itself.
20649         //
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.
20652         //
20653         // This feature is not intended for use by applications, and is thus not documented
20654         // publicly.
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);
20659
20660         if (identifier) {
20661           addIdentifier(locals, identifier, instance, constructor || expression.name);
20662         }
20663
20664         return extend(function $controllerInit() {
20665           var result = $injector.invoke(expression, instance, locals, constructor);
20666           if (result !== instance && (isObject(result) || isFunction(result))) {
20667             instance = result;
20668             if (identifier) {
20669               // If result changed, re-assign controllerAs value to scope.
20670               addIdentifier(locals, identifier, instance, constructor || expression.name);
20671             }
20672           }
20673           return instance;
20674         }, {
20675           instance: instance,
20676           identifier: identifier
20677         });
20678       }
20679
20680       instance = $injector.instantiate(expression, locals, constructor);
20681
20682       if (identifier) {
20683         addIdentifier(locals, identifier, instance, constructor || expression.name);
20684       }
20685
20686       return instance;
20687     };
20688
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`.',
20693           name, identifier);
20694       }
20695
20696       locals.$scope[identifier] = instance;
20697     }
20698   }];
20699 }
20700
20701 /**
20702  * @ngdoc service
20703  * @name $document
20704  * @requires $window
20705  * @this
20706  *
20707  * @description
20708  * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
20709  *
20710  * @example
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>
20716        </div>
20717      </file>
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;
20723          }]);
20724      </file>
20725    </example>
20726  */
20727 function $DocumentProvider() {
20728   this.$get = ['$window', function(window) {
20729     return jqLite(window.document);
20730   }];
20731 }
20732
20733 /**
20734  * @ngdoc service
20735  * @name $exceptionHandler
20736  * @requires ng.$log
20737  * @this
20738  *
20739  * @description
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.
20743  *
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.
20746  *
20747  * ## Example:
20748  *
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()`.
20752  *
20753  * ```js
20754  *   angular.
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);
20760  *       };
20761  *     }]);
20762  * ```
20763  *
20764  * <hr />
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).
20768  *
20769  * If you wish, you can manually delegate exceptions, e.g.
20770  * `try { ... } catch(e) { $exceptionHandler(e); }`
20771  *
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.
20775  *
20776  */
20777 function $ExceptionHandlerProvider() {
20778   this.$get = ['$log', function($log) {
20779     return function(exception, cause) {
20780       $log.error.apply($log, arguments);
20781     };
20782   }];
20783 }
20784
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.
20796       if (domNode) {
20797         if (!domNode.nodeType && domNode instanceof jqLite) {
20798           domNode = domNode[0];
20799         }
20800       } else {
20801         domNode = $document[0].body;
20802       }
20803       return domNode.offsetWidth + 1;
20804     };
20805   }];
20806 };
20807
20808 var APPLICATION_JSON = 'application/json';
20809 var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
20810 var JSON_START = /^\[|^\{(?!\{)/;
20811 var JSON_ENDS = {
20812   '[': /]$/,
20813   '{': /}$/
20814 };
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);
20820   };
20821 };
20822
20823 function serializeValue(v) {
20824   if (isObject(v)) {
20825     return isDate(v) ? v.toISOString() : toJson(v);
20826   }
20827   return v;
20828 }
20829
20830
20831 /** @this */
20832 function $HttpParamSerializerProvider() {
20833   /**
20834    * @ngdoc service
20835    * @name $httpParamSerializer
20836    * @description
20837    *
20838    * Default {@link $http `$http`} params serializer that converts objects to strings
20839    * according to the following rules:
20840    *
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)
20845    *
20846    * Note that serializer will sort the request parameters alphabetically.
20847    * */
20848
20849   this.$get = function() {
20850     return function ngParamSerializer(params) {
20851       if (!params) return '';
20852       var parts = [];
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)));
20858           });
20859         } else {
20860           parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
20861         }
20862       });
20863
20864       return parts.join('&');
20865     };
20866   };
20867 }
20868
20869 /** @this */
20870 function $HttpParamSerializerJQLikeProvider() {
20871   /**
20872    * @ngdoc service
20873    * @name $httpParamSerializerJQLike
20874    *
20875    * @description
20876    *
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.
20880    *
20881    * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
20882    *
20883    * ```js
20884    * $http({
20885    *   url: myUrl,
20886    *   method: 'GET',
20887    *   params: myParams,
20888    *   paramSerializer: '$httpParamSerializerJQLike'
20889    * });
20890    * ```
20891    *
20892    * It is also possible to set it as the default `paramSerializer` in the
20893    * {@link $httpProvider#defaults `$httpProvider`}.
20894    *
20895    * Additionally, you can inject the serializer and use it explicitly, for example to serialize
20896    * form data for submission:
20897    *
20898    * ```js
20899    * .controller(function($http, $httpParamSerializerJQLike) {
20900    *   //...
20901    *
20902    *   $http({
20903    *     url: myUrl,
20904    *     method: 'POST',
20905    *     data: $httpParamSerializerJQLike(myData),
20906    *     headers: {
20907    *       'Content-Type': 'application/x-www-form-urlencoded'
20908    *     }
20909    *   });
20910    *
20911    * });
20912    * ```
20913    *
20914    * */
20915   this.$get = function() {
20916     return function jQueryLikeParamSerializer(params) {
20917       if (!params) return '';
20918       var parts = [];
20919       serialize(params, '', true);
20920       return parts.join('&');
20921
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 : '') + ']');
20927           });
20928         } else if (isObject(toSerialize) && !isDate(toSerialize)) {
20929           forEachSorted(toSerialize, function(value, key) {
20930             serialize(value, prefix +
20931                 (topLevel ? '' : '[') +
20932                 key +
20933                 (topLevel ? '' : ']'));
20934           });
20935         } else {
20936           parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
20937         }
20938       }
20939     };
20940   };
20941 }
20942
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();
20947
20948     if (tempData) {
20949       var contentType = headers('Content-Type');
20950       if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
20951         data = fromJson(tempData);
20952       }
20953     }
20954   }
20955
20956   return data;
20957 }
20958
20959 function isJsonLike(str) {
20960     var jsonStart = str.match(JSON_START);
20961     return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
20962 }
20963
20964 /**
20965  * Parse headers into key value object
20966  *
20967  * @param {string} headers Raw headers as a string
20968  * @returns {Object} Parsed headers as key value object
20969  */
20970 function parseHeaders(headers) {
20971   var parsed = createMap(), i;
20972
20973   function fillInParsed(key, val) {
20974     if (key) {
20975       parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
20976     }
20977   }
20978
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)));
20983     });
20984   } else if (isObject(headers)) {
20985     forEach(headers, function(headerVal, headerKey) {
20986       fillInParsed(lowercase(headerKey), trim(headerVal));
20987     });
20988   }
20989
20990   return parsed;
20991 }
20992
20993
20994 /**
20995  * Returns a function that provides access to parsed headers.
20996  *
20997  * Headers are lazy parsed when first requested.
20998  * @see parseHeaders
20999  *
21000  * @param {(string|Object)} headers Headers to provide access to.
21001  * @returns {function(string=)} Returns a getter function which if called with:
21002  *
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.
21005  */
21006 function headersGetter(headers) {
21007   var headersObj;
21008
21009   return function(name) {
21010     if (!headersObj) headersObj =  parseHeaders(headers);
21011
21012     if (name) {
21013       var value = headersObj[lowercase(name)];
21014       if (value === undefined) {
21015         value = null;
21016       }
21017       return value;
21018     }
21019
21020     return headersObj;
21021   };
21022 }
21023
21024
21025 /**
21026  * Chain all given functions
21027  *
21028  * This function is used for both request and response transforming
21029  *
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.
21035  */
21036 function transformData(data, headers, status, fns) {
21037   if (isFunction(fns)) {
21038     return fns(data, headers, status);
21039   }
21040
21041   forEach(fns, function(fn) {
21042     data = fn(data, headers, status);
21043   });
21044
21045   return data;
21046 }
21047
21048
21049 function isSuccess(status) {
21050   return 200 <= status && status < 300;
21051 }
21052
21053
21054 /**
21055  * @ngdoc provider
21056  * @name $httpProvider
21057  * @this
21058  *
21059  * @description
21060  * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
21061  * */
21062 function $HttpProvider() {
21063   /**
21064    * @ngdoc property
21065    * @name $httpProvider#defaults
21066    * @description
21067    *
21068    * Object containing default values for all {@link ng.$http $http} requests.
21069    *
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.
21073    *
21074    * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
21075    * Defaults value is `'XSRF-TOKEN'`.
21076    *
21077    * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
21078    * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
21079    *
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`**
21087    *
21088    *
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}.
21093    *
21094    **/
21095   var defaults = this.defaults = {
21096     // transform incoming response data
21097     transformResponse: [defaultHttpResponseTransform],
21098
21099     // transform outgoing request data
21100     transformRequest: [function(d) {
21101       return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
21102     }],
21103
21104     // default headers
21105     headers: {
21106       common: {
21107         'Accept': 'application/json, text/plain, */*'
21108       },
21109       post:   shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
21110       put:    shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
21111       patch:  shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
21112     },
21113
21114     xsrfCookieName: 'XSRF-TOKEN',
21115     xsrfHeaderName: 'X-XSRF-TOKEN',
21116
21117     paramSerializer: '$httpParamSerializer'
21118   };
21119
21120   var useApplyAsync = false;
21121   /**
21122    * @ngdoc method
21123    * @name $httpProvider#useApplyAsync
21124    * @description
21125    *
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).
21130    *
21131    * Defaults to false. If no value is specified, returns the current configured value.
21132    *
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.
21136    *
21137    * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
21138    *    otherwise, returns the current configured value.
21139    **/
21140   this.useApplyAsync = function(value) {
21141     if (isDefined(value)) {
21142       useApplyAsync = !!value;
21143       return this;
21144     }
21145     return useApplyAsync;
21146   };
21147
21148   var useLegacyPromise = true;
21149   /**
21150    * @ngdoc method
21151    * @name $httpProvider#useLegacyPromiseExtensions
21152    * @description
21153    *
21154    * @deprecated
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.
21158    *
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.
21161    *
21162    * Defaults to true. If no value is specified, returns the current configured value.
21163    *
21164    * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
21165    *
21166    * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
21167    *    otherwise, returns the current configured value.
21168    **/
21169   this.useLegacyPromiseExtensions = function(value) {
21170     if (isDefined(value)) {
21171       useLegacyPromise = !!value;
21172       return this;
21173     }
21174     return useLegacyPromise;
21175   };
21176
21177   /**
21178    * @ngdoc property
21179    * @name $httpProvider#interceptors
21180    * @description
21181    *
21182    * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
21183    * pre-processing of request or postprocessing of responses.
21184    *
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.
21187    *
21188    * {@link ng.$http#interceptors Interceptors detailed info}
21189    **/
21190   var interceptorFactories = this.interceptors = [];
21191
21192   this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
21193       function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
21194
21195     var defaultCache = $cacheFactory('$http');
21196
21197     /**
21198      * Make sure that default param serializer is exposed as a function
21199      */
21200     defaults.paramSerializer = isString(defaults.paramSerializer) ?
21201       $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
21202
21203     /**
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
21206      * server request.
21207      */
21208     var reversedInterceptors = [];
21209
21210     forEach(interceptorFactories, function(interceptorFactory) {
21211       reversedInterceptors.unshift(isString(interceptorFactory)
21212           ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
21213     });
21214
21215     /**
21216      * @ngdoc service
21217      * @kind function
21218      * @name $http
21219      * @requires ng.$httpBackend
21220      * @requires $cacheFactory
21221      * @requires $rootScope
21222      * @requires $q
21223      * @requires $injector
21224      *
21225      * @description
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).
21229      *
21230      * For unit testing applications that use `$http` service, see
21231      * {@link ngMock.$httpBackend $httpBackend mock}.
21232      *
21233      * For a higher level of abstraction, please check out the {@link ngResource.$resource
21234      * $resource} service.
21235      *
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.
21239      *
21240      *
21241      * ## General usage
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}.
21244      *
21245      * ```js
21246      *   // Simple GET request example:
21247      *   $http({
21248      *     method: 'GET',
21249      *     url: '/someUrl'
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.
21256      *     });
21257      * ```
21258      *
21259      * The response object has these properties:
21260      *
21261      *   - **data** â€“ `{string|Object}` â€“ The response body transformed with the transform
21262      *     functions.
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.
21267      *
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.
21275      *
21276      *
21277      * ## Shortcut methods
21278      *
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
21281      * last argument.
21282      *
21283      * ```js
21284      *   $http.get('/someUrl', config).then(successCallback, errorCallback);
21285      *   $http.post('/someUrl', data, config).then(successCallback, errorCallback);
21286      * ```
21287      *
21288      * Complete list of shortcut methods:
21289      *
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}
21297      *
21298      *
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.
21303      *
21304      * ```
21305      * $httpBackend.expectGET(...);
21306      * $http.get(...);
21307      * $httpBackend.flush();
21308      * ```
21309      *
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.
21317      * </div>
21318      *
21319      * ## Setting HTTP Headers
21320      *
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:
21324      *
21325      * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
21326      *   - <code>Accept: application/json, text/plain, \*&#65279;/&#65279;\*</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`
21331      *
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' }`.
21336      *
21337      * The defaults can also be set at runtime via the `$http.defaults` object in the same
21338      * fashion. For example:
21339      *
21340      * ```
21341      * module.run(function($http) {
21342      *   $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
21343      * });
21344      * ```
21345      *
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.
21348      *
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:
21351      *
21352      * ```js
21353      * var req = {
21354      *  method: 'POST',
21355      *  url: 'http://example.com',
21356      *  headers: {
21357      *    'Content-Type': undefined
21358      *  },
21359      *  data: { test: 'test' }
21360      * }
21361      *
21362      * $http(req).then(function(){...}, function(){...});
21363      * ```
21364      *
21365      * ## Transforming Requests and Responses
21366      *
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.
21371      *
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.
21379      * </div>
21380      *
21381      * ### Default Transformations
21382      *
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.
21386      *
21387      * You can augment or replace the default transformations by modifying these properties by adding to or
21388      * replacing the array.
21389      *
21390      * Angular provides the following default transformations:
21391      *
21392      * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
21393      *
21394      * - If the `data` property of the request configuration object contains an object, serialize it
21395      *   into JSON format.
21396      *
21397      * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
21398      *
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.
21401      *
21402      *
21403      * ### Overriding the Default Transformations Per Request
21404      *
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
21407      * into `$http`.
21408      *
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.
21412      *
21413      * The following code demonstrates adding a new response transformation to be run after the default response
21414      * transformations have been run.
21415      *
21416      * ```js
21417      * function appendTransform(defaults, transform) {
21418      *
21419      *   // We can't guarantee that the default transformation is an array
21420      *   defaults = angular.isArray(defaults) ? defaults : [defaults];
21421      *
21422      *   // Append the new transformation to the defaults
21423      *   return defaults.concat(transform);
21424      * }
21425      *
21426      * $http({
21427      *   url: '...',
21428      *   method: 'GET',
21429      *   transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
21430      *     return doTransform(value);
21431      *   })
21432      * });
21433      * ```
21434      *
21435      *
21436      * ## Caching
21437      *
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.
21442      *
21443      * In order to:
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
21446      *
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.
21449      *
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.
21453      *
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.
21457      *
21458      * Take note that:
21459      *
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.
21466      *
21467      *
21468      * ## Interceptors
21469      *
21470      * Before you start creating interceptors, be sure to understand the
21471      * {@link ng.$q $q and deferred/promise APIs}.
21472      *
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.
21479      *
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.
21483      *
21484      * There are two kinds of interceptors (and two kinds of rejection interceptors):
21485      *
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.
21496      *
21497      *
21498      * ```js
21499      *   // register the interceptor as a service
21500      *   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
21501      *     return {
21502      *       // optional method
21503      *       'request': function(config) {
21504      *         // do something on success
21505      *         return config;
21506      *       },
21507      *
21508      *       // optional method
21509      *      'requestError': function(rejection) {
21510      *         // do something on error
21511      *         if (canRecover(rejection)) {
21512      *           return responseOrNewPromise
21513      *         }
21514      *         return $q.reject(rejection);
21515      *       },
21516      *
21517      *
21518      *
21519      *       // optional method
21520      *       'response': function(response) {
21521      *         // do something on success
21522      *         return response;
21523      *       },
21524      *
21525      *       // optional method
21526      *      'responseError': function(rejection) {
21527      *         // do something on error
21528      *         if (canRecover(rejection)) {
21529      *           return responseOrNewPromise
21530      *         }
21531      *         return $q.reject(rejection);
21532      *       }
21533      *     };
21534      *   });
21535      *
21536      *   $httpProvider.interceptors.push('myHttpInterceptor');
21537      *
21538      *
21539      *   // alternatively, register the interceptor via an anonymous factory
21540      *   $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
21541      *     return {
21542      *      'request': function(config) {
21543      *          // same as above
21544      *       },
21545      *
21546      *       'response': function(response) {
21547      *          // same as above
21548      *       }
21549      *     };
21550      *   });
21551      * ```
21552      *
21553      * ## Security Considerations
21554      *
21555      * When designing web applications, consider security threats from:
21556      *
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)
21559      *
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.
21563      *
21564      * ### JSON Vulnerability Protection
21565      *
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.
21571      *
21572      * For example if your server needs to return:
21573      * ```js
21574      * ['one','two']
21575      * ```
21576      *
21577      * which is vulnerable to attack, your server can return:
21578      * ```js
21579      * )]}',
21580      * ['one','two']
21581      * ```
21582      *
21583      * Angular will strip the prefix, before processing the JSON.
21584      *
21585      *
21586      * ### Cross Site Request Forgery (XSRF) Protection
21587      *
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.
21595      *
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&#41;)
21603      * for added security.
21604      *
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.
21608      *
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.
21611      *
21612      * @param {object} config Object describing the request to be made and how it should be
21613      *    processed. The object has following properties:
21614      *
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).
21660      *
21661      * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
21662      *                        when the request succeeds or fails.
21663      *
21664      *
21665      * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
21666      *   requests. This is primarily meant to be used for debugging purposes.
21667      *
21668      *
21669      * @example
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>
21676     </select>
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')">
21683       Sample JSONP
21684     </button>
21685     <button id="invalidjsonpbtn"
21686       ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
21687         Invalid JSONP
21688       </button>
21689     <pre>http status code: {{status}}</pre>
21690     <pre>http response data: {{data}}</pre>
21691   </div>
21692 </file>
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';
21699
21700         $scope.fetch = function() {
21701           $scope.code = null;
21702           $scope.response = null;
21703
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;
21711           });
21712         };
21713
21714         $scope.updateModel = function(method, url) {
21715           $scope.method = method;
21716           $scope.url = url;
21717         };
21718       }]);
21719 </file>
21720 <file name="http-hello.html">
21721   Hello, $http!
21722 </file>
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'));
21729
21730   it('should make an xhr GET request', function() {
21731     sampleGetBtn.click();
21732     fetchBtn.click();
21733     expect(status.getText()).toMatch('200');
21734     expect(data.getText()).toMatch(/Hello, \$http!/);
21735   });
21736
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!/);
21744 // });
21745
21746   it('should make JSONP request to invalid URL and invoke the error handler',
21747       function() {
21748     invalidJsonpBtn.click();
21749     fetchBtn.click();
21750     expect(status.getText()).toMatch('0');
21751     expect(data.getText()).toMatch('Request failed');
21752   });
21753 </file>
21754 </example>
21755      */
21756     function $http(requestConfig) {
21757
21758       if (!isObject(requestConfig)) {
21759         throw minErr('$http')('badreq', 'Http request configuration must be an object.  Received: {0}', requestConfig);
21760       }
21761
21762       if (!isString(requestConfig.url)) {
21763         throw minErr('$http')('badreq', 'Http request configuration url must be a string.  Received: {0}', requestConfig.url);
21764       }
21765
21766       var config = extend({
21767         method: 'get',
21768         transformRequest: defaults.transformRequest,
21769         transformResponse: defaults.transformResponse,
21770         paramSerializer: defaults.paramSerializer
21771       }, requestConfig);
21772
21773       config.headers = mergeHeaders(requestConfig);
21774       config.method = uppercase(config.method);
21775       config.paramSerializer = isString(config.paramSerializer) ?
21776           $injector.get(config.paramSerializer) : config.paramSerializer;
21777
21778       var requestInterceptors = [];
21779       var responseInterceptors = [];
21780       var promise = $q.when(config);
21781
21782       // apply interceptors
21783       forEach(reversedInterceptors, function(interceptor) {
21784         if (interceptor.request || interceptor.requestError) {
21785           requestInterceptors.unshift(interceptor.request, interceptor.requestError);
21786         }
21787         if (interceptor.response || interceptor.responseError) {
21788           responseInterceptors.push(interceptor.response, interceptor.responseError);
21789         }
21790       });
21791
21792       promise = chainInterceptors(promise, requestInterceptors);
21793       promise = promise.then(serverRequest);
21794       promise = chainInterceptors(promise, responseInterceptors);
21795
21796       if (useLegacyPromise) {
21797         promise.success = function(fn) {
21798           assertArgFn(fn, 'fn');
21799
21800           promise.then(function(response) {
21801             fn(response.data, response.status, response.headers, config);
21802           });
21803           return promise;
21804         };
21805
21806         promise.error = function(fn) {
21807           assertArgFn(fn, 'fn');
21808
21809           promise.then(null, function(response) {
21810             fn(response.data, response.status, response.headers, config);
21811           });
21812           return promise;
21813         };
21814       } else {
21815         promise.success = $httpMinErrLegacyFn('success');
21816         promise.error = $httpMinErrLegacyFn('error');
21817       }
21818
21819       return promise;
21820
21821
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++];
21826
21827           promise = promise.then(thenFn, rejectFn);
21828         }
21829
21830         interceptors.length = 0;
21831
21832         return promise;
21833       }
21834
21835       function executeHeaderFns(headers, config) {
21836         var headerContent, processedHeaders = {};
21837
21838         forEach(headers, function(headerFn, header) {
21839           if (isFunction(headerFn)) {
21840             headerContent = headerFn(config);
21841             if (headerContent != null) {
21842               processedHeaders[header] = headerContent;
21843             }
21844           } else {
21845             processedHeaders[header] = headerFn;
21846           }
21847         });
21848
21849         return processedHeaders;
21850       }
21851
21852       function mergeHeaders(config) {
21853         var defHeaders = defaults.headers,
21854             reqHeaders = extend({}, config.headers),
21855             defHeaderName, lowercaseDefHeaderName, reqHeaderName;
21856
21857         defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
21858
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);
21863
21864           for (reqHeaderName in reqHeaders) {
21865             if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
21866               continue defaultHeadersIteration;
21867             }
21868           }
21869
21870           reqHeaders[defHeaderName] = defHeaders[defHeaderName];
21871         }
21872
21873         // execute if header value is a function for merged headers
21874         return executeHeaderFns(reqHeaders, shallowCopy(config));
21875       }
21876
21877       function serverRequest(config) {
21878         var headers = config.headers;
21879         var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
21880
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];
21886             }
21887           });
21888         }
21889
21890         if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
21891           config.withCredentials = defaults.withCredentials;
21892         }
21893
21894         // send request
21895         return sendReq(config, reqData).then(transformResponse, transformResponse);
21896       }
21897
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))
21904           ? resp
21905           : $q.reject(resp);
21906       }
21907     }
21908
21909     $http.pendingRequests = [];
21910
21911     /**
21912      * @ngdoc method
21913      * @name $http#get
21914      *
21915      * @description
21916      * Shortcut method to perform `GET` request.
21917      *
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
21921      */
21922
21923     /**
21924      * @ngdoc method
21925      * @name $http#delete
21926      *
21927      * @description
21928      * Shortcut method to perform `DELETE` request.
21929      *
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
21933      */
21934
21935     /**
21936      * @ngdoc method
21937      * @name $http#head
21938      *
21939      * @description
21940      * Shortcut method to perform `HEAD` request.
21941      *
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
21945      */
21946
21947     /**
21948      * @ngdoc method
21949      * @name $http#jsonp
21950      *
21951      * @description
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.
21955      *
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
21960      */
21961     createShortMethods('get', 'delete', 'head', 'jsonp');
21962
21963     /**
21964      * @ngdoc method
21965      * @name $http#post
21966      *
21967      * @description
21968      * Shortcut method to perform `POST` request.
21969      *
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
21974      */
21975
21976     /**
21977      * @ngdoc method
21978      * @name $http#put
21979      *
21980      * @description
21981      * Shortcut method to perform `PUT` request.
21982      *
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
21987      */
21988
21989      /**
21990       * @ngdoc method
21991       * @name $http#patch
21992       *
21993       * @description
21994       * Shortcut method to perform `PATCH` request.
21995       *
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
22000       */
22001     createShortMethodsWithData('post', 'put', 'patch');
22002
22003         /**
22004          * @ngdoc property
22005          * @name $http#defaults
22006          *
22007          * @description
22008          * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
22009          * default headers, withCredentials as well as request and response transformations.
22010          *
22011          * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
22012          */
22013     $http.defaults = defaults;
22014
22015
22016     return $http;
22017
22018
22019     function createShortMethods(names) {
22020       forEach(arguments, function(name) {
22021         $http[name] = function(url, config) {
22022           return $http(extend({}, config || {}, {
22023             method: name,
22024             url: url
22025           }));
22026         };
22027       });
22028     }
22029
22030
22031     function createShortMethodsWithData(name) {
22032       forEach(arguments, function(name) {
22033         $http[name] = function(url, data, config) {
22034           return $http(extend({}, config || {}, {
22035             method: name,
22036             url: url,
22037             data: data
22038           }));
22039         };
22040       });
22041     }
22042
22043
22044     /**
22045      * Makes the request.
22046      *
22047      * !!! ACCESSES CLOSURE VARS:
22048      * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
22049      */
22050     function sendReq(config, reqData) {
22051       var deferred = $q.defer(),
22052           promise = deferred.promise,
22053           cache,
22054           cachedResp,
22055           reqHeaders = config.headers,
22056           url = buildUrl(config.url, config.paramSerializer(config.params));
22057
22058       $http.pendingRequests.push(config);
22059       promise.then(removePendingReq, removePendingReq);
22060
22061
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
22066               : defaultCache;
22067       }
22068
22069       if (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);
22075           } else {
22076             // serving from cache
22077             if (isArray(cachedResp)) {
22078               resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
22079             } else {
22080               resolvePromise(cachedResp, 200, {}, 'OK');
22081             }
22082           }
22083         } else {
22084           // put the promise for the non-transformed response into cache as a placeholder
22085           cache.put(url, promise);
22086         }
22087       }
22088
22089
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]
22095             : undefined;
22096         if (xsrfValue) {
22097           reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
22098         }
22099
22100         $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
22101             config.withCredentials, config.responseType,
22102             createApplyHandlers(config.eventHandlers),
22103             createApplyHandlers(config.uploadEventHandlers));
22104       }
22105
22106       return promise;
22107
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();
22117               } else {
22118                 $rootScope.$apply(callEventHandler);
22119               }
22120
22121               function callEventHandler() {
22122                 eventHandler(event);
22123               }
22124             };
22125           });
22126           return applyHandlers;
22127         }
22128       }
22129
22130
22131       /**
22132        * Callback registered to $httpBackend():
22133        *  - caches the response if desired
22134        *  - resolves the raw $http promise
22135        *  - calls $apply
22136        */
22137       function done(status, response, headersString, statusText) {
22138         if (cache) {
22139           if (isSuccess(status)) {
22140             cache.put(url, [status, response, parseHeaders(headersString), statusText]);
22141           } else {
22142             // remove promise from the cache
22143             cache.remove(url);
22144           }
22145         }
22146
22147         function resolveHttpPromise() {
22148           resolvePromise(response, status, headersString, statusText);
22149         }
22150
22151         if (useApplyAsync) {
22152           $rootScope.$applyAsync(resolveHttpPromise);
22153         } else {
22154           resolveHttpPromise();
22155           if (!$rootScope.$$phase) $rootScope.$apply();
22156         }
22157       }
22158
22159
22160       /**
22161        * Resolves the raw $http promise.
22162        */
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;
22166
22167         (isSuccess(status) ? deferred.resolve : deferred.reject)({
22168           data: response,
22169           status: status,
22170           headers: headersGetter(headers),
22171           config: config,
22172           statusText: statusText
22173         });
22174       }
22175
22176       function resolvePromiseWithResult(result) {
22177         resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
22178       }
22179
22180       function removePendingReq() {
22181         var idx = $http.pendingRequests.indexOf(config);
22182         if (idx !== -1) $http.pendingRequests.splice(idx, 1);
22183       }
22184     }
22185
22186
22187     function buildUrl(url, serializedParams) {
22188       if (serializedParams.length > 0) {
22189         url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
22190       }
22191       return url;
22192     }
22193   }];
22194 }
22195
22196 /**
22197  * @ngdoc service
22198  * @name $xhrFactory
22199  * @this
22200  *
22201  * @description
22202  * Factory function used to create XMLHttpRequest objects.
22203  *
22204  * Replace or decorate this service to create your own custom XMLHttpRequest objects.
22205  *
22206  * ```
22207  * angular.module('myApp', [])
22208  * .factory('$xhrFactory', function() {
22209  *   return function createXhr(method, url) {
22210  *     return new window.XMLHttpRequest({mozSystem: true});
22211  *   };
22212  * });
22213  * ```
22214  *
22215  * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
22216  * @param {string} url URL of the request.
22217  */
22218 function $xhrFactoryProvider() {
22219   this.$get = function() {
22220     return function createXhr() {
22221       return new window.XMLHttpRequest();
22222     };
22223   };
22224 }
22225
22226 /**
22227  * @ngdoc service
22228  * @name $httpBackend
22229  * @requires $jsonpCallbacks
22230  * @requires $document
22231  * @requires $xhrFactory
22232  * @this
22233  *
22234  * @description
22235  * HTTP backend used by the {@link ng.$http service} that delegates to
22236  * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
22237  *
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}.
22240  *
22241  * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
22242  * $httpBackend} which can be trained with responses.
22243  */
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]);
22247   }];
22248 }
22249
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();
22255
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);
22263       });
22264     } else {
22265
22266       var xhr = createXhr(method, url);
22267
22268       xhr.open(method, url, true);
22269       forEach(headers, function(value, key) {
22270         if (isDefined(value)) {
22271             xhr.setRequestHeader(key, value);
22272         }
22273       });
22274
22275       xhr.onload = function requestLoaded() {
22276         var statusText = xhr.statusText || '';
22277
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;
22281
22282         // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
22283         var status = xhr.status === 1223 ? 204 : xhr.status;
22284
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;
22290         }
22291
22292         completeRequest(callback,
22293             status,
22294             response,
22295             xhr.getAllResponseHeaders(),
22296             statusText);
22297       };
22298
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, '');
22303       };
22304
22305       xhr.onerror = requestError;
22306       xhr.onabort = requestError;
22307       xhr.ontimeout = requestError;
22308
22309       forEach(eventHandlers, function(value, key) {
22310           xhr.addEventListener(key, value);
22311       });
22312
22313       forEach(uploadEventHandlers, function(value, key) {
22314         xhr.upload.addEventListener(key, value);
22315       });
22316
22317       if (withCredentials) {
22318         xhr.withCredentials = true;
22319       }
22320
22321       if (responseType) {
22322         try {
22323           xhr.responseType = responseType;
22324         } catch (e) {
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
22329           //
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') {
22333             throw e;
22334           }
22335         }
22336       }
22337
22338       xhr.send(isUndefined(post) ? null : post);
22339     }
22340
22341     if (timeout > 0) {
22342       var timeoutId = $browserDefer(timeoutRequest, timeout);
22343     } else if (isPromiseLike(timeout)) {
22344       timeout.then(timeoutRequest);
22345     }
22346
22347
22348     function timeoutRequest() {
22349       if (jsonpDone) {
22350         jsonpDone();
22351       }
22352       if (xhr) {
22353         xhr.abort();
22354       }
22355     }
22356
22357     function completeRequest(callback, status, response, headersString, statusText) {
22358       // cancel timeout and subsequent timeout promise resolution
22359       if (isDefined(timeoutId)) {
22360         $browserDefer.cancel(timeoutId);
22361       }
22362       jsonpDone = xhr = null;
22363
22364       callback(status, response, headersString, statusText);
22365       $browser.$$completeOutstandingRequest(noop);
22366     }
22367   };
22368
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';
22376     script.src = url;
22377     script.async = true;
22378
22379     callback = function(event) {
22380       removeEventListenerFn(script, 'load', callback);
22381       removeEventListenerFn(script, 'error', callback);
22382       rawDocument.body.removeChild(script);
22383       script = null;
22384       var status = -1;
22385       var text = 'unknown';
22386
22387       if (event) {
22388         if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {
22389           event = { type: 'error' };
22390         }
22391         text = event.type;
22392         status = event.type === 'error' ? 404 : 200;
22393       }
22394
22395       if (done) {
22396         done(status, text);
22397       }
22398     };
22399
22400     addEventListenerFn(script, 'load', callback);
22401     addEventListenerFn(script, 'error', callback);
22402     rawDocument.body.appendChild(script);
22403     return callback;
22404   }
22405 }
22406
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);
22413 };
22414
22415 $interpolateMinErr.interr = function(text, err) {
22416   return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString());
22417 };
22418
22419 /**
22420  * @ngdoc provider
22421  * @name $interpolateProvider
22422  * @this
22423  *
22424  * @description
22425  *
22426  * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
22427  *
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)
22433  * security bugs!
22434  * </div>
22435  *
22436  * @example
22437 <example name="custom-interpolation-markup" module="customInterpolationApp">
22438 <file name="index.html">
22439 <script>
22440   var customInterpolationApp = angular.module('customInterpolationApp', []);
22441
22442   customInterpolationApp.config(function($interpolateProvider) {
22443     $interpolateProvider.startSymbol('//');
22444     $interpolateProvider.endSymbol('//');
22445   });
22446
22447
22448   customInterpolationApp.controller('DemoController', function() {
22449       this.label = "This binding is brought you by // interpolation symbols.";
22450   });
22451 </script>
22452 <div ng-controller="DemoController as demo">
22453     //demo.label//
22454 </div>
22455 </file>
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.');
22459   });
22460 </file>
22461 </example>
22462  */
22463 function $InterpolateProvider() {
22464   var startSymbol = '{{';
22465   var endSymbol = '}}';
22466
22467   /**
22468    * @ngdoc method
22469    * @name $interpolateProvider#startSymbol
22470    * @description
22471    * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
22472    *
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.
22475    */
22476   this.startSymbol = function(value) {
22477     if (value) {
22478       startSymbol = value;
22479       return this;
22480     } else {
22481       return startSymbol;
22482     }
22483   };
22484
22485   /**
22486    * @ngdoc method
22487    * @name $interpolateProvider#endSymbol
22488    * @description
22489    * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
22490    *
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.
22493    */
22494   this.endSymbol = function(value) {
22495     if (value) {
22496       endSymbol = value;
22497       return this;
22498     } else {
22499       return endSymbol;
22500     }
22501   };
22502
22503
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');
22509
22510     function escape(ch) {
22511       return '\\\\\\' + ch;
22512     }
22513
22514     function unescapeText(text) {
22515       return text.replace(escapedStartRegexp, startSymbol).
22516         replace(escapedEndRegexp, endSymbol);
22517     }
22518
22519     function stringify(value) {
22520       if (value == null) { // null || undefined
22521         return '';
22522       }
22523       switch (typeof value) {
22524         case 'string':
22525           break;
22526         case 'number':
22527           value = '' + value;
22528           break;
22529         default:
22530           value = toJson(value);
22531       }
22532
22533       return value;
22534     }
22535
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) {
22539         unwatch();
22540         return constantInterp(scope);
22541       }, listener, objectEquality);
22542       return unwatch;
22543     }
22544
22545     /**
22546      * @ngdoc service
22547      * @name $interpolate
22548      * @kind function
22549      *
22550      * @requires $parse
22551      * @requires $sce
22552      *
22553      * @description
22554      *
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.
22559      *
22560      *
22561      * ```js
22562      *   var $interpolate = ...; // injected
22563      *   var exp = $interpolate('Hello {{name | uppercase}}!');
22564      *   expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
22565      * ```
22566      *
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`.
22570      *
22571      * ```js
22572      *   var $interpolate = ...; // injected
22573      *   var context = {greeting: 'Hello', name: undefined };
22574      *
22575      *   // default "forgiving" mode
22576      *   var exp = $interpolate('{{greeting}} {{name}}!');
22577      *   expect(exp(context)).toEqual('Hello !');
22578      *
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!');
22584      * ```
22585      *
22586      * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
22587      *
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
22592      * or binding.
22593      *
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.
22597      *
22598      * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
22599      * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
22600      * interpolation start/end markers with their escaped counterparts.**
22601      *
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.
22608      *
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"; \}\}
22613      *        </p>
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)
22617      *        characters.</p>
22618      *      <p>Instead, the result of the attempted script injection is visible, and can be removed
22619      *        from the database by an administrator.</p>
22620      *    </div>
22621      *  </file>
22622      * </example>
22623      *
22624      * @knownIssue
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.
22628      *
22629      * @knownIssue
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:
22636      *
22637      * ```
22638      * <div data-context='{"context":{"id":3,"type":"page"}}">
22639      * ```
22640      *
22641      * The workaround is to ensure that such instances are separated by whitespace:
22642      * ```
22643      * <div data-context='{"context":{"id":3,"type":"page"} }">
22644      * ```
22645      *
22646      * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
22647      *
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:
22660      *
22661      * - `context`: evaluation context for all expressions embedded in the interpolated text
22662      */
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;
22673         }
22674         return constantInterp;
22675       }
22676
22677       allOrNothing = !!allOrNothing;
22678       var startIndex,
22679           endIndex,
22680           index = 0,
22681           expressions = [],
22682           parseFns = [],
22683           textLength = text.length,
22684           exp,
22685           concat = [],
22686           expressionPositions = [];
22687
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)));
22693           }
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);
22699           concat.push('');
22700         } else {
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)));
22704           }
22705           break;
22706         }
22707       }
22708
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);
22717       }
22718
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];
22724           }
22725           return concat.join('');
22726         };
22727
22728         var getValue = function(value) {
22729           return trustedContext ?
22730             $sce.getTrusted(trustedContext, value) :
22731             $sce.valueOf(value);
22732         };
22733
22734         return extend(function interpolationFn(context) {
22735             var i = 0;
22736             var ii = expressions.length;
22737             var values = new Array(ii);
22738
22739             try {
22740               for (; i < ii; i++) {
22741                 values[i] = parseFns[i](context);
22742               }
22743
22744               return compute(values);
22745             } catch (err) {
22746               $exceptionHandler($interpolateMinErr.interr(text, err));
22747             }
22748
22749           }, {
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) {
22754             var lastValue;
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);
22759               }
22760               lastValue = currValue;
22761             });
22762           }
22763         });
22764       }
22765
22766       function parseStringifyInterceptor(value) {
22767         try {
22768           value = getValue(value);
22769           return allOrNothing && !isDefined(value) ? value : stringify(value);
22770         } catch (err) {
22771           $exceptionHandler($interpolateMinErr.interr(text, err));
22772         }
22773       }
22774     }
22775
22776
22777     /**
22778      * @ngdoc method
22779      * @name $interpolate#startSymbol
22780      * @description
22781      * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
22782      *
22783      * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
22784      * the symbol.
22785      *
22786      * @returns {string} start symbol.
22787      */
22788     $interpolate.startSymbol = function() {
22789       return startSymbol;
22790     };
22791
22792
22793     /**
22794      * @ngdoc method
22795      * @name $interpolate#endSymbol
22796      * @description
22797      * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
22798      *
22799      * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
22800      * the symbol.
22801      *
22802      * @returns {string} end symbol.
22803      */
22804     $interpolate.endSymbol = function() {
22805       return endSymbol;
22806     };
22807
22808     return $interpolate;
22809   }];
22810 }
22811
22812 /** @this */
22813 function $IntervalProvider() {
22814   this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
22815        function($rootScope,   $window,   $q,   $$q,   $browser) {
22816     var intervals = {};
22817
22818
22819      /**
22820       * @ngdoc service
22821       * @name $interval
22822       *
22823       * @description
22824       * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
22825       * milliseconds.
22826       *
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)`.
22832       *
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
22835       * time.
22836       *
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.
22843       * </div>
22844       *
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
22849       *   indefinitely.
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.
22854       *
22855       * @example
22856       * <example module="intervalExample" name="interval-service">
22857       * <file name="index.html">
22858       *   <script>
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;
22865       *
22866       *           var stop;
22867       *           $scope.fight = function() {
22868       *             // Don't start a new fight if we are already fighting
22869       *             if ( angular.isDefined(stop) ) return;
22870       *
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;
22875       *               } else {
22876       *                 $scope.stopFight();
22877       *               }
22878       *             }, 100);
22879       *           };
22880       *
22881       *           $scope.stopFight = function() {
22882       *             if (angular.isDefined(stop)) {
22883       *               $interval.cancel(stop);
22884       *               stop = undefined;
22885       *             }
22886       *           };
22887       *
22888       *           $scope.resetFight = function() {
22889       *             $scope.blood_1 = 100;
22890       *             $scope.blood_2 = 120;
22891       *           };
22892       *
22893       *           $scope.$on('$destroy', function() {
22894       *             // Make sure that the interval is destroyed too
22895       *             $scope.stopFight();
22896       *           });
22897       *         }])
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
22906       *
22907       *             // used to update the UI
22908       *             function updateTime() {
22909       *               element.text(dateFilter(new Date(), format));
22910       *             }
22911       *
22912       *             // watch the expression, and update the UI on change.
22913       *             scope.$watch(attrs.myCurrentTime, function(value) {
22914       *               format = value;
22915       *               updateTime();
22916       *             });
22917       *
22918       *             stopTime = $interval(updateTime, 1000);
22919       *
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);
22924       *             });
22925       *           }
22926       *         }]);
22927       *   </script>
22928       *
22929       *   <div>
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>
22933       *       <hr/>
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>
22939       *     </div>
22940       *   </div>
22941       *
22942       * </file>
22943       * </example>
22944       */
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,
22950           iteration = 0,
22951           skipApply = (isDefined(invokeApply) && !invokeApply),
22952           deferred = (skipApply ? $$q : $q).defer(),
22953           promise = deferred.promise;
22954
22955       count = isDefined(count) ? count : 0;
22956
22957       promise.$$intervalId = setInterval(function tick() {
22958         if (skipApply) {
22959           $browser.defer(callback);
22960         } else {
22961           $rootScope.$evalAsync(callback);
22962         }
22963         deferred.notify(iteration++);
22964
22965         if (count > 0 && iteration >= count) {
22966           deferred.resolve(iteration);
22967           clearInterval(promise.$$intervalId);
22968           delete intervals[promise.$$intervalId];
22969         }
22970
22971         if (!skipApply) $rootScope.$apply();
22972
22973       }, delay);
22974
22975       intervals[promise.$$intervalId] = deferred;
22976
22977       return promise;
22978
22979       function callback() {
22980         if (!hasParams) {
22981           fn(iteration);
22982         } else {
22983           fn.apply(null, args);
22984         }
22985       }
22986     }
22987
22988
22989      /**
22990       * @ngdoc method
22991       * @name $interval#cancel
22992       *
22993       * @description
22994       * Cancels a task associated with the `promise`.
22995       *
22996       * @param {Promise=} promise returned by the `$interval` function.
22997       * @returns {boolean} Returns `true` if the task was successfully canceled.
22998       */
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];
23004         return true;
23005       }
23006       return false;
23007     };
23008
23009     return interval;
23010   }];
23011 }
23012
23013 /**
23014  * @ngdoc service
23015  * @name $jsonpCallbacks
23016  * @requires $window
23017  * @description
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.
23021  */
23022 var $jsonpCallbacksProvider = /** @this */ function() {
23023   this.$get = ['$window', function($window) {
23024     var callbacks = $window.angular.callbacks;
23025     var callbackMap = {};
23026
23027     function createCallback(callbackId) {
23028       var callback = function(data) {
23029         callback.data = data;
23030         callback.called = true;
23031       };
23032       callback.id = callbackId;
23033       return callback;
23034     }
23035
23036     return {
23037       /**
23038        * @ngdoc method
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
23042        * @description
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.
23045        */
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;
23052       },
23053       /**
23054        * @ngdoc method
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
23058        * @description
23059        * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the
23060        * callback that was passed in the request.
23061        */
23062       wasCalled: function(callbackPath) {
23063         return callbackMap[callbackPath].called;
23064       },
23065       /**
23066        * @ngdoc method
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
23070        * @description
23071        * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback
23072        * in the JSONP response.
23073        */
23074       getResponse: function(callbackPath) {
23075         return callbackMap[callbackPath].data;
23076       },
23077       /**
23078        * @ngdoc method
23079        * @name $jsonpCallbacks#removeCallback
23080        * @param {string} callbackPath the path to the callback that was sent in the JSONP request
23081        * @description
23082        * {@link $httpBackend} calls this method to remove the callback after the JSONP request has
23083        * completed or timed-out.
23084        */
23085       removeCallback: function(callbackPath) {
23086         var callback = callbackMap[callbackPath];
23087         delete callbacks[callback.id];
23088         delete callbackMap[callbackPath];
23089       }
23090     };
23091   }];
23092 };
23093
23094 /**
23095  * @ngdoc service
23096  * @name $locale
23097  *
23098  * @description
23099  * $locale service provides localization rules for various Angular components. As of right now the
23100  * only public api is:
23101  *
23102  * * `id` â€“ `{string}` â€“ locale id formatted as `languageId-countryId` (e.g. `en-us`)
23103  */
23104
23105 var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/,
23106     DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
23107 var $locationMinErr = minErr('$location');
23108
23109
23110 /**
23111  * Encode path using encodeUriSegment, ignoring forward slashes
23112  *
23113  * @param {string} path Path to encode
23114  * @returns {string}
23115  */
23116 function encodePath(path) {
23117   var segments = path.split('/'),
23118       i = segments.length;
23119
23120   while (i--) {
23121     segments[i] = encodeUriSegment(segments[i]);
23122   }
23123
23124   return segments.join('/');
23125 }
23126
23127 function parseAbsoluteUrl(absoluteUrl, locationObj) {
23128   var parsedUrl = urlResolve(absoluteUrl);
23129
23130   locationObj.$$protocol = parsedUrl.protocol;
23131   locationObj.$$host = parsedUrl.hostname;
23132   locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
23133 }
23134
23135 var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
23136 function parseAppUrl(url, locationObj) {
23137
23138   if (DOUBLE_SLASH_REGEX.test(url)) {
23139     throw $locationMinErr('badpath', 'Invalid url "{0}".', url);
23140   }
23141
23142   var prefixed = (url.charAt(0) !== '/');
23143   if (prefixed) {
23144     url = '/' + url;
23145   }
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);
23151
23152   // make sure path starts with '/';
23153   if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {
23154     locationObj.$$path = '/' + locationObj.$$path;
23155   }
23156 }
23157
23158 function startsWith(str, search) {
23159   return str.slice(0, search.length) === search;
23160 }
23161
23162 /**
23163  *
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.
23168  */
23169 function stripBaseUrl(base, url) {
23170   if (startsWith(url, base)) {
23171     return url.substr(base.length);
23172   }
23173 }
23174
23175
23176 function stripHash(url) {
23177   var index = url.indexOf('#');
23178   return index === -1 ? url : url.substr(0, index);
23179 }
23180
23181 function trimEmptyHash(url) {
23182   return url.replace(/(#.+)|#$/, '$1');
23183 }
23184
23185
23186 function stripFile(url) {
23187   return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
23188 }
23189
23190 /* return the server only (scheme://host:port) */
23191 function serverBase(url) {
23192   return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
23193 }
23194
23195
23196 /**
23197  * LocationHtml5Url represents a URL
23198  * This object is exposed as $location service when HTML5 mode is enabled and supported
23199  *
23200  * @constructor
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
23204  */
23205 function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
23206   this.$$html5 = true;
23207   basePrefix = basePrefix || '';
23208   parseAbsoluteUrl(appBase, this);
23209
23210
23211   /**
23212    * Parse given HTML5 (regular) URL string into properties
23213    * @param {string} url HTML5 URL
23214    * @private
23215    */
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,
23220           appBaseNoFile);
23221     }
23222
23223     parseAppUrl(pathUrl, this);
23224
23225     if (!this.$$path) {
23226       this.$$path = '/';
23227     }
23228
23229     this.$$compose();
23230   };
23231
23232   /**
23233    * Compose url and update `absUrl` property
23234    * @private
23235    */
23236   this.$$compose = function() {
23237     var search = toKeyValue(this.$$search),
23238         hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
23239
23240     this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
23241     this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
23242   };
23243
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));
23249       return true;
23250     }
23251     var appUrl, prevAppUrl;
23252     var rewrittenUrl;
23253
23254
23255     if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
23256       prevAppUrl = appUrl;
23257       if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
23258         rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
23259       } else {
23260         rewrittenUrl = appBase + prevAppUrl;
23261       }
23262     } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
23263       rewrittenUrl = appBaseNoFile + appUrl;
23264     } else if (appBaseNoFile === url + '/') {
23265       rewrittenUrl = appBaseNoFile;
23266     }
23267     if (rewrittenUrl) {
23268       this.$$parse(rewrittenUrl);
23269     }
23270     return !!rewrittenUrl;
23271   };
23272 }
23273
23274
23275 /**
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.
23279  *
23280  * @constructor
23281  * @param {string} appBase application base URL
23282  * @param {string} appBaseNoFile application base URL stripped of any filename
23283  * @param {string} hashPrefix hashbang prefix
23284  */
23285 function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
23286
23287   parseAbsoluteUrl(appBase, this);
23288
23289
23290   /**
23291    * Parse given hashbang URL into properties
23292    * @param {string} url Hashbang URL
23293    * @private
23294    */
23295   this.$$parse = function(url) {
23296     var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
23297     var withoutHashUrl;
23298
23299     if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
23300
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;
23307       }
23308
23309     } else {
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;
23315       } else {
23316         withoutHashUrl = '';
23317         if (isUndefined(withoutBaseUrl)) {
23318           appBase = url;
23319           this.replace();
23320         }
23321       }
23322     }
23323
23324     parseAppUrl(withoutHashUrl, this);
23325
23326     this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
23327
23328     this.$$compose();
23329
23330     /*
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
23337      *
23338      * Inside of Angular, we're always using pathnames that
23339      * do not include drive names for routing.
23340      */
23341     function removeWindowsDriveName(path, url, base) {
23342       /*
23343       Matches paths for file protocol on windows,
23344       such as /C:/foo/bar, and captures only /foo/bar.
23345       */
23346       var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
23347
23348       var firstPathSegmentMatch;
23349
23350       //Get the relative path from the input URL.
23351       if (startsWith(url, base)) {
23352         url = url.replace(base, '');
23353       }
23354
23355       // The input URL intentionally contains a first path segment that ends with a colon.
23356       if (windowsFilePathExp.exec(url)) {
23357         return path;
23358       }
23359
23360       firstPathSegmentMatch = windowsFilePathExp.exec(path);
23361       return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
23362     }
23363   };
23364
23365   /**
23366    * Compose hashbang URL and update `absUrl` property
23367    * @private
23368    */
23369   this.$$compose = function() {
23370     var search = toKeyValue(this.$$search),
23371         hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
23372
23373     this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
23374     this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
23375   };
23376
23377   this.$$parseLinkUrl = function(url, relHref) {
23378     if (stripHash(appBase) === stripHash(url)) {
23379       this.$$parse(url);
23380       return true;
23381     }
23382     return false;
23383   };
23384 }
23385
23386
23387 /**
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.
23391  *
23392  * @constructor
23393  * @param {string} appBase application base URL
23394  * @param {string} appBaseNoFile application base URL stripped of any filename
23395  * @param {string} hashPrefix hashbang prefix
23396  */
23397 function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
23398   this.$$html5 = true;
23399   LocationHashbangUrl.apply(this, arguments);
23400
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));
23406       return true;
23407     }
23408
23409     var rewrittenUrl;
23410     var appUrl;
23411
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;
23418     }
23419     if (rewrittenUrl) {
23420       this.$$parse(rewrittenUrl);
23421     }
23422     return !!rewrittenUrl;
23423   };
23424
23425   this.$$compose = function() {
23426     var search = toKeyValue(this.$$search),
23427         hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
23428
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;
23432   };
23433
23434 }
23435
23436
23437 var locationPrototype = {
23438
23439   /**
23440    * Ensure absolute URL is initialized.
23441    * @private
23442    */
23443   $$absUrl:'',
23444
23445   /**
23446    * Are we in html5 mode?
23447    * @private
23448    */
23449   $$html5: false,
23450
23451   /**
23452    * Has any change been replacing?
23453    * @private
23454    */
23455   $$replace: false,
23456
23457   /**
23458    * @ngdoc method
23459    * @name $location#absUrl
23460    *
23461    * @description
23462    * This method is getter only.
23463    *
23464    * Return full URL representation with all segments encoded according to rules specified in
23465    * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
23466    *
23467    *
23468    * ```js
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"
23472    * ```
23473    *
23474    * @return {string} full URL
23475    */
23476   absUrl: locationGetter('$$absUrl'),
23477
23478   /**
23479    * @ngdoc method
23480    * @name $location#url
23481    *
23482    * @description
23483    * This method is getter / setter.
23484    *
23485    * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.
23486    *
23487    * Change path, search and hash, when called with parameter and return `$location`.
23488    *
23489    *
23490    * ```js
23491    * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
23492    * var url = $location.url();
23493    * // => "/some/path?foo=bar&baz=xoxo"
23494    * ```
23495    *
23496    * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)
23497    * @return {string} url
23498    */
23499   url: function(url) {
23500     if (isUndefined(url)) {
23501       return this.$$url;
23502     }
23503
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] || '');
23508
23509     return this;
23510   },
23511
23512   /**
23513    * @ngdoc method
23514    * @name $location#protocol
23515    *
23516    * @description
23517    * This method is getter only.
23518    *
23519    * Return protocol of current URL.
23520    *
23521    *
23522    * ```js
23523    * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
23524    * var protocol = $location.protocol();
23525    * // => "http"
23526    * ```
23527    *
23528    * @return {string} protocol of current URL
23529    */
23530   protocol: locationGetter('$$protocol'),
23531
23532   /**
23533    * @ngdoc method
23534    * @name $location#host
23535    *
23536    * @description
23537    * This method is getter only.
23538    *
23539    * Return host of current URL.
23540    *
23541    * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
23542    *
23543    *
23544    * ```js
23545    * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
23546    * var host = $location.host();
23547    * // => "example.com"
23548    *
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"
23554    * ```
23555    *
23556    * @return {string} host of current URL.
23557    */
23558   host: locationGetter('$$host'),
23559
23560   /**
23561    * @ngdoc method
23562    * @name $location#port
23563    *
23564    * @description
23565    * This method is getter only.
23566    *
23567    * Return port of current URL.
23568    *
23569    *
23570    * ```js
23571    * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
23572    * var port = $location.port();
23573    * // => 80
23574    * ```
23575    *
23576    * @return {Number} port
23577    */
23578   port: locationGetter('$$port'),
23579
23580   /**
23581    * @ngdoc method
23582    * @name $location#path
23583    *
23584    * @description
23585    * This method is getter / setter.
23586    *
23587    * Return path of current URL when called without any parameter.
23588    *
23589    * Change path when called with parameter and return `$location`.
23590    *
23591    * Note: Path should always begin with forward slash (/), this method will add the forward slash
23592    * if it is missing.
23593    *
23594    *
23595    * ```js
23596    * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
23597    * var path = $location.path();
23598    * // => "/some/path"
23599    * ```
23600    *
23601    * @param {(string|number)=} path New path
23602    * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
23603    */
23604   path: locationGetterSetter('$$path', function(path) {
23605     path = path !== null ? path.toString() : '';
23606     return path.charAt(0) === '/' ? path : '/' + path;
23607   }),
23608
23609   /**
23610    * @ngdoc method
23611    * @name $location#search
23612    *
23613    * @description
23614    * This method is getter / setter.
23615    *
23616    * Return search part (as object) of current URL when called without any parameter.
23617    *
23618    * Change search part when called with parameter and return `$location`.
23619    *
23620    *
23621    * ```js
23622    * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
23623    * var searchObject = $location.search();
23624    * // => {foo: 'bar', baz: 'xoxo'}
23625    *
23626    * // set foo to 'yipee'
23627    * $location.search('foo', 'yipee');
23628    * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
23629    * ```
23630    *
23631    * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
23632    * hash object.
23633    *
23634    * When called with a single argument the method acts as a setter, setting the `search` component
23635    * of `$location` to the specified value.
23636    *
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.
23639    *
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.
23642    *
23643    * If `paramValue` is an array, it will override the property of the `search` component of
23644    * `$location` specified via the first argument.
23645    *
23646    * If `paramValue` is `null`, the property specified via the first argument will be deleted.
23647    *
23648    * If `paramValue` is `true`, the property specified via the first argument will be added with no
23649    * value nor trailing equal sign.
23650    *
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.
23653    */
23654   search: function(search, paramValue) {
23655     switch (arguments.length) {
23656       case 0:
23657         return this.$$search;
23658       case 1:
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];
23667           });
23668
23669           this.$$search = search;
23670         } else {
23671           throw $locationMinErr('isrcharg',
23672               'The first argument of the `$location#search()` call must be a string or an object.');
23673         }
23674         break;
23675       default:
23676         if (isUndefined(paramValue) || paramValue === null) {
23677           delete this.$$search[search];
23678         } else {
23679           this.$$search[search] = paramValue;
23680         }
23681     }
23682
23683     this.$$compose();
23684     return this;
23685   },
23686
23687   /**
23688    * @ngdoc method
23689    * @name $location#hash
23690    *
23691    * @description
23692    * This method is getter / setter.
23693    *
23694    * Returns the hash fragment when called without any parameters.
23695    *
23696    * Changes the hash fragment when called with a parameter and returns `$location`.
23697    *
23698    *
23699    * ```js
23700    * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
23701    * var hash = $location.hash();
23702    * // => "hashValue"
23703    * ```
23704    *
23705    * @param {(string|number)=} hash New hash fragment
23706    * @return {string} hash
23707    */
23708   hash: locationGetterSetter('$$hash', function(hash) {
23709     return hash !== null ? hash.toString() : '';
23710   }),
23711
23712   /**
23713    * @ngdoc method
23714    * @name $location#replace
23715    *
23716    * @description
23717    * If called, all changes to $location during the current `$digest` will replace the current history
23718    * record, instead of adding a new one.
23719    */
23720   replace: function() {
23721     this.$$replace = true;
23722     return this;
23723   }
23724 };
23725
23726 forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
23727   Location.prototype = Object.create(locationPrototype);
23728
23729   /**
23730    * @ngdoc method
23731    * @name $location#state
23732    *
23733    * @description
23734    * This method is getter / setter.
23735    *
23736    * Return the history state object when called without any parameter.
23737    *
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`.
23740    *
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.
23744    *
23745    * @param {object=} state State object for pushState or replaceState
23746    * @return {object} state
23747    */
23748   Location.prototype.state = function(state) {
23749     if (!arguments.length) {
23750       return this.$$state;
23751     }
23752
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');
23756     }
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;
23761
23762     return this;
23763   };
23764 });
23765
23766
23767 function locationGetter(property) {
23768   return /** @this */ function() {
23769     return this[property];
23770   };
23771 }
23772
23773
23774 function locationGetterSetter(property, preprocess) {
23775   return /** @this */ function(value) {
23776     if (isUndefined(value)) {
23777       return this[property];
23778     }
23779
23780     this[property] = preprocess(value);
23781     this.$$compose();
23782
23783     return this;
23784   };
23785 }
23786
23787
23788 /**
23789  * @ngdoc service
23790  * @name $location
23791  *
23792  * @requires $rootElement
23793  *
23794  * @description
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.
23799  *
23800  * **The $location service:**
23801  *
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).
23810  *
23811  * For more information see {@link guide/$location Developer Guide: Using $location}
23812  */
23813
23814 /**
23815  * @ngdoc provider
23816  * @name $locationProvider
23817  * @this
23818  *
23819  * @description
23820  * Use the `$locationProvider` to configure how the application deep linking paths are stored.
23821  */
23822 function $LocationProvider() {
23823   var hashPrefix = '',
23824       html5Mode = {
23825         enabled: false,
23826         requireBase: true,
23827         rewriteLinks: true
23828       };
23829
23830   /**
23831    * @ngdoc method
23832    * @name $locationProvider#hashPrefix
23833    * @description
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
23837    */
23838   this.hashPrefix = function(prefix) {
23839     if (isDefined(prefix)) {
23840       hashPrefix = prefix;
23841       return this;
23842     } else {
23843       return hashPrefix;
23844     }
23845   };
23846
23847   /**
23848    * @ngdoc method
23849    * @name $locationProvider#html5Mode
23850    * @description
23851    * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
23852    *   If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
23853    *   properties:
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'`.
23867    *
23868    * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
23869    */
23870   this.html5Mode = function(mode) {
23871     if (isBoolean(mode)) {
23872       html5Mode.enabled = mode;
23873       return this;
23874     } else if (isObject(mode)) {
23875
23876       if (isBoolean(mode.enabled)) {
23877         html5Mode.enabled = mode.enabled;
23878       }
23879
23880       if (isBoolean(mode.requireBase)) {
23881         html5Mode.requireBase = mode.requireBase;
23882       }
23883
23884       if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {
23885         html5Mode.rewriteLinks = mode.rewriteLinks;
23886       }
23887
23888       return this;
23889     } else {
23890       return html5Mode;
23891     }
23892   };
23893
23894   /**
23895    * @ngdoc event
23896    * @name $location#$locationChangeStart
23897    * @eventType broadcast on root scope
23898    * @description
23899    * Broadcasted before a URL will change.
23900    *
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.
23905    *
23906    * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
23907    * the browser supports the HTML5 History API.
23908    *
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.
23914    */
23915
23916   /**
23917    * @ngdoc event
23918    * @name $location#$locationChangeSuccess
23919    * @eventType broadcast on root scope
23920    * @description
23921    * Broadcasted after a URL was changed.
23922    *
23923    * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
23924    * the browser supports the HTML5 History API.
23925    *
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.
23931    */
23932
23933   this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
23934       function($rootScope, $browser, $sniffer, $rootElement, $window) {
23935     var $location,
23936         LocationMode,
23937         baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
23938         initialUrl = $browser.url(),
23939         appBase;
23940
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!');
23945       }
23946       appBase = serverBase(initialUrl) + (baseHref || '/');
23947       LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
23948     } else {
23949       appBase = stripHash(initialUrl);
23950       LocationMode = LocationHashbangUrl;
23951     }
23952     var appBaseNoFile = stripFile(appBase);
23953
23954     $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
23955     $location.$$parseLinkUrl(initialUrl, initialUrl);
23956
23957     $location.$$state = $browser.state();
23958
23959     var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
23960
23961     function setBrowserUrlWithFallback(url, replace, state) {
23962       var oldUrl = $location.url();
23963       var oldState = $location.$$state;
23964       try {
23965         $browser.url(url, replace, state);
23966
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();
23971       } catch (e) {
23972         // Restore old values if pushState fails
23973         $location.url(oldUrl);
23974         $location.$$state = oldState;
23975
23976         throw e;
23977       }
23978     }
23979
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
23984
23985       if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;
23986
23987       var elm = jqLite(event.target);
23988
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;
23993       }
23994
23995       if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;
23996
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');
24001
24002       if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
24003         // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
24004         // an animation.
24005         absHref = urlResolve(absHref.animVal).href;
24006       }
24007
24008       // Ignore when url is started with javascript: or mailto:
24009       if (IGNORE_URI_REGEXP.test(absHref)) return;
24010
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;
24022           }
24023         }
24024       }
24025     });
24026
24027
24028     // rewrite hashbang url <> html5 url
24029     if (trimEmptyHash($location.absUrl()) !== trimEmptyHash(initialUrl)) {
24030       $browser.url($location.absUrl(), true);
24031     }
24032
24033     var initializing = true;
24034
24035     // update $location when $browser url changes
24036     $browser.onUrlChange(function(newUrl, newState) {
24037
24038       if (isUndefined(stripBaseUrl(appBaseNoFile, newUrl))) {
24039         // If we are navigating outside of the app then force a reload
24040         $window.location.href = newUrl;
24041         return;
24042       }
24043
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;
24051
24052         defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
24053             newState, oldState).defaultPrevented;
24054
24055         // if the location was changed by a `$locationChangeStart` handler then stop
24056         // processing this location change
24057         if ($location.absUrl() !== newUrl) return;
24058
24059         if (defaultPrevented) {
24060           $location.$$parse(oldUrl);
24061           $location.$$state = oldState;
24062           setBrowserUrlWithFallback(oldUrl, false, oldState);
24063         } else {
24064           initializing = false;
24065           afterLocationChange(oldUrl, oldState);
24066         }
24067       });
24068       if (!$rootScope.$$phase) $rootScope.$digest();
24069     });
24070
24071     // update browser
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);
24079
24080       if (initializing || urlOrStateChanged) {
24081         initializing = false;
24082
24083         $rootScope.$evalAsync(function() {
24084           var newUrl = $location.absUrl();
24085           var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
24086               $location.$$state, oldState).defaultPrevented;
24087
24088           // if the location was changed by a `$locationChangeStart` handler then stop
24089           // processing this location change
24090           if ($location.absUrl() !== newUrl) return;
24091
24092           if (defaultPrevented) {
24093             $location.$$parse(oldUrl);
24094             $location.$$state = oldState;
24095           } else {
24096             if (urlOrStateChanged) {
24097               setBrowserUrlWithFallback(newUrl, currentReplace,
24098                                         oldState === $location.$$state ? null : $location.$$state);
24099             }
24100             afterLocationChange(oldUrl, oldState);
24101           }
24102         });
24103       }
24104
24105       $location.$$replace = false;
24106
24107       // we don't need to return anything because $evalAsync will make the digest loop dirty when
24108       // there is a change
24109     });
24110
24111     return $location;
24112
24113     function afterLocationChange(oldUrl, oldState) {
24114       $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
24115         $location.$$state, oldState);
24116     }
24117 }];
24118 }
24119
24120 /**
24121  * @ngdoc service
24122  * @name $log
24123  * @requires $window
24124  *
24125  * @description
24126  * Simple service for logging. Default implementation safely writes the message
24127  * into the browser's console (if present).
24128  *
24129  * The main purpose of this service is to simplify debugging and troubleshooting.
24130  *
24131  * The default is to log `debug` messages. You can use
24132  * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
24133  *
24134  * @example
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!';
24141          }]);
24142      </file>
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>
24146          <label>Message:
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>
24153        </div>
24154      </file>
24155    </example>
24156  */
24157
24158 /**
24159  * @ngdoc provider
24160  * @name $logProvider
24161  * @this
24162  *
24163  * @description
24164  * Use the `$logProvider` to configure how the application logs messages
24165  */
24166 function $LogProvider() {
24167   var debug = true,
24168       self = this;
24169
24170   /**
24171    * @ngdoc method
24172    * @name $logProvider#debugEnabled
24173    * @description
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
24176    */
24177   this.debugEnabled = function(flag) {
24178     if (isDefined(flag)) {
24179       debug = flag;
24180       return this;
24181     } else {
24182       return debug;
24183     }
24184   };
24185
24186   this.$get = ['$window', function($window) {
24187     return {
24188       /**
24189        * @ngdoc method
24190        * @name $log#log
24191        *
24192        * @description
24193        * Write a log message
24194        */
24195       log: consoleLog('log'),
24196
24197       /**
24198        * @ngdoc method
24199        * @name $log#info
24200        *
24201        * @description
24202        * Write an information message
24203        */
24204       info: consoleLog('info'),
24205
24206       /**
24207        * @ngdoc method
24208        * @name $log#warn
24209        *
24210        * @description
24211        * Write a warning message
24212        */
24213       warn: consoleLog('warn'),
24214
24215       /**
24216        * @ngdoc method
24217        * @name $log#error
24218        *
24219        * @description
24220        * Write an error message
24221        */
24222       error: consoleLog('error'),
24223
24224       /**
24225        * @ngdoc method
24226        * @name $log#debug
24227        *
24228        * @description
24229        * Write a debug message
24230        */
24231       debug: (function() {
24232         var fn = consoleLog('debug');
24233
24234         return function() {
24235           if (debug) {
24236             fn.apply(self, arguments);
24237           }
24238         };
24239       })()
24240     };
24241
24242     function formatError(arg) {
24243       if (arg instanceof Error) {
24244         if (arg.stack) {
24245           arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
24246               ? 'Error: ' + arg.message + '\n' + arg.stack
24247               : arg.stack;
24248         } else if (arg.sourceURL) {
24249           arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
24250         }
24251       }
24252       return arg;
24253     }
24254
24255     function consoleLog(type) {
24256       var console = $window.console || {},
24257           logFn = console[type] || console.log || noop,
24258           hasApply = false;
24259
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...
24262       try {
24263         hasApply = !!logFn.apply;
24264       } catch (e) { /* empty */ }
24265
24266       if (hasApply) {
24267         return function() {
24268           var args = [];
24269           forEach(arguments, function(arg) {
24270             args.push(formatError(arg));
24271           });
24272           return logFn.apply(console, args);
24273         };
24274       }
24275
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);
24280       };
24281     }
24282   }];
24283 }
24284
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.                          *
24290  *                                                                         *
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  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
24295
24296 var $parseMinErr = minErr('$parse');
24297
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;
24310
24311 var CALL = FUNCTION_CTOR_PROTO.call;
24312 var APPLY = FUNCTION_CTOR_PROTO.apply;
24313 var BIND = FUNCTION_CTOR_PROTO.bind;
24314
24315 var objectValueOf = OBJECT_CTOR_PROTO.valueOf;
24316
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.
24322 //
24323 // As an example, consider the following Angular expression:
24324 //
24325 //   {}.toString.constructor('alert("evil JS code")')
24326 //
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.
24332 //
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
24336 // native objects.
24337 //
24338 // See https://docs.angularjs.org/guide/security
24339
24340
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);
24348   }
24349   return name;
24350 }
24351
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
24357   //
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:
24361   //
24362   // TypeError: Cannot convert object to primitive value
24363   //
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.
24367   return name + '';
24368 }
24369
24370 function ensureSafeObject(obj, fullExpression) {
24371   // nifty check if obj is Function that is fast and works across iframes and other contexts
24372   if (obj) {
24373     if (obj.constructor === obj) {
24374       throw $parseMinErr('isecfn',
24375           'Referencing Function in Angular expressions is disallowed! Expression: {0}',
24376           fullExpression);
24377     } else if (// isWindow(obj)
24378         obj.window === obj) {
24379       throw $parseMinErr('isecwindow',
24380           'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
24381           fullExpression);
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}',
24386           fullExpression);
24387     } else if (// block Object so that we can't get hold of dangerous Object.* methods
24388         obj === Object) {
24389       throw $parseMinErr('isecobj',
24390           'Referencing Object in Angular expressions is disallowed! Expression: {0}',
24391           fullExpression);
24392     }
24393   }
24394   return obj;
24395 }
24396
24397 function ensureSafeFunction(obj, fullExpression) {
24398   if (obj) {
24399     if (obj.constructor === obj) {
24400       throw $parseMinErr('isecfn',
24401         'Referencing Function in Angular expressions is disallowed! Expression: {0}',
24402         fullExpression);
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}',
24406         fullExpression);
24407     }
24408   }
24409 }
24410
24411 function ensureSafeAssignContext(obj, fullExpression) {
24412   if (obj) {
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}',
24427         fullExpression);
24428     }
24429   }
24430 }
24431
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', '\'':'\'', '"':'"'};
24435
24436
24437 /////////////////////////////////////////
24438
24439
24440 /**
24441  * @constructor
24442  */
24443 var Lexer = function Lexer(options) {
24444   this.options = options;
24445 };
24446
24447 Lexer.prototype = {
24448   constructor: Lexer,
24449
24450   lex: function(text) {
24451     this.text = text;
24452     this.index = 0;
24453     this.tokens = [];
24454
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())) {
24460         this.readNumber();
24461       } else if (this.isIdentifierStart(this.peekMultichar())) {
24462         this.readIdent();
24463       } else if (this.is(ch, '(){}[].,;:?')) {
24464         this.tokens.push({index: this.index, text: ch});
24465         this.index++;
24466       } else if (this.isWhitespace(ch)) {
24467         this.index++;
24468       } else {
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;
24478         } else {
24479           this.throwError('Unexpected next character ', this.index, this.index + 1);
24480         }
24481       }
24482     }
24483     return this.tokens;
24484   },
24485
24486   is: function(ch, chars) {
24487     return chars.indexOf(ch) !== -1;
24488   },
24489
24490   peek: function(i) {
24491     var num = i || 1;
24492     return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
24493   },
24494
24495   isNumber: function(ch) {
24496     return ('0' <= ch && ch <= '9') && typeof ch === 'string';
24497   },
24498
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');
24503   },
24504
24505   isIdentifierStart: function(ch) {
24506     return this.options.isIdentifierStart ?
24507         this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
24508         this.isValidIdentifierStart(ch);
24509   },
24510
24511   isValidIdentifierStart: function(ch) {
24512     return ('a' <= ch && ch <= 'z' ||
24513             'A' <= ch && ch <= 'Z' ||
24514             '_' === ch || ch === '$');
24515   },
24516
24517   isIdentifierContinue: function(ch) {
24518     return this.options.isIdentifierContinue ?
24519         this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
24520         this.isValidIdentifierContinue(ch);
24521   },
24522
24523   isValidIdentifierContinue: function(ch, cp) {
24524     return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
24525   },
24526
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;
24531   },
24532
24533   peekMultichar: function() {
24534     var ch = this.text.charAt(this.index);
24535     var peek = this.peek();
24536     if (!peek) {
24537       return ch;
24538     }
24539     var cp1 = ch.charCodeAt(0);
24540     var cp2 = peek.charCodeAt(0);
24541     if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
24542       return ch + peek;
24543     }
24544     return ch;
24545   },
24546
24547   isExpOperator: function(ch) {
24548     return (ch === '-' || ch === '+' || this.isNumber(ch));
24549   },
24550
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) + ']'
24555             : ' ' + end);
24556     throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
24557         error, colStr, this.text);
24558   },
24559
24560   readNumber: function() {
24561     var number = '';
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)) {
24566         number += ch;
24567       } else {
24568         var peekCh = this.peek();
24569         if (ch === 'e' && this.isExpOperator(peekCh)) {
24570           number += ch;
24571         } else if (this.isExpOperator(ch) &&
24572             peekCh && this.isNumber(peekCh) &&
24573             number.charAt(number.length - 1) === 'e') {
24574           number += ch;
24575         } else if (this.isExpOperator(ch) &&
24576             (!peekCh || !this.isNumber(peekCh)) &&
24577             number.charAt(number.length - 1) === 'e') {
24578           this.throwError('Invalid exponent');
24579         } else {
24580           break;
24581         }
24582       }
24583       this.index++;
24584     }
24585     this.tokens.push({
24586       index: start,
24587       text: number,
24588       constant: true,
24589       value: Number(number)
24590     });
24591   },
24592
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)) {
24599         break;
24600       }
24601       this.index += ch.length;
24602     }
24603     this.tokens.push({
24604       index: start,
24605       text: this.text.slice(start, this.index),
24606       identifier: true
24607     });
24608   },
24609
24610   readString: function(quote) {
24611     var start = this.index;
24612     this.index++;
24613     var string = '';
24614     var rawString = quote;
24615     var escape = false;
24616     while (this.index < this.text.length) {
24617       var ch = this.text.charAt(this.index);
24618       rawString += ch;
24619       if (escape) {
24620         if (ch === 'u') {
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 + ']');
24624           }
24625           this.index += 4;
24626           string += String.fromCharCode(parseInt(hex, 16));
24627         } else {
24628           var rep = ESCAPE[ch];
24629           string = string + (rep || ch);
24630         }
24631         escape = false;
24632       } else if (ch === '\\') {
24633         escape = true;
24634       } else if (ch === quote) {
24635         this.index++;
24636         this.tokens.push({
24637           index: start,
24638           text: rawString,
24639           constant: true,
24640           value: string
24641         });
24642         return;
24643       } else {
24644         string += ch;
24645       }
24646       this.index++;
24647     }
24648     this.throwError('Unterminated quote', start);
24649   }
24650 };
24651
24652 var AST = function AST(lexer, options) {
24653   this.lexer = lexer;
24654   this.options = options;
24655 };
24656
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';
24673
24674 // Internal use only
24675 AST.NGValueParameter = 'NGValueParameter';
24676
24677 AST.prototype = {
24678   ast: function(text) {
24679     this.text = text;
24680     this.tokens = this.lexer.lex(text);
24681
24682     var value = this.program();
24683
24684     if (this.tokens.length !== 0) {
24685       this.throwError('is an unexpected token', this.tokens[0]);
24686     }
24687
24688     return value;
24689   },
24690
24691   program: function() {
24692     var body = [];
24693     while (true) {
24694       if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
24695         body.push(this.expressionStatement());
24696       if (!this.expect(';')) {
24697         return { type: AST.Program, body: body};
24698       }
24699     }
24700   },
24701
24702   expressionStatement: function() {
24703     return { type: AST.ExpressionStatement, expression: this.filterChain() };
24704   },
24705
24706   filterChain: function() {
24707     var left = this.expression();
24708     while (this.expect('|')) {
24709       left = this.filter(left);
24710     }
24711     return left;
24712   },
24713
24714   expression: function() {
24715     return this.assignment();
24716   },
24717
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');
24723       }
24724
24725       result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
24726     }
24727     return result;
24728   },
24729
24730   ternary: function() {
24731     var test = this.logicalOR();
24732     var alternate;
24733     var consequent;
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};
24739       }
24740     }
24741     return test;
24742   },
24743
24744   logicalOR: function() {
24745     var left = this.logicalAND();
24746     while (this.expect('||')) {
24747       left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
24748     }
24749     return left;
24750   },
24751
24752   logicalAND: function() {
24753     var left = this.equality();
24754     while (this.expect('&&')) {
24755       left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
24756     }
24757     return left;
24758   },
24759
24760   equality: function() {
24761     var left = this.relational();
24762     var token;
24763     while ((token = this.expect('==','!=','===','!=='))) {
24764       left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
24765     }
24766     return left;
24767   },
24768
24769   relational: function() {
24770     var left = this.additive();
24771     var token;
24772     while ((token = this.expect('<', '>', '<=', '>='))) {
24773       left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
24774     }
24775     return left;
24776   },
24777
24778   additive: function() {
24779     var left = this.multiplicative();
24780     var token;
24781     while ((token = this.expect('+','-'))) {
24782       left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
24783     }
24784     return left;
24785   },
24786
24787   multiplicative: function() {
24788     var left = this.unary();
24789     var token;
24790     while ((token = this.expect('*','/','%'))) {
24791       left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
24792     }
24793     return left;
24794   },
24795
24796   unary: function() {
24797     var token;
24798     if ((token = this.expect('+', '-', '!'))) {
24799       return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
24800     } else {
24801       return this.primary();
24802     }
24803   },
24804
24805   primary: function() {
24806     var primary;
24807     if (this.expect('(')) {
24808       primary = this.filterChain();
24809       this.consume(')');
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();
24822     } else {
24823       this.throwError('not a primary expression', this.peek());
24824     }
24825
24826     var next;
24827     while ((next = this.expect('(', '[', '.'))) {
24828       if (next.text === '(') {
24829         primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
24830         this.consume(')');
24831       } else if (next.text === '[') {
24832         primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
24833         this.consume(']');
24834       } else if (next.text === '.') {
24835         primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
24836       } else {
24837         this.throwError('IMPOSSIBLE');
24838       }
24839     }
24840     return primary;
24841   },
24842
24843   filter: function(baseExpression) {
24844     var args = [baseExpression];
24845     var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
24846
24847     while (this.expect(':')) {
24848       args.push(this.expression());
24849     }
24850
24851     return result;
24852   },
24853
24854   parseArguments: function() {
24855     var args = [];
24856     if (this.peekToken().text !== ')') {
24857       do {
24858         args.push(this.filterChain());
24859       } while (this.expect(','));
24860     }
24861     return args;
24862   },
24863
24864   identifier: function() {
24865     var token = this.consume();
24866     if (!token.identifier) {
24867       this.throwError('is not a valid identifier', token);
24868     }
24869     return { type: AST.Identifier, name: token.text };
24870   },
24871
24872   constant: function() {
24873     // TODO check that it is a constant
24874     return { type: AST.Literal, value: this.consume().value };
24875   },
24876
24877   arrayDeclaration: function() {
24878     var elements = [];
24879     if (this.peekToken().text !== ']') {
24880       do {
24881         if (this.peek(']')) {
24882           // Support trailing commas per ES5.1.
24883           break;
24884         }
24885         elements.push(this.expression());
24886       } while (this.expect(','));
24887     }
24888     this.consume(']');
24889
24890     return { type: AST.ArrayExpression, elements: elements };
24891   },
24892
24893   object: function() {
24894     var properties = [], property;
24895     if (this.peekToken().text !== '}') {
24896       do {
24897         if (this.peek('}')) {
24898           // Support trailing commas per ES5.1.
24899           break;
24900         }
24901         property = {type: AST.Property, kind: 'init'};
24902         if (this.peek().constant) {
24903           property.key = this.constant();
24904           property.computed = false;
24905           this.consume(':');
24906           property.value = this.expression();
24907         } else if (this.peek().identifier) {
24908           property.key = this.identifier();
24909           property.computed = false;
24910           if (this.peek(':')) {
24911             this.consume(':');
24912             property.value = this.expression();
24913           } else {
24914             property.value = property.key;
24915           }
24916         } else if (this.peek('[')) {
24917           this.consume('[');
24918           property.key = this.expression();
24919           this.consume(']');
24920           property.computed = true;
24921           this.consume(':');
24922           property.value = this.expression();
24923         } else {
24924           this.throwError('invalid key', this.peek());
24925         }
24926         properties.push(property);
24927       } while (this.expect(','));
24928     }
24929     this.consume('}');
24930
24931     return {type: AST.ObjectExpression, properties: properties };
24932   },
24933
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));
24938   },
24939
24940   consume: function(e1) {
24941     if (this.tokens.length === 0) {
24942       throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
24943     }
24944
24945     var token = this.expect(e1);
24946     if (!token) {
24947       this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
24948     }
24949     return token;
24950   },
24951
24952   peekToken: function() {
24953     if (this.tokens.length === 0) {
24954       throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
24955     }
24956     return this.tokens[0];
24957   },
24958
24959   peek: function(e1, e2, e3, e4) {
24960     return this.peekAhead(0, e1, e2, e3, e4);
24961   },
24962
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)) {
24969         return token;
24970       }
24971     }
24972     return false;
24973   },
24974
24975   expect: function(e1, e2, e3, e4) {
24976     var token = this.peek(e1, e2, e3, e4);
24977     if (token) {
24978       this.tokens.shift();
24979       return token;
24980     }
24981     return false;
24982   },
24983
24984   selfReferential: {
24985     'this': {type: AST.ThisExpression },
24986     '$locals': {type: AST.LocalsExpression }
24987   }
24988 };
24989
24990 function ifDefined(v, d) {
24991   return typeof v !== 'undefined' ? v : d;
24992 }
24993
24994 function plusFn(l, r) {
24995   if (typeof l === 'undefined') return r;
24996   if (typeof r === 'undefined') return l;
24997   return l + r;
24998 }
24999
25000 function isStateless($filter, filterName) {
25001   var fn = $filter(filterName);
25002   return !fn.$stateful;
25003 }
25004
25005 function findConstantAndWatchExpressions(ast, $filter) {
25006   var allConstants;
25007   var argsToWatch;
25008   var isStatelessFilter;
25009   switch (ast.type) {
25010   case AST.Program:
25011     allConstants = true;
25012     forEach(ast.body, function(expr) {
25013       findConstantAndWatchExpressions(expr.expression, $filter);
25014       allConstants = allConstants && expr.expression.constant;
25015     });
25016     ast.constant = allConstants;
25017     break;
25018   case AST.Literal:
25019     ast.constant = true;
25020     ast.toWatch = [];
25021     break;
25022   case AST.UnaryExpression:
25023     findConstantAndWatchExpressions(ast.argument, $filter);
25024     ast.constant = ast.argument.constant;
25025     ast.toWatch = ast.argument.toWatch;
25026     break;
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);
25032     break;
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];
25038     break;
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];
25045     break;
25046   case AST.Identifier:
25047     ast.constant = false;
25048     ast.toWatch = [ast];
25049     break;
25050   case AST.MemberExpression:
25051     findConstantAndWatchExpressions(ast.object, $filter);
25052     if (ast.computed) {
25053       findConstantAndWatchExpressions(ast.property, $filter);
25054     }
25055     ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
25056     ast.toWatch = [ast];
25057     break;
25058   case AST.CallExpression:
25059     isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;
25060     allConstants = isStatelessFilter;
25061     argsToWatch = [];
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);
25067       }
25068     });
25069     ast.constant = allConstants;
25070     ast.toWatch = isStatelessFilter ? argsToWatch : [ast];
25071     break;
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];
25077     break;
25078   case AST.ArrayExpression:
25079     allConstants = true;
25080     argsToWatch = [];
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);
25086       }
25087     });
25088     ast.constant = allConstants;
25089     ast.toWatch = argsToWatch;
25090     break;
25091   case AST.ObjectExpression:
25092     allConstants = true;
25093     argsToWatch = [];
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);
25099       }
25100     });
25101     ast.constant = allConstants;
25102     ast.toWatch = argsToWatch;
25103     break;
25104   case AST.ThisExpression:
25105     ast.constant = false;
25106     ast.toWatch = [];
25107     break;
25108   case AST.LocalsExpression:
25109     ast.constant = false;
25110     ast.toWatch = [];
25111     break;
25112   }
25113 }
25114
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;
25121 }
25122
25123 function isAssignable(ast) {
25124   return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
25125 }
25126
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: '='};
25130   }
25131 }
25132
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);
25139 }
25140
25141 function isConstant(ast) {
25142   return ast.constant;
25143 }
25144
25145 function ASTCompiler(astBuilder, $filter) {
25146   this.astBuilder = astBuilder;
25147   this.$filter = $filter;
25148 }
25149
25150 ASTCompiler.prototype = {
25151   compile: function(expression, expensiveChecks) {
25152     var self = this;
25153     var ast = this.astBuilder.ast(expression);
25154     this.state = {
25155       nextId: 0,
25156       filters: {},
25157       expensiveChecks: expensiveChecks,
25158       fn: {vars: [], body: [], own: {}},
25159       assign: {vars: [], body: [], own: {}},
25160       inputs: []
25161     };
25162     findConstantAndWatchExpressions(ast, self.$filter);
25163     var extra = '';
25164     var assignable;
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');
25172     }
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;
25184     });
25185     this.state.computing = 'fn';
25186     this.stage = 'main';
25187     this.recurse(ast);
25188     var fnString =
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') +
25194       extra +
25195       this.watchFns() +
25196       'return fn;';
25197
25198     // eslint-disable-next-line no-new-func
25199     var fn = (new Function('$filter',
25200         'ensureSafeMemberName',
25201         'ensureSafeObject',
25202         'ensureSafeFunction',
25203         'getStringValue',
25204         'ensureSafeAssignContext',
25205         'ifDefined',
25206         'plus',
25207         'text',
25208         fnString))(
25209           this.$filter,
25210           ensureSafeMemberName,
25211           ensureSafeObject,
25212           ensureSafeFunction,
25213           getStringValue,
25214           ensureSafeAssignContext,
25215           ifDefined,
25216           plusFn,
25217           expression);
25218     this.state = this.stage = undefined;
25219     fn.literal = isLiteral(ast);
25220     fn.constant = isConstant(ast);
25221     return fn;
25222   },
25223
25224   USE: 'use',
25225
25226   STRICT: 'strict',
25227
25228   watchFns: function() {
25229     var result = [];
25230     var fns = this.state.inputs;
25231     var self = this;
25232     forEach(fns, function(name) {
25233       result.push('var ' + name + '=' + self.generateFunction(name, 's'));
25234     });
25235     if (fns.length) {
25236       result.push('fn.inputs=[' + fns.join(',') + '];');
25237     }
25238     return result.join('');
25239   },
25240
25241   generateFunction: function(name, params) {
25242     return 'function(' + params + '){' +
25243         this.varsPrefix(name) +
25244         this.body(name) +
25245         '};';
25246   },
25247
25248   filterPrefix: function() {
25249     var parts = [];
25250     var self = this;
25251     forEach(this.state.filters, function(id, filter) {
25252       parts.push(id + '=$filter(' + self.escape(filter) + ')');
25253     });
25254     if (parts.length) return 'var ' + parts.join(',') + ';';
25255     return '';
25256   },
25257
25258   varsPrefix: function(section) {
25259     return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
25260   },
25261
25262   body: function(section) {
25263     return this.state[section].body.join('');
25264   },
25265
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();
25271       this.if_('i',
25272         this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
25273         this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
25274       );
25275       return;
25276     }
25277     switch (ast.type) {
25278     case AST.Program:
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, ';');
25283         } else {
25284           self.return_(right);
25285         }
25286       });
25287       break;
25288     case AST.Literal:
25289       expression = this.escape(ast.value);
25290       this.assign(intoId, expression);
25291       recursionFn(expression);
25292       break;
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);
25298       break;
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);
25306       } else {
25307         expression = '(' + left + ')' + ast.operator + '(' + right + ')';
25308       }
25309       this.assign(intoId, expression);
25310       recursionFn(expression);
25311       break;
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);
25317       break;
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);
25323       break;
25324     case AST.Identifier:
25325       intoId = intoId || this.nextId();
25326       if (nameId) {
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;
25330       }
25331       ensureSafeMemberName(ast.name);
25332       self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
25333         function() {
25334           self.if_(self.stage === 'inputs' || 's', function() {
25335             if (create && create !== 1) {
25336               self.if_(
25337                 self.not(self.nonComputedMember('s', ast.name)),
25338                 self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
25339             }
25340             self.assign(intoId, self.nonComputedMember('s', ast.name));
25341           });
25342         }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
25343         );
25344       if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
25345         self.addEnsureSafeObject(intoId);
25346       }
25347       recursionFn(intoId);
25348       break;
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);
25356           }
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), '{}'));
25364             }
25365             expression = self.ensureSafeObject(self.computedMember(left, right));
25366             self.assign(intoId, expression);
25367             if (nameId) {
25368               nameId.computed = true;
25369               nameId.name = right;
25370             }
25371           } else {
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), '{}'));
25375             }
25376             expression = self.nonComputedMember(left, ast.property.name);
25377             if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
25378               expression = self.ensureSafeObject(expression);
25379             }
25380             self.assign(intoId, expression);
25381             if (nameId) {
25382               nameId.computed = false;
25383               nameId.name = ast.property.name;
25384             }
25385           }
25386         }, function() {
25387           self.assign(intoId, 'undefined');
25388         });
25389         recursionFn(intoId);
25390       }, !!create);
25391       break;
25392     case AST.CallExpression:
25393       intoId = intoId || this.nextId();
25394       if (ast.filter) {
25395         right = self.filter(ast.callee.name);
25396         args = [];
25397         forEach(ast.arguments, function(expr) {
25398           var argument = self.nextId();
25399           self.recurse(expr, argument);
25400           args.push(argument);
25401         });
25402         expression = right + '(' + args.join(',') + ')';
25403         self.assign(intoId, expression);
25404         recursionFn(intoId);
25405       } else {
25406         right = self.nextId();
25407         left = {};
25408         args = [];
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));
25415               });
25416             });
25417             if (left.name) {
25418               if (!self.state.expensiveChecks) {
25419                 self.addEnsureSafeObject(left.context);
25420               }
25421               expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
25422             } else {
25423               expression = right + '(' + args.join(',') + ')';
25424             }
25425             expression = self.ensureSafeObject(expression);
25426             self.assign(intoId, expression);
25427           }, function() {
25428             self.assign(intoId, 'undefined');
25429           });
25430           recursionFn(intoId);
25431         });
25432       }
25433       break;
25434     case AST.AssignmentExpression:
25435       right = this.nextId();
25436       left = {};
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);
25445         });
25446       }, 1);
25447       break;
25448     case AST.ArrayExpression:
25449       args = [];
25450       forEach(ast.elements, function(expr) {
25451         self.recurse(expr, self.nextId(), undefined, function(argument) {
25452           args.push(argument);
25453         });
25454       });
25455       expression = '[' + args.join(',') + ']';
25456       this.assign(intoId, expression);
25457       recursionFn(expression);
25458       break;
25459     case AST.ObjectExpression:
25460       args = [];
25461       computed = false;
25462       forEach(ast.properties, function(property) {
25463         if (property.computed) {
25464           computed = true;
25465         }
25466       });
25467       if (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);
25474           } else {
25475             left = property.key.type === AST.Identifier ?
25476                        property.key.name :
25477                        ('' + property.key.value);
25478           }
25479           right = self.nextId();
25480           self.recurse(property.value, right);
25481           self.assign(self.member(intoId, left, property.computed), right);
25482         });
25483       } else {
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)) +
25489                 ':' + expr);
25490           });
25491         });
25492         expression = '{' + args.join(',') + '}';
25493         this.assign(intoId, expression);
25494       }
25495       recursionFn(intoId || expression);
25496       break;
25497     case AST.ThisExpression:
25498       this.assign(intoId, 's');
25499       recursionFn('s');
25500       break;
25501     case AST.LocalsExpression:
25502       this.assign(intoId, 'l');
25503       recursionFn('l');
25504       break;
25505     case AST.NGValueParameter:
25506       this.assign(intoId, 'v');
25507       recursionFn('v');
25508       break;
25509     }
25510   },
25511
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 + ')');
25517     }
25518     return own[key];
25519   },
25520
25521   assign: function(id, value) {
25522     if (!id) return;
25523     this.current().body.push(id, '=', value, ';');
25524     return id;
25525   },
25526
25527   filter: function(filterName) {
25528     if (!this.state.filters.hasOwnProperty(filterName)) {
25529       this.state.filters[filterName] = this.nextId(true);
25530     }
25531     return this.state.filters[filterName];
25532   },
25533
25534   ifDefined: function(id, defaultValue) {
25535     return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
25536   },
25537
25538   plus: function(left, right) {
25539     return 'plus(' + left + ',' + right + ')';
25540   },
25541
25542   return_: function(id) {
25543     this.current().body.push('return ', id, ';');
25544   },
25545
25546   if_: function(test, alternate, consequent) {
25547     if (test === true) {
25548       alternate();
25549     } else {
25550       var body = this.current().body;
25551       body.push('if(', test, '){');
25552       alternate();
25553       body.push('}');
25554       if (consequent) {
25555         body.push('else{');
25556         consequent();
25557         body.push('}');
25558       }
25559     }
25560   },
25561
25562   not: function(expression) {
25563     return '!(' + expression + ')';
25564   },
25565
25566   notNull: function(expression) {
25567     return expression + '!=null';
25568   },
25569
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;
25575     } else {
25576       return left  + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
25577     }
25578   },
25579
25580   computedMember: function(left, right) {
25581     return left + '[' + right + ']';
25582   },
25583
25584   member: function(left, right, computed) {
25585     if (computed) return this.computedMember(left, right);
25586     return this.nonComputedMember(left, right);
25587   },
25588
25589   addEnsureSafeObject: function(item) {
25590     this.current().body.push(this.ensureSafeObject(item), ';');
25591   },
25592
25593   addEnsureSafeMemberName: function(item) {
25594     this.current().body.push(this.ensureSafeMemberName(item), ';');
25595   },
25596
25597   addEnsureSafeFunction: function(item) {
25598     this.current().body.push(this.ensureSafeFunction(item), ';');
25599   },
25600
25601   addEnsureSafeAssignContext: function(item) {
25602     this.current().body.push(this.ensureSafeAssignContext(item), ';');
25603   },
25604
25605   ensureSafeObject: function(item) {
25606     return 'ensureSafeObject(' + item + ',text)';
25607   },
25608
25609   ensureSafeMemberName: function(item) {
25610     return 'ensureSafeMemberName(' + item + ',text)';
25611   },
25612
25613   ensureSafeFunction: function(item) {
25614     return 'ensureSafeFunction(' + item + ',text)';
25615   },
25616
25617   getStringValue: function(item) {
25618     this.assign(item, 'getStringValue(' + item + ')');
25619   },
25620
25621   ensureSafeAssignContext: function(item) {
25622     return 'ensureSafeAssignContext(' + item + ',text)';
25623   },
25624
25625   lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
25626     var self = this;
25627     return function() {
25628       self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
25629     };
25630   },
25631
25632   lazyAssign: function(id, value) {
25633     var self = this;
25634     return function() {
25635       self.assign(id, value);
25636     };
25637   },
25638
25639   stringEscapeRegex: /[^ a-zA-Z0-9]/g,
25640
25641   stringEscapeFn: function(c) {
25642     return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
25643   },
25644
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';
25652
25653     throw $parseMinErr('esc', 'IMPOSSIBLE');
25654   },
25655
25656   nextId: function(skip, init) {
25657     var id = 'v' + (this.state.nextId++);
25658     if (!skip) {
25659       this.current().vars.push(id + (init ? '=' + init : ''));
25660     }
25661     return id;
25662   },
25663
25664   current: function() {
25665     return this.state[this.state.computing];
25666   }
25667 };
25668
25669
25670 function ASTInterpreter(astBuilder, $filter) {
25671   this.astBuilder = astBuilder;
25672   this.$filter = $filter;
25673 }
25674
25675 ASTInterpreter.prototype = {
25676   compile: function(expression, expensiveChecks) {
25677     var self = this;
25678     var ast = this.astBuilder.ast(expression);
25679     this.expression = expression;
25680     this.expensiveChecks = expensiveChecks;
25681     findConstantAndWatchExpressions(ast, self.$filter);
25682     var assignable;
25683     var assign;
25684     if ((assignable = assignableAST(ast))) {
25685       assign = this.recurse(assignable);
25686     }
25687     var toWatch = getInputs(ast.body);
25688     var inputs;
25689     if (toWatch) {
25690       inputs = [];
25691       forEach(toWatch, function(watch, key) {
25692         var input = self.recurse(watch);
25693         watch.input = input;
25694         inputs.push(input);
25695         watch.watchId = key;
25696       });
25697     }
25698     var expressions = [];
25699     forEach(ast.body, function(expression) {
25700       expressions.push(self.recurse(expression.expression));
25701     });
25702     var fn = ast.body.length === 0 ? noop :
25703              ast.body.length === 1 ? expressions[0] :
25704              function(scope, locals) {
25705                var lastValue;
25706                forEach(expressions, function(exp) {
25707                  lastValue = exp(scope, locals);
25708                });
25709                return lastValue;
25710              };
25711     if (assign) {
25712       fn.assign = function(scope, value, locals) {
25713         return assign(scope, locals, value);
25714       };
25715     }
25716     if (inputs) {
25717       fn.inputs = inputs;
25718     }
25719     fn.literal = isLiteral(ast);
25720     fn.constant = isConstant(ast);
25721     return fn;
25722   },
25723
25724   recurse: function(ast, context, create) {
25725     var left, right, self = this, args;
25726     if (ast.input) {
25727       return this.inputs(ast.input, ast.watchId);
25728     }
25729     switch (ast.type) {
25730     case AST.Literal:
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),
25748         context
25749       );
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;
25760       }
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:
25766       args = [];
25767       forEach(ast.arguments, function(expr) {
25768         args.push(self.recurse(expr));
25769       });
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) {
25774           var values = [];
25775           for (var i = 0; i < args.length; ++i) {
25776             values.push(args[i](scope, locals, assign, inputs));
25777           }
25778           var value = right.apply(undefined, values, inputs);
25779           return context ? {context: undefined, name: undefined, value: value} : value;
25780         } :
25781         function(scope, locals, assign, inputs) {
25782           var rhs = right(scope, locals, assign, inputs);
25783           var value;
25784           if (rhs.value != null) {
25785             ensureSafeObject(rhs.context, self.expression);
25786             ensureSafeFunction(rhs.value, self.expression);
25787             var values = [];
25788             for (var i = 0; i < args.length; ++i) {
25789               values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
25790             }
25791             value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
25792           }
25793           return context ? {value: value} : value;
25794         };
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;
25805       };
25806     case AST.ArrayExpression:
25807       args = [];
25808       forEach(ast.elements, function(expr) {
25809         args.push(self.recurse(expr));
25810       });
25811       return function(scope, locals, assign, inputs) {
25812         var value = [];
25813         for (var i = 0; i < args.length; ++i) {
25814           value.push(args[i](scope, locals, assign, inputs));
25815         }
25816         return context ? {value: value} : value;
25817       };
25818     case AST.ObjectExpression:
25819       args = [];
25820       forEach(ast.properties, function(property) {
25821         if (property.computed) {
25822           args.push({key: self.recurse(property.key),
25823                      computed: true,
25824                      value: self.recurse(property.value)
25825           });
25826         } else {
25827           args.push({key: property.key.type === AST.Identifier ?
25828                           property.key.name :
25829                           ('' + property.key.value),
25830                      computed: false,
25831                      value: self.recurse(property.value)
25832           });
25833         }
25834       });
25835       return function(scope, locals, assign, inputs) {
25836         var value = {};
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);
25840           } else {
25841             value[args[i].key] = args[i].value(scope, locals, assign, inputs);
25842           }
25843         }
25844         return context ? {value: value} : value;
25845       };
25846     case AST.ThisExpression:
25847       return function(scope) {
25848         return context ? {value: scope} : scope;
25849       };
25850     case AST.LocalsExpression:
25851       return function(scope, locals) {
25852         return context ? {value: locals} : locals;
25853       };
25854     case AST.NGValueParameter:
25855       return function(scope, locals, assign) {
25856         return context ? {value: assign} : assign;
25857       };
25858     }
25859   },
25860
25861   'unary+': function(argument, context) {
25862     return function(scope, locals, assign, inputs) {
25863       var arg = argument(scope, locals, assign, inputs);
25864       if (isDefined(arg)) {
25865         arg = +arg;
25866       } else {
25867         arg = 0;
25868       }
25869       return context ? {value: arg} : arg;
25870     };
25871   },
25872   'unary-': function(argument, context) {
25873     return function(scope, locals, assign, inputs) {
25874       var arg = argument(scope, locals, assign, inputs);
25875       if (isDefined(arg)) {
25876         arg = -arg;
25877       } else {
25878         arg = 0;
25879       }
25880       return context ? {value: arg} : arg;
25881     };
25882   },
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;
25887     };
25888   },
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;
25895     };
25896   },
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;
25903     };
25904   },
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;
25909     };
25910   },
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;
25915     };
25916   },
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;
25921     };
25922   },
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;
25927     };
25928   },
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;
25933     };
25934   },
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;
25940     };
25941   },
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;
25947     };
25948   },
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;
25953     };
25954   },
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;
25959     };
25960   },
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;
25965     };
25966   },
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;
25971     };
25972   },
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;
25977     };
25978   },
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;
25983     };
25984   },
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;
25989     };
25990   },
25991   value: function(value, context) {
25992     return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
25993   },
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])) {
25998         base[name] = {};
25999       }
26000       var value = base ? base[name] : undefined;
26001       if (expensiveChecks) {
26002         ensureSafeObject(value, expression);
26003       }
26004       if (context) {
26005         return {context: base, name: name, value: value};
26006       } else {
26007         return value;
26008       }
26009     };
26010   },
26011   computedMember: function(left, right, context, create, expression) {
26012     return function(scope, locals, assign, inputs) {
26013       var lhs = left(scope, locals, assign, inputs);
26014       var rhs;
26015       var value;
26016       if (lhs != null) {
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])) {
26023             lhs[rhs] = {};
26024           }
26025         }
26026         value = lhs[rhs];
26027         ensureSafeObject(value, expression);
26028       }
26029       if (context) {
26030         return {context: lhs, name: rhs, value: value};
26031       } else {
26032         return value;
26033       }
26034     };
26035   },
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])) {
26042           lhs[right] = {};
26043         }
26044       }
26045       var value = lhs != null ? lhs[right] : undefined;
26046       if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
26047         ensureSafeObject(value, expression);
26048       }
26049       if (context) {
26050         return {context: lhs, name: right, value: value};
26051       } else {
26052         return value;
26053       }
26054     };
26055   },
26056   inputs: function(input, watchId) {
26057     return function(scope, value, locals, inputs) {
26058       if (inputs) return inputs[watchId];
26059       return input(scope, value, locals);
26060     };
26061   }
26062 };
26063
26064 /**
26065  * @constructor
26066  */
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);
26074 };
26075
26076 Parser.prototype = {
26077   constructor: Parser,
26078
26079   parse: function(text) {
26080     return this.astCompiler.compile(text, this.options.expensiveChecks);
26081   }
26082 };
26083
26084 function isPossiblyDangerousMemberName(name) {
26085   return name === 'constructor';
26086 }
26087
26088 function getValueOf(value) {
26089   return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
26090 }
26091
26092 ///////////////////////////////////
26093
26094 /**
26095  * @ngdoc service
26096  * @name $parse
26097  * @kind function
26098  *
26099  * @description
26100  *
26101  * Converts Angular {@link guide/expression expression} into a function.
26102  *
26103  * ```js
26104  *   var getter = $parse('user.name');
26105  *   var setter = getter.assign;
26106  *   var context = {user:{name:'angular'}};
26107  *   var locals = {user:{name:'local'}};
26108  *
26109  *   expect(getter(context)).toEqual('angular');
26110  *   setter(context, 'newValue');
26111  *   expect(context.user.name).toEqual('newValue');
26112  *   expect(getter(context, locals)).toEqual('local');
26113  * ```
26114  *
26115  *
26116  * @param {string} expression String expression to compile.
26117  * @returns {function(context, locals)} a function which represents the compiled expression:
26118  *
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
26122  *      `context`.
26123  *
26124  *    The returned function also has the following properties:
26125  *      * `literal` â€“ `{boolean}` â€“ whether the expression's top-level node is a JavaScript
26126  *        literal.
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.
26131  *
26132  */
26133
26134
26135 /**
26136  * @ngdoc provider
26137  * @name $parseProvider
26138  * @this
26139  *
26140  * @description
26141  * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
26142  *  service.
26143  */
26144 function $ParseProvider() {
26145   var cacheDefault = createMap();
26146   var cacheExpensive = createMap();
26147   var literals = {
26148     'true': true,
26149     'false': false,
26150     'null': null,
26151     'undefined': undefined
26152   };
26153   var identStart, identContinue;
26154
26155   /**
26156    * @ngdoc method
26157    * @name $parseProvider#addLiteral
26158    * @description
26159    *
26160    * Configure $parse service to add literal values that will be present as literal at expressions.
26161    *
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`.
26164    *
26165    **/
26166   this.addLiteral = function(literalName, literalValue) {
26167     literals[literalName] = literalValue;
26168   };
26169
26170  /**
26171   * @ngdoc method
26172   * @name $parseProvider#setIdentifierFns
26173   *
26174   * @description
26175   *
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.
26185   *
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.
26188   *
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.
26193   */
26194   this.setIdentifierFns = function(identifierStart, identifierContinue) {
26195     identStart = identifierStart;
26196     identContinue = identifierContinue;
26197     return this;
26198   };
26199
26200   this.$get = ['$filter', function($filter) {
26201     var noUnsafeEval = csp().noUnsafeEval;
26202     var $parseOptions = {
26203           csp: noUnsafeEval,
26204           expensiveChecks: false,
26205           literals: copy(literals),
26206           isIdentifierStart: isFunction(identStart) && identStart,
26207           isIdentifierContinue: isFunction(identContinue) && identContinue
26208         },
26209         $parseOptionsExpensive = {
26210           csp: noUnsafeEval,
26211           expensiveChecks: true,
26212           literals: copy(literals),
26213           isIdentifierStart: isFunction(identStart) && identStart,
26214           isIdentifierContinue: isFunction(identContinue) && identContinue
26215         };
26216     var runningChecksEnabled = false;
26217
26218     $parse.$$runningExpensiveChecks = function() {
26219       return runningChecksEnabled;
26220     };
26221
26222     return $parse;
26223
26224     function $parse(exp, interceptorFn, expensiveChecks) {
26225       var parsedExpression, oneTime, cacheKey;
26226
26227       expensiveChecks = expensiveChecks || runningChecksEnabled;
26228
26229       switch (typeof exp) {
26230         case 'string':
26231           exp = exp.trim();
26232           cacheKey = exp;
26233
26234           var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
26235           parsedExpression = cache[cacheKey];
26236
26237           if (!parsedExpression) {
26238             if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
26239               oneTime = true;
26240               exp = exp.substring(2);
26241             }
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;
26253             }
26254             if (expensiveChecks) {
26255               parsedExpression = expensiveChecksInterceptor(parsedExpression);
26256             }
26257             cache[cacheKey] = parsedExpression;
26258           }
26259           return addInterceptor(parsedExpression, interceptorFn);
26260
26261         case 'function':
26262           return addInterceptor(exp, interceptorFn);
26263
26264         default:
26265           return addInterceptor(noop, interceptorFn);
26266       }
26267     }
26268
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]);
26277       }
26278       expensiveCheckFn.inputs = fn.inputs;
26279
26280       return expensiveCheckFn;
26281
26282       function expensiveCheckFn(scope, locals, assign, inputs) {
26283         var expensiveCheckOldValue = runningChecksEnabled;
26284         runningChecksEnabled = true;
26285         try {
26286           return fn(scope, locals, assign, inputs);
26287         } finally {
26288           runningChecksEnabled = expensiveCheckOldValue;
26289         }
26290       }
26291     }
26292
26293     function expressionInputDirtyCheck(newValue, oldValueOfValue) {
26294
26295       if (newValue == null || oldValueOfValue == null) { // null/undefined
26296         return newValue === oldValueOfValue;
26297       }
26298
26299       if (typeof newValue === 'object') {
26300
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);
26305
26306         if (typeof newValue === 'object') {
26307           // objects/arrays are not supported - deep-watching them would be too expensive
26308           return false;
26309         }
26310
26311         // fall-through to the primitive equality check
26312       }
26313
26314       //Primitive or NaN
26315       // eslint-disable-next-line no-self-compare
26316       return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
26317     }
26318
26319     function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
26320       var inputExpressions = parsedExpression.inputs;
26321       var lastResult;
26322
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);
26331           }
26332           return lastResult;
26333         }, listener, objectEquality, prettyPrintExpression);
26334       }
26335
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;
26341       }
26342
26343       return scope.$watch(function expressionInputsWatch(scope) {
26344         var changed = false;
26345
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);
26351           }
26352         }
26353
26354         if (changed) {
26355           lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
26356         }
26357
26358         return lastResult;
26359       }, listener, objectEquality, prettyPrintExpression);
26360     }
26361
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) {
26367         lastValue = value;
26368         if (isFunction(listener)) {
26369           listener.apply(this, arguments);
26370         }
26371         if (isDefined(value)) {
26372           scope.$$postDigest(function() {
26373             if (isDefined(lastValue)) {
26374               unwatch();
26375             }
26376           });
26377         }
26378       }, objectEquality);
26379       return unwatch;
26380     }
26381
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) {
26387         lastValue = value;
26388         if (isFunction(listener)) {
26389           listener.call(this, value, old, scope);
26390         }
26391         if (isAllDefined(value)) {
26392           scope.$$postDigest(function() {
26393             if (isAllDefined(lastValue)) unwatch();
26394           });
26395         }
26396       }, objectEquality);
26397
26398       return unwatch;
26399
26400       function isAllDefined(value) {
26401         var allDefined = true;
26402         forEach(value, function(val) {
26403           if (!isDefined(val)) allDefined = false;
26404         });
26405         return allDefined;
26406       }
26407     }
26408
26409     function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
26410       var unwatch = scope.$watch(function constantWatch(scope) {
26411         unwatch();
26412         return parsedExpression(scope);
26413       }, listener, objectEquality);
26414       return unwatch;
26415     }
26416
26417     function addInterceptor(parsedExpression, interceptorFn) {
26418       if (!interceptorFn) return parsedExpression;
26419       var watchDelegate = parsedExpression.$$watchDelegate;
26420       var useInputs = false;
26421
26422       var regularWatch =
26423           watchDelegate !== oneTimeLiteralWatchDelegate &&
26424           watchDelegate !== oneTimeWatchDelegate;
26425
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;
26435       };
26436
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];
26447       }
26448
26449       return fn;
26450     }
26451   }];
26452 }
26453
26454 /**
26455  * @ngdoc service
26456  * @name $q
26457  * @requires $rootScope
26458  * @this
26459  *
26460  * @description
26461  * A service that helps you run functions asynchronously, and use their return values (or exceptions)
26462  * when they are done processing.
26463  *
26464  * This is an implementation of promises/deferred objects inspired by
26465  * [Kris Kowal's Q](https://github.com/kriskowal/q).
26466  *
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.
26469  *
26470  * # $q constructor
26471  *
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).
26475  *
26476  * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
26477  * available yet.
26478  *
26479  * It can be used like so:
26480  *
26481  * ```js
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).
26484  *
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 + '!');
26491  *         } else {
26492  *           reject('Greeting ' + name + ' is not allowed.');
26493  *         }
26494  *       }, 1000);
26495  *     });
26496  *   }
26497  *
26498  *   var promise = asyncGreet('Robin Hood');
26499  *   promise.then(function(greeting) {
26500  *     alert('Success: ' + greeting);
26501  *   }, function(reason) {
26502  *     alert('Failed: ' + reason);
26503  *   });
26504  * ```
26505  *
26506  * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
26507  *
26508  * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
26509  *
26510  * However, the more traditional CommonJS-style usage is still available, and documented below.
26511  *
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.
26515  *
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.
26518  *
26519  * ```js
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).
26522  *
26523  *   function asyncGreet(name) {
26524  *     var deferred = $q.defer();
26525  *
26526  *     setTimeout(function() {
26527  *       deferred.notify('About to greet ' + name + '.');
26528  *
26529  *       if (okToGreet(name)) {
26530  *         deferred.resolve('Hello, ' + name + '!');
26531  *       } else {
26532  *         deferred.reject('Greeting ' + name + ' is not allowed.');
26533  *       }
26534  *     }, 1000);
26535  *
26536  *     return deferred.promise;
26537  *   }
26538  *
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);
26546  *   });
26547  * ```
26548  *
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.
26552  *
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.
26557  *
26558  * # The Deferred API
26559  *
26560  * A new instance of deferred is constructed by calling `$q.defer()`.
26561  *
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
26564  * of the task.
26565  *
26566  * **Methods**
26567  *
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.
26574  *
26575  * **Properties**
26576  *
26577  * - promise â€“ `{Promise}` â€“ promise object associated with this deferred.
26578  *
26579  *
26580  * # The Promise API
26581  *
26582  * A new promise instance is created when a deferred instance is created and can be retrieved by
26583  * calling `deferred.promise`.
26584  *
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.
26587  *
26588  * **Methods**
26589  *
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.
26595  *
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.
26603  *
26604  * - `catch(errorCallback)` â€“ shorthand for `promise.then(null, errorCallback)`
26605  *
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.
26611  *
26612  * # Chaining promises
26613  *
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:
26616  *
26617  * ```js
26618  *   promiseB = promiseA.then(function(result) {
26619  *     return result + 1;
26620  *   });
26621  *
26622  *   // promiseB will be resolved immediately after promiseA is resolved and its value
26623  *   // will be the result of promiseA incremented by 1
26624  * ```
26625  *
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.
26630  *
26631  *
26632  * # Differences between Kris Kowal's Q and $q
26633  *
26634  *  There are two main differences:
26635  *
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.
26641  *
26642  * # Testing
26643  *
26644  *  ```js
26645  *    it('should simulate promise', inject(function($q, $rootScope) {
26646  *      var deferred = $q.defer();
26647  *      var promise = deferred.promise;
26648  *      var resolvedValue;
26649  *
26650  *      promise.then(function(value) { resolvedValue = value; });
26651  *      expect(resolvedValue).toBeUndefined();
26652  *
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();
26659  *
26660  *      // Propagate promise resolution to 'then' functions using $apply().
26661  *      $rootScope.$apply();
26662  *      expect(resolvedValue).toEqual(123);
26663  *    }));
26664  *  ```
26665  *
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.
26669  *
26670  * @returns {Promise} The newly created promise.
26671  */
26672 function $QProvider() {
26673
26674   this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
26675     return qFactory(function(callback) {
26676       $rootScope.$evalAsync(callback);
26677     }, $exceptionHandler);
26678   }];
26679 }
26680
26681 /** @this */
26682 function $$QProvider() {
26683   this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
26684     return qFactory(function(callback) {
26685       $browser.defer(callback);
26686     }, $exceptionHandler);
26687   }];
26688 }
26689
26690 /**
26691  * Constructs a promise manager.
26692  *
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.
26697  */
26698 function qFactory(nextTick, exceptionHandler) {
26699   var $qMinErr = minErr('$q', TypeError);
26700
26701   /**
26702    * @ngdoc method
26703    * @name ng.$q#defer
26704    * @kind function
26705    *
26706    * @description
26707    * Creates a `Deferred` object which represents a task which will finish in the future.
26708    *
26709    * @returns {Deferred} Returns a new instance of deferred.
26710    */
26711   function defer() {
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);
26717     return d;
26718   }
26719
26720   function Promise() {
26721     this.$$state = { status: 0 };
26722   }
26723
26724   extend(Promise.prototype, {
26725     then: function(onFulfilled, onRejected, progressBack) {
26726       if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
26727         return this;
26728       }
26729       var result = new Deferred();
26730
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);
26734
26735       return result.promise;
26736     },
26737
26738     'catch': function(callback) {
26739       return this.then(null, callback);
26740     },
26741
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);
26747       }, progressBack);
26748     }
26749   });
26750
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);
26755     };
26756   }
26757
26758   function processQueue(state) {
26759     var fn, deferred, pending;
26760
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];
26767       try {
26768         if (isFunction(fn)) {
26769           deferred.resolve(fn(state.value));
26770         } else if (state.status === 1) {
26771           deferred.resolve(state.value);
26772         } else {
26773           deferred.reject(state.value);
26774         }
26775       } catch (e) {
26776         deferred.reject(e);
26777         exceptionHandler(e);
26778       }
26779     }
26780   }
26781
26782   function scheduleProcessQueue(state) {
26783     if (state.processScheduled || !state.pending) return;
26784     state.processScheduled = true;
26785     nextTick(function() { processQueue(state); });
26786   }
26787
26788   function Deferred() {
26789     this.promise = new Promise();
26790   }
26791
26792   extend(Deferred.prototype, {
26793     resolve: function(val) {
26794       if (this.promise.$$state.status) return;
26795       if (val === this.promise) {
26796         this.$$reject($qMinErr(
26797           'qcycle',
26798           'Expected promise to be resolved with value other than itself \'{0}\'',
26799           val));
26800       } else {
26801         this.$$resolve(val);
26802       }
26803
26804     },
26805
26806     $$resolve: function(val) {
26807       var then;
26808       var that = this;
26809       var done = false;
26810       try {
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));
26815         } else {
26816           this.promise.$$state.value = val;
26817           this.promise.$$state.status = 1;
26818           scheduleProcessQueue(this.promise.$$state);
26819         }
26820       } catch (e) {
26821         rejectPromise(e);
26822         exceptionHandler(e);
26823       }
26824
26825       function resolvePromise(val) {
26826         if (done) return;
26827         done = true;
26828         that.$$resolve(val);
26829       }
26830       function rejectPromise(val) {
26831         if (done) return;
26832         done = true;
26833         that.$$reject(val);
26834       }
26835     },
26836
26837     reject: function(reason) {
26838       if (this.promise.$$state.status) return;
26839       this.$$reject(reason);
26840     },
26841
26842     $$reject: function(reason) {
26843       this.promise.$$state.value = reason;
26844       this.promise.$$state.status = 2;
26845       scheduleProcessQueue(this.promise.$$state);
26846     },
26847
26848     notify: function(progress) {
26849       var callbacks = this.promise.$$state.pending;
26850
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];
26857             try {
26858               result.notify(isFunction(callback) ? callback(progress) : progress);
26859             } catch (e) {
26860               exceptionHandler(e);
26861             }
26862           }
26863         });
26864       }
26865     }
26866   });
26867
26868   /**
26869    * @ngdoc method
26870    * @name $q#reject
26871    * @kind function
26872    *
26873    * @description
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.
26877    *
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
26882    * `reject`.
26883    *
26884    * ```js
26885    *   promiseB = promiseA.then(function(result) {
26886    *     // success: do something and resolve promiseB
26887    *     //          with the old or a new result
26888    *     return 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;
26896    *     }
26897    *     return $q.reject(reason);
26898    *   });
26899    * ```
26900    *
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`.
26903    */
26904   function reject(reason) {
26905     var result = new Deferred();
26906     result.reject(reason);
26907     return result.promise;
26908   }
26909
26910   function handleCallback(value, resolver, callback) {
26911     var callbackOutput = null;
26912     try {
26913       if (isFunction(callback)) callbackOutput = callback();
26914     } catch (e) {
26915       return reject(e);
26916     }
26917     if (isPromiseLike(callbackOutput)) {
26918       return callbackOutput.then(function() {
26919         return resolver(value);
26920       }, reject);
26921     } else {
26922       return resolver(value);
26923     }
26924   }
26925
26926   /**
26927    * @ngdoc method
26928    * @name $q#when
26929    * @kind function
26930    *
26931    * @description
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.
26935    *
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
26941    */
26942
26943
26944   function when(value, callback, errback, progressBack) {
26945     var result = new Deferred();
26946     result.resolve(value);
26947     return result.promise.then(callback, errback, progressBack);
26948   }
26949
26950   /**
26951    * @ngdoc method
26952    * @name $q#resolve
26953    * @kind function
26954    *
26955    * @description
26956    * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
26957    *
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
26963    */
26964   var resolve = when;
26965
26966   /**
26967    * @ngdoc method
26968    * @name $q#all
26969    * @kind function
26970    *
26971    * @description
26972    * Combines multiple promises into a single promise that is resolved when all of the input
26973    * promises are resolved.
26974    *
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.
26980    */
26981
26982   function all(promises) {
26983     var deferred = new Deferred(),
26984         counter = 0,
26985         results = isArray(promises) ? [] : {};
26986
26987     forEach(promises, function(promise, key) {
26988       counter++;
26989       when(promise).then(function(value) {
26990         results[key] = value;
26991         if (!(--counter)) deferred.resolve(results);
26992       }, function(reason) {
26993         deferred.reject(reason);
26994       });
26995     });
26996
26997     if (counter === 0) {
26998       deferred.resolve(results);
26999     }
27000
27001     return deferred.promise;
27002   }
27003
27004   /**
27005    * @ngdoc method
27006    * @name $q#race
27007    * @kind function
27008    *
27009    * @description
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.
27012    *
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.
27016    */
27017
27018   function race(promises) {
27019     var deferred = defer();
27020
27021     forEach(promises, function(promise) {
27022       when(promise).then(deferred.resolve, deferred.reject);
27023     });
27024
27025     return deferred.promise;
27026   }
27027
27028   function $Q(resolver) {
27029     if (!isFunction(resolver)) {
27030       throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver);
27031     }
27032
27033     var deferred = new Deferred();
27034
27035     function resolveFn(value) {
27036       deferred.resolve(value);
27037     }
27038
27039     function rejectFn(reason) {
27040       deferred.reject(reason);
27041     }
27042
27043     resolver(resolveFn, rejectFn);
27044
27045     return deferred.promise;
27046   }
27047
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;
27051
27052   $Q.defer = defer;
27053   $Q.reject = reject;
27054   $Q.when = when;
27055   $Q.resolve = resolve;
27056   $Q.all = all;
27057   $Q.race = race;
27058
27059   return $Q;
27060 }
27061
27062 /** @this */
27063 function $$RAFProvider() { //rAF
27064   this.$get = ['$window', '$timeout', function($window, $timeout) {
27065     var requestAnimationFrame = $window.requestAnimationFrame ||
27066                                 $window.webkitRequestAnimationFrame;
27067
27068     var cancelAnimationFrame = $window.cancelAnimationFrame ||
27069                                $window.webkitCancelAnimationFrame ||
27070                                $window.webkitCancelRequestAnimationFrame;
27071
27072     var rafSupported = !!requestAnimationFrame;
27073     var raf = rafSupported
27074       ? function(fn) {
27075           var id = requestAnimationFrame(fn);
27076           return function() {
27077             cancelAnimationFrame(id);
27078           };
27079         }
27080       : function(fn) {
27081           var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
27082           return function() {
27083             $timeout.cancel(timer);
27084           };
27085         };
27086
27087     raf.supported = rafSupported;
27088
27089     return raf;
27090   }];
27091 }
27092
27093 /**
27094  * DESIGN NOTES
27095  *
27096  * The design decisions behind the scope are heavily favored for speed and memory consumption.
27097  *
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.
27100  *
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
27105  *
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)
27109  *
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
27112  *
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
27115  * to construct.
27116  */
27117
27118
27119 /**
27120  * @ngdoc provider
27121  * @name $rootScopeProvider
27122  * @description
27123  *
27124  * Provider for the $rootScope service.
27125  */
27126
27127 /**
27128  * @ngdoc method
27129  * @name $rootScopeProvider#digestTtl
27130  * @description
27131  *
27132  * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
27133  * assuming that the model is unstable.
27134  *
27135  * The current default is 10 iterations.
27136  *
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.
27141  *
27142  * Increasing the TTL could have performance implications, so you should not change it without
27143  * proper justification.
27144  *
27145  * @param {number} limit The number of digest iterations.
27146  */
27147
27148
27149 /**
27150  * @ngdoc service
27151  * @name $rootScope
27152  * @this
27153  *
27154  * @description
27155  *
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}.
27161  */
27162 function $RootScopeProvider() {
27163   var TTL = 10;
27164   var $rootScopeMinErr = minErr('$rootScope');
27165   var lastDirtyWatch = null;
27166   var applyAsyncId = null;
27167
27168   this.digestTtl = function(value) {
27169     if (arguments.length) {
27170       TTL = value;
27171     }
27172     return TTL;
27173   };
27174
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;
27184     }
27185     ChildScope.prototype = parent;
27186     return ChildScope;
27187   }
27188
27189   this.$get = ['$exceptionHandler', '$parse', '$browser',
27190       function($exceptionHandler, $parse, $browser) {
27191
27192     function destroyChildScope($event) {
27193         $event.currentScope.$$destroyed = true;
27194     }
27195
27196     function cleanUpScope($scope) {
27197
27198       if (msie === 9) {
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
27202         //
27203         // See issue https://github.com/angular/angular.js/issues/10706
27204         if ($scope.$$childHead) {
27205           cleanUpScope($scope.$$childHead);
27206         }
27207         if ($scope.$$nextSibling) {
27208           cleanUpScope($scope.$$nextSibling);
27209         }
27210       }
27211
27212       // The code below works around IE9 and V8's memory leaks
27213       //
27214       // See:
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
27218
27219       $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
27220           $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
27221     }
27222
27223     /**
27224      * @ngdoc type
27225      * @name $rootScope.Scope
27226      *
27227      * @description
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.
27233      *
27234      *
27235      * # Inheritance
27236      * A scope can inherit from a parent scope, as in this example:
27237      * ```js
27238          var parent = $rootScope;
27239          var child = parent.$new();
27240
27241          parent.salutation = "Hello";
27242          expect(child.salutation).toEqual('Hello');
27243
27244          child.salutation = "Welcome";
27245          expect(child.salutation).toEqual('Welcome');
27246          expect(parent.salutation).toEqual('Hello');
27247      * ```
27248      *
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
27251      * details.
27252      *
27253      *
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
27259      *                              service.
27260      * @returns {Object} Newly created scope.
27261      *
27262      */
27263     function Scope() {
27264       this.$id = nextUid();
27265       this.$$phase = this.$parent = this.$$watchers =
27266                      this.$$nextSibling = this.$$prevSibling =
27267                      this.$$childHead = this.$$childTail = null;
27268       this.$root = this;
27269       this.$$destroyed = false;
27270       this.$$listeners = {};
27271       this.$$listenerCount = {};
27272       this.$$watchersCount = 0;
27273       this.$$isolateBindings = null;
27274     }
27275
27276     /**
27277      * @ngdoc property
27278      * @name $rootScope.Scope#$id
27279      *
27280      * @description
27281      * Unique scope ID (monotonically increasing) useful for debugging.
27282      */
27283
27284      /**
27285       * @ngdoc property
27286       * @name $rootScope.Scope#$parent
27287       *
27288       * @description
27289       * Reference to the parent scope.
27290       */
27291
27292       /**
27293        * @ngdoc property
27294        * @name $rootScope.Scope#$root
27295        *
27296        * @description
27297        * Reference to the root scope.
27298        */
27299
27300     Scope.prototype = {
27301       constructor: Scope,
27302       /**
27303        * @ngdoc method
27304        * @name $rootScope.Scope#$new
27305        * @kind function
27306        *
27307        * @description
27308        * Creates a new child {@link ng.$rootScope.Scope scope}.
27309        *
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()}.
27312        *
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.
27316        *
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
27320        *         state.
27321        *
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
27326        *                              inheritance.
27327        *
27328        * @returns {Object} The newly created child scope.
27329        *
27330        */
27331       $new: function(isolate, parent) {
27332         var child;
27333
27334         parent = parent || this;
27335
27336         if (isolate) {
27337           child = new Scope();
27338           child.$root = this.$root;
27339         } else {
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);
27344           }
27345           child = new this.$$ChildScope();
27346         }
27347         child.$parent = parent;
27348         child.$$prevSibling = parent.$$childTail;
27349         if (parent.$$childHead) {
27350           parent.$$childTail.$$nextSibling = child;
27351           parent.$$childTail = child;
27352         } else {
27353           parent.$$childHead = parent.$$childTail = child;
27354         }
27355
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);
27362
27363         return child;
27364       },
27365
27366       /**
27367        * @ngdoc method
27368        * @name $rootScope.Scope#$watch
27369        * @kind function
27370        *
27371        * @description
27372        * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
27373        *
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`
27384        *   (see next point)
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.
27392        *
27393        *
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.)
27398        *
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.
27405        *
27406        *
27407        *
27408        * # Example
27409        * ```js
27410            // let's assume that scope was dependency injected as the $rootScope
27411            var scope = $rootScope;
27412            scope.name = 'misko';
27413            scope.counter = 0;
27414
27415            expect(scope.counter).toEqual(0);
27416            scope.$watch('name', function(newValue, oldValue) {
27417              scope.counter = scope.counter + 1;
27418            });
27419            expect(scope.counter).toEqual(0);
27420
27421            scope.$digest();
27422            // the listener is always called during the first $digest loop after it was registered
27423            expect(scope.counter).toEqual(1);
27424
27425            scope.$digest();
27426            // but now it will not be called unless the value changes
27427            expect(scope.counter).toEqual(1);
27428
27429            scope.name = 'adam';
27430            scope.$digest();
27431            expect(scope.counter).toEqual(2);
27432
27433
27434
27435            // Using a function as a watchExpression
27436            var food;
27437            scope.foodCounter = 0;
27438            expect(scope.foodCounter).toEqual(0);
27439            scope.$watch(
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;
27447                }
27448              }
27449            );
27450            // No digest has been run so the counter will be zero
27451            expect(scope.foodCounter).toEqual(0);
27452
27453            // Run the digest but since food has not changed count will still be zero
27454            scope.$digest();
27455            expect(scope.foodCounter).toEqual(0);
27456
27457            // Update food and run digest.  Now the counter will increment
27458            food = 'cheeseburger';
27459            scope.$digest();
27460            expect(scope.foodCounter).toEqual(1);
27461
27462        * ```
27463        *
27464        *
27465        *
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`.
27469        *
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.
27474        *
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.
27481        */
27482       $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
27483         var get = $parse(watchExp);
27484
27485         if (get.$$watchDelegate) {
27486           return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
27487         }
27488         var scope = this,
27489             array = scope.$$watchers,
27490             watcher = {
27491               fn: listener,
27492               last: initWatchVal,
27493               get: get,
27494               exp: prettyPrintExpression || watchExp,
27495               eq: !!objectEquality
27496             };
27497
27498         lastDirtyWatch = null;
27499
27500         if (!isFunction(listener)) {
27501           watcher.fn = noop;
27502         }
27503
27504         if (!array) {
27505           array = scope.$$watchers = [];
27506           array.$$digestWatchIndex = -1;
27507         }
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);
27513
27514         return function deregisterWatch() {
27515           var index = arrayRemove(array, watcher);
27516           if (index >= 0) {
27517             incrementWatchersCount(scope, -1);
27518             if (index < array.$$digestWatchIndex) {
27519               array.$$digestWatchIndex--;
27520             }
27521           }
27522           lastDirtyWatch = null;
27523         };
27524       },
27525
27526       /**
27527        * @ngdoc method
27528        * @name $rootScope.Scope#$watchGroup
27529        * @kind function
27530        *
27531        * @description
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.
27534        *
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.
27538        *
27539        * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
27540        * watched using {@link ng.$rootScope.Scope#$watch $watch()}
27541        *
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.
27550        */
27551       $watchGroup: function(watchExpressions, listener) {
27552         var oldValues = new Array(watchExpressions.length);
27553         var newValues = new Array(watchExpressions.length);
27554         var deregisterFns = [];
27555         var self = this;
27556         var changeReactionScheduled = false;
27557         var firstRun = true;
27558
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);
27564           });
27565           return function deregisterWatchGroup() {
27566             shouldCall = false;
27567           };
27568         }
27569
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);
27576           });
27577         }
27578
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);
27586             }
27587           });
27588           deregisterFns.push(unwatchFn);
27589         });
27590
27591         function watchGroupAction() {
27592           changeReactionScheduled = false;
27593
27594           if (firstRun) {
27595             firstRun = false;
27596             listener(newValues, newValues, self);
27597           } else {
27598             listener(newValues, oldValues, self);
27599           }
27600         }
27601
27602         return function deregisterWatchGroup() {
27603           while (deregisterFns.length) {
27604             deregisterFns.shift()();
27605           }
27606         };
27607       },
27608
27609
27610       /**
27611        * @ngdoc method
27612        * @name $rootScope.Scope#$watchCollection
27613        * @kind function
27614        *
27615        * @description
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.
27619        *
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.
27624        *
27625        *
27626        * # Example
27627        * ```js
27628           $scope.names = ['igor', 'matias', 'misko', 'james'];
27629           $scope.dataCount = 4;
27630
27631           $scope.$watchCollection('names', function(newNames, oldNames) {
27632             $scope.dataCount = newNames.length;
27633           });
27634
27635           expect($scope.dataCount).toEqual(4);
27636           $scope.$digest();
27637
27638           //still at 4 ... no changes
27639           expect($scope.dataCount).toEqual(4);
27640
27641           $scope.names.pop();
27642           $scope.$digest();
27643
27644           //now there's been a change
27645           expect($scope.dataCount).toEqual(3);
27646        * ```
27647        *
27648        *
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`.
27653        *
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.
27661        *
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.
27664        */
27665       $watchCollection: function(obj, listener) {
27666         $watchCollectionInterceptor.$stateful = true;
27667
27668         var self = this;
27669         // the current value, updated on each dirty-check run
27670         var newValue;
27671         // a shallow copy of the newValue from the last dirty-check run,
27672         // updated to match newValue during dirty-check run
27673         var oldValue;
27674         // a shallow copy of the newValue from when the last change happened
27675         var veryOldValue;
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;
27683         var oldLength = 0;
27684
27685         function $watchCollectionInterceptor(_value) {
27686           newValue = _value;
27687           var newLength, key, bothNaN, newItem, oldItem;
27688
27689           // If the new value is undefined, then return undefined as the watch may be a one-time watch
27690           if (isUndefined(newValue)) return;
27691
27692           if (!isObject(newValue)) { // if primitive
27693             if (oldValue !== newValue) {
27694               oldValue = newValue;
27695               changeDetected++;
27696             }
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;
27702               changeDetected++;
27703             }
27704
27705             newLength = newValue.length;
27706
27707             if (oldLength !== newLength) {
27708               // if lengths do not match we need to trigger change notification
27709               changeDetected++;
27710               oldValue.length = oldLength = newLength;
27711             }
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];
27716
27717               // eslint-disable-next-line no-self-compare
27718               bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
27719               if (!bothNaN && (oldItem !== newItem)) {
27720                 changeDetected++;
27721                 oldValue[i] = newItem;
27722               }
27723             }
27724           } else {
27725             if (oldValue !== internalObject) {
27726               // we are transitioning from something which was not an object into object.
27727               oldValue = internalObject = {};
27728               oldLength = 0;
27729               changeDetected++;
27730             }
27731             // copy the items to oldValue and look for changes.
27732             newLength = 0;
27733             for (key in newValue) {
27734               if (hasOwnProperty.call(newValue, key)) {
27735                 newLength++;
27736                 newItem = newValue[key];
27737                 oldItem = oldValue[key];
27738
27739                 if (key in oldValue) {
27740                   // eslint-disable-next-line no-self-compare
27741                   bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
27742                   if (!bothNaN && (oldItem !== newItem)) {
27743                     changeDetected++;
27744                     oldValue[key] = newItem;
27745                   }
27746                 } else {
27747                   oldLength++;
27748                   oldValue[key] = newItem;
27749                   changeDetected++;
27750                 }
27751               }
27752             }
27753             if (oldLength > newLength) {
27754               // we used to have more keys, need to find them and destroy them.
27755               changeDetected++;
27756               for (key in oldValue) {
27757                 if (!hasOwnProperty.call(newValue, key)) {
27758                   oldLength--;
27759                   delete oldValue[key];
27760                 }
27761               }
27762             }
27763           }
27764           return changeDetected;
27765         }
27766
27767         function $watchCollectionAction() {
27768           if (initRun) {
27769             initRun = false;
27770             listener(newValue, newValue, self);
27771           } else {
27772             listener(newValue, veryOldValue, self);
27773           }
27774
27775           // make a copy for the next time a collection is changed
27776           if (trackVeryOldValue) {
27777             if (!isObject(newValue)) {
27778               //primitive
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];
27784               }
27785             } else { // if object
27786               veryOldValue = {};
27787               for (var key in newValue) {
27788                 if (hasOwnProperty.call(newValue, key)) {
27789                   veryOldValue[key] = newValue[key];
27790                 }
27791               }
27792             }
27793           }
27794         }
27795
27796         return this.$watch(changeDetector, $watchCollectionAction);
27797       },
27798
27799       /**
27800        * @ngdoc method
27801        * @name $rootScope.Scope#$digest
27802        * @kind function
27803        *
27804        * @description
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.
27811        *
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()`.
27817        *
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`.
27821        *
27822        * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
27823        *
27824        * # Example
27825        * ```js
27826            var scope = ...;
27827            scope.name = 'misko';
27828            scope.counter = 0;
27829
27830            expect(scope.counter).toEqual(0);
27831            scope.$watch('name', function(newValue, oldValue) {
27832              scope.counter = scope.counter + 1;
27833            });
27834            expect(scope.counter).toEqual(0);
27835
27836            scope.$digest();
27837            // the listener is always called during the first $digest loop after it was registered
27838            expect(scope.counter).toEqual(1);
27839
27840            scope.$digest();
27841            // but now it will not be called unless the value changes
27842            expect(scope.counter).toEqual(1);
27843
27844            scope.name = 'adam';
27845            scope.$digest();
27846            expect(scope.counter).toEqual(2);
27847        * ```
27848        *
27849        */
27850       $digest: function() {
27851         var watch, value, last, fn, get,
27852             watchers,
27853             dirty, ttl = TTL,
27854             next, current, target = this,
27855             watchLog = [],
27856             logIdx, asyncTask;
27857
27858         beginPhase('$digest');
27859         // Check for changes to browser url that happened in sync before the call to $digest
27860         $browser.$$checkUrlChange();
27861
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);
27866           flushApplyAsync();
27867         }
27868
27869         lastDirtyWatch = null;
27870
27871         do { // "while dirty" loop
27872           dirty = false;
27873           current = target;
27874
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++) {
27879             try {
27880               asyncTask = asyncQueue[asyncQueuePosition];
27881               asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
27882             } catch (e) {
27883               $exceptionHandler(e);
27884             }
27885             lastDirtyWatch = null;
27886           }
27887           asyncQueue.length = 0;
27888
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--) {
27895                 try {
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
27899                   if (watch) {
27900                     get = watch.get;
27901                     if ((value = get(current)) !== (last = watch.last) &&
27902                         !(watch.eq
27903                             ? equals(value, last)
27904                             : (isNumberNaN(value) && isNumberNaN(last)))) {
27905                       dirty = true;
27906                       lastDirtyWatch = watch;
27907                       watch.last = watch.eq ? copy(value, null) : value;
27908                       fn = watch.fn;
27909                       fn(value, ((last === initWatchVal) ? value : last), current);
27910                       if (ttl < 5) {
27911                         logIdx = 4 - ttl;
27912                         if (!watchLog[logIdx]) watchLog[logIdx] = [];
27913                         watchLog[logIdx].push({
27914                           msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
27915                           newVal: value,
27916                           oldVal: last
27917                         });
27918                       }
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.
27922                       dirty = false;
27923                       break traverseScopesLoop;
27924                     }
27925                   }
27926                 } catch (e) {
27927                   $exceptionHandler(e);
27928                 }
27929               }
27930             }
27931
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;
27939               }
27940             }
27941           } while ((current = next));
27942
27943           // `break traverseScopesLoop;` takes us to here
27944
27945           if ((dirty || asyncQueue.length) && !(ttl--)) {
27946             clearPhase();
27947             throw $rootScopeMinErr('infdig',
27948                 '{0} $digest() iterations reached. Aborting!\n' +
27949                 'Watchers fired in the last 5 iterations: {1}',
27950                 TTL, watchLog);
27951           }
27952
27953         } while (dirty || asyncQueue.length);
27954
27955         clearPhase();
27956
27957         // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
27958         while (postDigestQueuePosition < postDigestQueue.length) {
27959           try {
27960             postDigestQueue[postDigestQueuePosition++]();
27961           } catch (e) {
27962             $exceptionHandler(e);
27963           }
27964         }
27965         postDigestQueue.length = postDigestQueuePosition = 0;
27966       },
27967
27968
27969       /**
27970        * @ngdoc event
27971        * @name $rootScope.Scope#$destroy
27972        * @eventType broadcast on scope being destroyed
27973        *
27974        * @description
27975        * Broadcasted when a scope and its children are being destroyed.
27976        *
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.
27979        */
27980
27981       /**
27982        * @ngdoc method
27983        * @name $rootScope.Scope#$destroy
27984        * @kind function
27985        *
27986        * @description
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.
27991        *
27992        * The `$destroy()` is usually used by directives such as
27993        * {@link ng.directive:ngRepeat ngRepeat} for managing the
27994        * unrolling of the loop.
27995        *
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.
27999        *
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.
28002        */
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;
28007
28008         this.$broadcast('$destroy');
28009         this.$$destroyed = true;
28010
28011         if (this === $rootScope) {
28012           //Remove handlers attached to window when $rootScope is removed
28013           $browser.$$applicationDestroyed();
28014         }
28015
28016         incrementWatchersCount(this, -this.$$watchersCount);
28017         for (var eventName in this.$$listenerCount) {
28018           decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
28019         }
28020
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;
28027
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 = {};
28032
28033         // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
28034         this.$$nextSibling = null;
28035         cleanUpScope(this);
28036       },
28037
28038       /**
28039        * @ngdoc method
28040        * @name $rootScope.Scope#$eval
28041        * @kind function
28042        *
28043        * @description
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
28046        * expressions.
28047        *
28048        * # Example
28049        * ```js
28050            var scope = ng.$rootScope.Scope();
28051            scope.a = 1;
28052            scope.b = 2;
28053
28054            expect(scope.$eval('a+b')).toEqual(3);
28055            expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
28056        * ```
28057        *
28058        * @param {(string|function())=} expression An angular expression to be executed.
28059        *
28060        *    - `string`: execute using the rules as defined in  {@link guide/expression expression}.
28061        *    - `function(scope)`: execute the function with the current `scope` parameter.
28062        *
28063        * @param {(object)=} locals Local variables object, useful for overriding values in scope.
28064        * @returns {*} The result of evaluating the expression.
28065        */
28066       $eval: function(expr, locals) {
28067         return $parse(expr)(this, locals);
28068       },
28069
28070       /**
28071        * @ngdoc method
28072        * @name $rootScope.Scope#$evalAsync
28073        * @kind function
28074        *
28075        * @description
28076        * Executes the expression on the current scope at a later point in time.
28077        *
28078        * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
28079        * that:
28080        *
28081        *   - it will execute after the function that scheduled the evaluation (preferably before DOM
28082        *     rendering).
28083        *   - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
28084        *     `expression` execution.
28085        *
28086        * Any exceptions from the execution of the expression are forwarded to the
28087        * {@link ng.$exceptionHandler $exceptionHandler} service.
28088        *
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`.
28092        *
28093        * @param {(string|function())=} expression An angular expression to be executed.
28094        *
28095        *    - `string`: execute using the rules as defined in {@link guide/expression expression}.
28096        *    - `function(scope)`: execute the function with the current `scope` parameter.
28097        *
28098        * @param {(object)=} locals Local variables object, useful for overriding values in scope.
28099        */
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();
28107             }
28108           });
28109         }
28110
28111         asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});
28112       },
28113
28114       $$postDigest: function(fn) {
28115         postDigestQueue.push(fn);
28116       },
28117
28118       /**
28119        * @ngdoc method
28120        * @name $rootScope.Scope#$apply
28121        * @kind function
28122        *
28123        * @description
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}.
28129        *
28130        * ## Life cycle
28131        *
28132        * # Pseudo-Code of `$apply()`
28133        * ```js
28134            function $apply(expr) {
28135              try {
28136                return $eval(expr);
28137              } catch (e) {
28138                $exceptionHandler(e);
28139              } finally {
28140                $root.$digest();
28141              }
28142            }
28143        * ```
28144        *
28145        *
28146        * Scope's `$apply()` method transitions through the following stages:
28147        *
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.
28154        *
28155        *
28156        * @param {(string|function())=} exp An angular expression to be executed.
28157        *
28158        *    - `string`: execute using the rules as defined in {@link guide/expression expression}.
28159        *    - `function(scope)`: execute the function with current `scope` parameter.
28160        *
28161        * @returns {*} The result of evaluating the expression.
28162        */
28163       $apply: function(expr) {
28164         try {
28165           beginPhase('$apply');
28166           try {
28167             return this.$eval(expr);
28168           } finally {
28169             clearPhase();
28170           }
28171         } catch (e) {
28172           $exceptionHandler(e);
28173         } finally {
28174           try {
28175             $rootScope.$digest();
28176           } catch (e) {
28177             $exceptionHandler(e);
28178             // eslint-disable-next-line no-unsafe-finally
28179             throw e;
28180           }
28181         }
28182       },
28183
28184       /**
28185        * @ngdoc method
28186        * @name $rootScope.Scope#$applyAsync
28187        * @kind function
28188        *
28189        * @description
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.
28192        *
28193        * This can be used to queue up multiple expressions which need to be evaluated in the same
28194        * digest.
28195        *
28196        * @param {(string|function())=} exp An angular expression to be executed.
28197        *
28198        *    - `string`: execute using the rules as defined in {@link guide/expression expression}.
28199        *    - `function(scope)`: execute the function with current `scope` parameter.
28200        */
28201       $applyAsync: function(expr) {
28202         var scope = this;
28203         if (expr) {
28204           applyAsyncQueue.push($applyAsyncExpression);
28205         }
28206         expr = $parse(expr);
28207         scheduleApplyAsync();
28208
28209         function $applyAsyncExpression() {
28210           scope.$eval(expr);
28211         }
28212       },
28213
28214       /**
28215        * @ngdoc method
28216        * @name $rootScope.Scope#$on
28217        * @kind function
28218        *
28219        * @description
28220        * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
28221        * discussion of event life cycle.
28222        *
28223        * The event listener function format is: `function(event, args...)`. The `event` object
28224        * passed into the listener has the following attributes:
28225        *
28226        *   - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
28227        *     `$broadcast`-ed.
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
28234        *     to true.
28235        *   - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
28236        *
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.
28240        */
28241       $on: function(name, listener) {
28242         var namedListeners = this.$$listeners[name];
28243         if (!namedListeners) {
28244           this.$$listeners[name] = namedListeners = [];
28245         }
28246         namedListeners.push(listener);
28247
28248         var current = this;
28249         do {
28250           if (!current.$$listenerCount[name]) {
28251             current.$$listenerCount[name] = 0;
28252           }
28253           current.$$listenerCount[name]++;
28254         } while ((current = current.$parent));
28255
28256         var self = this;
28257         return function() {
28258           var indexOfListener = namedListeners.indexOf(listener);
28259           if (indexOfListener !== -1) {
28260             namedListeners[indexOfListener] = null;
28261             decrementListenerCount(self, 1, name);
28262           }
28263         };
28264       },
28265
28266
28267       /**
28268        * @ngdoc method
28269        * @name $rootScope.Scope#$emit
28270        * @kind function
28271        *
28272        * @description
28273        * Dispatches an event `name` upwards through the scope hierarchy notifying the
28274        * registered {@link ng.$rootScope.Scope#$on} listeners.
28275        *
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
28280        * cancels it.
28281        *
28282        * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
28283        * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
28284        *
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}).
28288        */
28289       $emit: function(name, args) {
28290         var empty = [],
28291             namedListeners,
28292             scope = this,
28293             stopPropagation = false,
28294             event = {
28295               name: name,
28296               targetScope: scope,
28297               stopPropagation: function() {stopPropagation = true;},
28298               preventDefault: function() {
28299                 event.defaultPrevented = true;
28300               },
28301               defaultPrevented: false
28302             },
28303             listenerArgs = concat([event], arguments, 1),
28304             i, length;
28305
28306         do {
28307           namedListeners = scope.$$listeners[name] || empty;
28308           event.currentScope = scope;
28309           for (i = 0, length = namedListeners.length; i < length; i++) {
28310
28311             // if listeners were deregistered, defragment the array
28312             if (!namedListeners[i]) {
28313               namedListeners.splice(i, 1);
28314               i--;
28315               length--;
28316               continue;
28317             }
28318             try {
28319               //allow all listeners attached to the current scope to run
28320               namedListeners[i].apply(null, listenerArgs);
28321             } catch (e) {
28322               $exceptionHandler(e);
28323             }
28324           }
28325           //if any listener on the current scope stops propagation, prevent bubbling
28326           if (stopPropagation) {
28327             event.currentScope = null;
28328             return event;
28329           }
28330           //traverse upwards
28331           scope = scope.$parent;
28332         } while (scope);
28333
28334         event.currentScope = null;
28335
28336         return event;
28337       },
28338
28339
28340       /**
28341        * @ngdoc method
28342        * @name $rootScope.Scope#$broadcast
28343        * @kind function
28344        *
28345        * @description
28346        * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
28347        * registered {@link ng.$rootScope.Scope#$on} listeners.
28348        *
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.
28353        *
28354        * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
28355        * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
28356        *
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}
28360        */
28361       $broadcast: function(name, args) {
28362         var target = this,
28363             current = target,
28364             next = target,
28365             event = {
28366               name: name,
28367               targetScope: target,
28368               preventDefault: function() {
28369                 event.defaultPrevented = true;
28370               },
28371               defaultPrevented: false
28372             };
28373
28374         if (!target.$$listenerCount[name]) return event;
28375
28376         var listenerArgs = concat([event], arguments, 1),
28377             listeners, i, length;
28378
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);
28387               i--;
28388               length--;
28389               continue;
28390             }
28391
28392             try {
28393               listeners[i].apply(null, listenerArgs);
28394             } catch (e) {
28395               $exceptionHandler(e);
28396             }
28397           }
28398
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;
28407             }
28408           }
28409         }
28410
28411         event.currentScope = null;
28412         return event;
28413       }
28414     };
28415
28416     var $rootScope = new Scope();
28417
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 = [];
28422
28423     var postDigestQueuePosition = 0;
28424
28425     return $rootScope;
28426
28427
28428     function beginPhase(phase) {
28429       if ($rootScope.$$phase) {
28430         throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
28431       }
28432
28433       $rootScope.$$phase = phase;
28434     }
28435
28436     function clearPhase() {
28437       $rootScope.$$phase = null;
28438     }
28439
28440     function incrementWatchersCount(current, count) {
28441       do {
28442         current.$$watchersCount += count;
28443       } while ((current = current.$parent));
28444     }
28445
28446     function decrementListenerCount(current, count, name) {
28447       do {
28448         current.$$listenerCount[name] -= count;
28449
28450         if (current.$$listenerCount[name] === 0) {
28451           delete current.$$listenerCount[name];
28452         }
28453       } while ((current = current.$parent));
28454     }
28455
28456     /**
28457      * function used as an initial value for watchers.
28458      * because it's unique we can easily tell it apart from other values
28459      */
28460     function initWatchVal() {}
28461
28462     function flushApplyAsync() {
28463       while (applyAsyncQueue.length) {
28464         try {
28465           applyAsyncQueue.shift()();
28466         } catch (e) {
28467           $exceptionHandler(e);
28468         }
28469       }
28470       applyAsyncId = null;
28471     }
28472
28473     function scheduleApplyAsync() {
28474       if (applyAsyncId === null) {
28475         applyAsyncId = $browser.defer(function() {
28476           $rootScope.$apply(flushApplyAsync);
28477         });
28478       }
28479     }
28480   }];
28481 }
28482
28483 /**
28484  * @ngdoc service
28485  * @name $rootElement
28486  *
28487  * @description
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()`.
28493  */
28494
28495
28496 // the implementation is in angular.bootstrap
28497
28498 /**
28499  * @this
28500  * @description
28501  * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
28502  */
28503 function $$SanitizeUriProvider() {
28504   var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
28505     imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
28506
28507   /**
28508    * @description
28509    * Retrieves or overrides the default regular expression that is used for whitelisting of safe
28510    * urls during a[href] sanitization.
28511    *
28512    * The sanitization is a security measure aimed at prevent XSS attacks via html links.
28513    *
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.
28518    *
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.
28522    */
28523   this.aHrefSanitizationWhitelist = function(regexp) {
28524     if (isDefined(regexp)) {
28525       aHrefSanitizationWhitelist = regexp;
28526       return this;
28527     }
28528     return aHrefSanitizationWhitelist;
28529   };
28530
28531
28532   /**
28533    * @description
28534    * Retrieves or overrides the default regular expression that is used for whitelisting of safe
28535    * urls during img[src] sanitization.
28536    *
28537    * The sanitization is a security measure aimed at prevent XSS attacks via html links.
28538    *
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.
28543    *
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.
28547    */
28548   this.imgSrcSanitizationWhitelist = function(regexp) {
28549     if (isDefined(regexp)) {
28550       imgSrcSanitizationWhitelist = regexp;
28551       return this;
28552     }
28553     return imgSrcSanitizationWhitelist;
28554   };
28555
28556   this.$get = function() {
28557     return function sanitizeUri(uri, isImage) {
28558       var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
28559       var normalizedVal;
28560       normalizedVal = urlResolve(uri).href;
28561       if (normalizedVal !== '' && !normalizedVal.match(regex)) {
28562         return 'unsafe:' + normalizedVal;
28563       }
28564       return uri;
28565     };
28566   };
28567 }
28568
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.                          *
28574  *                                                                         *
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  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
28579
28580 /* exported $SceProvider, $SceDelegateProvider */
28581
28582 var $sceMinErr = minErr('$sce');
28583
28584 var SCE_CONTEXTS = {
28585   HTML: 'html',
28586   CSS: 'css',
28587   URL: 'url',
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',
28591   JS: 'js'
28592 };
28593
28594 // Helper functions follow.
28595
28596 function adjustMatcher(matcher) {
28597   if (matcher === 'self') {
28598     return matcher;
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);
28607     }
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 + '$');
28617   } else {
28618     throw $sceMinErr('imatcher',
28619         'Matchers may only be "self", string patterns or RegExp objects');
28620   }
28621 }
28622
28623
28624 function adjustMatchers(matchers) {
28625   var adjustedMatchers = [];
28626   if (isDefined(matchers)) {
28627     forEach(matchers, function(matcher) {
28628       adjustedMatchers.push(adjustMatcher(matcher));
28629     });
28630   }
28631   return adjustedMatchers;
28632 }
28633
28634
28635 /**
28636  * @ngdoc service
28637  * @name $sceDelegate
28638  * @kind function
28639  *
28640  * @description
28641  *
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.
28644  *
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.
28650  *
28651  * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
28652  *
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}
28660  */
28661
28662 /**
28663  * @ngdoc provider
28664  * @name $sceDelegateProvider
28665  * @this
28666  *
28667  * @description
28668  *
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}
28674  *
28675  * For the general details about this service in Angular, read the main page for {@link ng.$sce
28676  * Strict Contextual Escaping (SCE)}.
28677  *
28678  * **Example**:  Consider the following case. <a name="example"></a>
28679  *
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?...`.
28684  *
28685  * Here is what a secure configuration for this scenario might look like:
28686  *
28687  * ```
28688  *  angular.module('myApp', []).config(function($sceDelegateProvider) {
28689  *    $sceDelegateProvider.resourceUrlWhitelist([
28690  *      // Allow same origin resource loads.
28691  *      'self',
28692  *      // Allow loading from our assets domain.  Notice the difference between * and **.
28693  *      'http://srv*.assets.example.com/**'
28694  *    ]);
28695  *
28696  *    // The blacklist overrides the whitelist so the open redirect here is blocked.
28697  *    $sceDelegateProvider.resourceUrlBlacklist([
28698  *      'http://myapp.example.com/clickThru**'
28699  *    ]);
28700  *  });
28701  * ```
28702  */
28703
28704 function $SceDelegateProvider() {
28705   this.SCE_CONTEXTS = SCE_CONTEXTS;
28706
28707   // Resource URLs can also be trusted by policy.
28708   var resourceUrlWhitelist = ['self'],
28709       resourceUrlBlacklist = [];
28710
28711   /**
28712    * @ngdoc method
28713    * @name $sceDelegateProvider#resourceUrlWhitelist
28714    * @kind function
28715    *
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.
28719    *
28720    *    Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
28721    *    allowed in this array.
28722    *
28723    *    <div class="alert alert-warning">
28724    *    **Note:** an empty whitelist array will block all URLs!
28725    *    </div>
28726    *
28727    * @return {Array} the currently set whitelist array.
28728    *
28729    * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
28730    * same origin resource requests.
28731    *
28732    * @description
28733    * Sets/Gets the whitelist of trusted resource URLs.
28734    */
28735   this.resourceUrlWhitelist = function(value) {
28736     if (arguments.length) {
28737       resourceUrlWhitelist = adjustMatchers(value);
28738     }
28739     return resourceUrlWhitelist;
28740   };
28741
28742   /**
28743    * @ngdoc method
28744    * @name $sceDelegateProvider#resourceUrlBlacklist
28745    * @kind function
28746    *
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.
28750    *
28751    *    Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
28752    *    allowed in this array.
28753    *
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.
28757    *
28758    *    Finally, **the blacklist overrides the whitelist** and has the final say.
28759    *
28760    * @return {Array} the currently set blacklist array.
28761    *
28762    * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
28763    * is no blacklist.)
28764    *
28765    * @description
28766    * Sets/Gets the blacklist of trusted resource URLs.
28767    */
28768
28769   this.resourceUrlBlacklist = function(value) {
28770     if (arguments.length) {
28771       resourceUrlBlacklist = adjustMatchers(value);
28772     }
28773     return resourceUrlBlacklist;
28774   };
28775
28776   this.$get = ['$injector', function($injector) {
28777
28778     var htmlSanitizer = function htmlSanitizer(html) {
28779       throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
28780     };
28781
28782     if ($injector.has('$sanitize')) {
28783       htmlSanitizer = $injector.get('$sanitize');
28784     }
28785
28786
28787     function matchUrl(matcher, parsedUrl) {
28788       if (matcher === 'self') {
28789         return urlIsSameOrigin(parsedUrl);
28790       } else {
28791         // definitely a regex.  See adjustMatchers()
28792         return !!matcher.exec(parsedUrl.href);
28793       }
28794     }
28795
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)) {
28802           allowed = true;
28803           break;
28804         }
28805       }
28806       if (allowed) {
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)) {
28810             allowed = false;
28811             break;
28812           }
28813         }
28814       }
28815       return allowed;
28816     }
28817
28818     function generateHolderType(Base) {
28819       var holderType = function TrustedValueHolderType(trustedValue) {
28820         this.$$unwrapTrustedValue = function() {
28821           return trustedValue;
28822         };
28823       };
28824       if (Base) {
28825         holderType.prototype = new Base();
28826       }
28827       holderType.prototype.valueOf = function sceValueOf() {
28828         return this.$$unwrapTrustedValue();
28829       };
28830       holderType.prototype.toString = function sceToString() {
28831         return this.$$unwrapTrustedValue().toString();
28832       };
28833       return holderType;
28834     }
28835
28836     var trustedValueHolderBase = generateHolderType(),
28837         byType = {};
28838
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]);
28844
28845     /**
28846      * @ngdoc method
28847      * @name $sceDelegate#trustAs
28848      *
28849      * @description
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.
28855      *
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.
28861      */
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);
28868       }
28869       if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
28870         return trustedValue;
28871       }
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}',
28877             type);
28878       }
28879       return new Constructor(trustedValue);
28880     }
28881
28882     /**
28883      * @ngdoc method
28884      * @name $sceDelegate#valueOf
28885      *
28886      * @description
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`}.
28890      *
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.
28893      *
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.
28899      */
28900     function valueOf(maybeTrusted) {
28901       if (maybeTrusted instanceof trustedValueHolderBase) {
28902         return maybeTrusted.$$unwrapTrustedValue();
28903       } else {
28904         return maybeTrusted;
28905       }
28906     }
28907
28908     /**
28909      * @ngdoc method
28910      * @name $sceDelegate#getTrusted
28911      *
28912      * @description
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.
28916      *
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.
28920      * </div>
28921      *
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.
28927      */
28928     function getTrusted(type, maybeTrusted) {
28929       if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
28930         return maybeTrusted;
28931       }
28932       var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
28933       if (constructor && maybeTrusted instanceof constructor) {
28934         return maybeTrusted.$$unwrapTrustedValue();
28935       }
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;
28942         } else {
28943           throw $sceMinErr('insecurl',
28944               'Blocked loading resource from url not allowed by $sceDelegate policy.  URL: {0}',
28945               maybeTrusted.toString());
28946         }
28947       } else if (type === SCE_CONTEXTS.HTML) {
28948         return htmlSanitizer(maybeTrusted);
28949       }
28950       throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
28951     }
28952
28953     return { trustAs: trustAs,
28954              getTrusted: getTrusted,
28955              valueOf: valueOf };
28956   }];
28957 }
28958
28959
28960 /**
28961  * @ngdoc provider
28962  * @name $sceProvider
28963  * @this
28964  *
28965  * @description
28966  *
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
28970  *
28971  * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
28972  */
28973
28974 /**
28975  * @ngdoc service
28976  * @name $sce
28977  * @kind function
28978  *
28979  * @description
28980  *
28981  * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
28982  *
28983  * # Strict Contextual Escaping
28984  *
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.
28989  *
28990  * As of version 1.2, Angular ships with SCE enabled by default.
28991  *
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.
28997  *
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.
29000  *
29001  * Here's an example of a binding in a privileged context:
29002  *
29003  * ```
29004  * <input ng-model="userHtml" aria-label="User input">
29005  * <div ng-bind-html="userHtml"></div>
29006  * ```
29007  *
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.)
29013  *
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.
29016  *
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?
29021  *
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.
29029  *
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.
29033  *
29034  *
29035  * ## How does it work?
29036  *
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.
29041  *
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
29044  * simplified):
29045  *
29046  * ```
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 || '');
29051  *     });
29052  *   };
29053  * }];
29054  * ```
29055  *
29056  * ## Impact on loading templates
29057  *
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}.
29060  *
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.
29066  *
29067  * *Please note*:
29068  * The browser's
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
29074  * browsers.
29075  *
29076  * ## This feels like too much overhead
29077  *
29078  * It's important to remember that SCE only applies to interpolation expressions.
29079  *
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.
29083  *
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.
29086  *
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.
29093  *
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.
29097  *
29098  * <a name="contexts"></a>
29099  * ## What trusted context types are supported?
29100  *
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. |
29108  *
29109  * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
29110  *
29111  *  Each element in these arrays must be one of the following:
29112  *
29113  *  - **'self'**
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
29123  *      in a whitelist.
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).
29153  *
29154  * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
29155  *
29156  * ## Show me an example using SCE.
29157  *
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
29165  *     exploit.
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>
29170  *         <br>
29171  *       </div>
29172  *     </div>
29173  *   </div>
29174  * </file>
29175  *
29176  * <file name="script.js">
29177  *   angular.module('mySceApp', ['ngSanitize'])
29178  *     .controller('AppController', ['$http', '$templateCache', '$sce',
29179  *       function AppController($http, $templateCache, $sce) {
29180  *         var self = this;
29181  *         $http.get('test_data.json', {cache: $templateCache}).success(function(userComments) {
29182  *           self.userComments = userComments;
29183  *         });
29184  *         self.explicitlyTrustedHtml = $sce.trustAsHtml(
29185  *             '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
29186  *             'sanitization.&quot;">Hover over this text.</span>');
29187  *       }]);
29188  * </file>
29189  *
29190  * <file name="test_data.json">
29191  * [
29192  *   { "name": "Alice",
29193  *     "htmlComment":
29194  *         "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
29195  *   },
29196  *   { "name": "Bob",
29197  *     "htmlComment": "<i>Yes!</i>  Am I the only other one?"
29198  *   }
29199  * ]
29200  * </file>
29201  *
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>');
29207  *     });
29208  *
29209  *     it('should NOT sanitize explicitly trusted values', function() {
29210  *       expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(
29211  *           '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
29212  *           'sanitization.&quot;">Hover over this text.</span>');
29213  *     });
29214  *   });
29215  * </file>
29216  * </example>
29217  *
29218  *
29219  *
29220  * ## Can I disable SCE completely?
29221  *
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.
29227  *
29228  * That said, here's how you can completely disable SCE:
29229  *
29230  * ```
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);
29235  * });
29236  * ```
29237  *
29238  */
29239
29240 function $SceProvider() {
29241   var enabled = true;
29242
29243   /**
29244    * @ngdoc method
29245    * @name $sceProvider#enabled
29246    * @kind function
29247    *
29248    * @param {boolean=} value If provided, then enables/disables SCE.
29249    * @return {boolean} true if SCE is enabled, false otherwise.
29250    *
29251    * @description
29252    * Enables/disables SCE and returns the current value.
29253    */
29254   this.enabled = function(value) {
29255     if (arguments.length) {
29256       enabled = !!value;
29257     }
29258     return enabled;
29259   };
29260
29261
29262   /* Design notes on the default implementation for SCE.
29263    *
29264    * The API contract for the SCE delegate
29265    * -------------------------------------
29266    * The SCE delegate object must provide the following 3 methods:
29267    *
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.
29272    *
29273    * - valueOf(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
29277    *     such a value.
29278    *
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.
29282    *
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.
29291    *
29292    *
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.
29297    *
29298    * The contract is simply this:
29299    *
29300    *     getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
29301    *     will also succeed.
29302    *
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.
29306    */
29307
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.');
29317     }
29318
29319     var sce = shallowCopy(SCE_CONTEXTS);
29320
29321     /**
29322      * @ngdoc method
29323      * @name $sce#isEnabled
29324      * @kind function
29325      *
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}.
29328      *
29329      * @description
29330      * Returns a boolean indicating if SCE is enabled.
29331      */
29332     sce.isEnabled = function() {
29333       return enabled;
29334     };
29335     sce.trustAs = $sceDelegate.trustAs;
29336     sce.getTrusted = $sceDelegate.getTrusted;
29337     sce.valueOf = $sceDelegate.valueOf;
29338
29339     if (!enabled) {
29340       sce.trustAs = sce.getTrusted = function(type, value) { return value; };
29341       sce.valueOf = identity;
29342     }
29343
29344     /**
29345      * @ngdoc method
29346      * @name $sce#parseAs
29347      *
29348      * @description
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*,
29352      * *result*)}
29353      *
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:
29357      *
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
29361      *      `context`.
29362      */
29363     sce.parseAs = function sceParseAs(type, expr) {
29364       var parsed = $parse(expr);
29365       if (parsed.literal && parsed.constant) {
29366         return parsed;
29367       } else {
29368         return $parse(expr, function(value) {
29369           return sce.getTrusted(type, value);
29370         });
29371       }
29372     };
29373
29374     /**
29375      * @ngdoc method
29376      * @name $sce#trustAs
29377      *
29378      * @description
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
29384      * escaping.
29385      *
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.
29391      */
29392
29393     /**
29394      * @ngdoc method
29395      * @name $sce#trustAsHtml
29396      *
29397      * @description
29398      * Shorthand method.  `$sce.trustAsHtml(value)` â†’
29399      *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
29400      *
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}.)
29406      */
29407
29408     /**
29409      * @ngdoc method
29410      * @name $sce#trustAsUrl
29411      *
29412      * @description
29413      * Shorthand method.  `$sce.trustAsUrl(value)` â†’
29414      *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
29415      *
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}.)
29421      */
29422
29423     /**
29424      * @ngdoc method
29425      * @name $sce#trustAsResourceUrl
29426      *
29427      * @description
29428      * Shorthand method.  `$sce.trustAsResourceUrl(value)` â†’
29429      *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
29430      *
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}.)
29436      */
29437
29438     /**
29439      * @ngdoc method
29440      * @name $sce#trustAsJs
29441      *
29442      * @description
29443      * Shorthand method.  `$sce.trustAsJs(value)` â†’
29444      *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
29445      *
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}.)
29451      */
29452
29453     /**
29454      * @ngdoc method
29455      * @name $sce#getTrusted
29456      *
29457      * @description
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.
29462      *
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`}
29465      *                         call.
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.
29469      */
29470
29471     /**
29472      * @ngdoc method
29473      * @name $sce#getTrustedHtml
29474      *
29475      * @description
29476      * Shorthand method.  `$sce.getTrustedHtml(value)` â†’
29477      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
29478      *
29479      * @param {*} value The value to pass to `$sce.getTrusted`.
29480      * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
29481      */
29482
29483     /**
29484      * @ngdoc method
29485      * @name $sce#getTrustedCss
29486      *
29487      * @description
29488      * Shorthand method.  `$sce.getTrustedCss(value)` â†’
29489      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
29490      *
29491      * @param {*} value The value to pass to `$sce.getTrusted`.
29492      * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
29493      */
29494
29495     /**
29496      * @ngdoc method
29497      * @name $sce#getTrustedUrl
29498      *
29499      * @description
29500      * Shorthand method.  `$sce.getTrustedUrl(value)` â†’
29501      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
29502      *
29503      * @param {*} value The value to pass to `$sce.getTrusted`.
29504      * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
29505      */
29506
29507     /**
29508      * @ngdoc method
29509      * @name $sce#getTrustedResourceUrl
29510      *
29511      * @description
29512      * Shorthand method.  `$sce.getTrustedResourceUrl(value)` â†’
29513      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
29514      *
29515      * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
29516      * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
29517      */
29518
29519     /**
29520      * @ngdoc method
29521      * @name $sce#getTrustedJs
29522      *
29523      * @description
29524      * Shorthand method.  `$sce.getTrustedJs(value)` â†’
29525      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
29526      *
29527      * @param {*} value The value to pass to `$sce.getTrusted`.
29528      * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
29529      */
29530
29531     /**
29532      * @ngdoc method
29533      * @name $sce#parseAsHtml
29534      *
29535      * @description
29536      * Shorthand method.  `$sce.parseAsHtml(expression string)` â†’
29537      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
29538      *
29539      * @param {string} expression String expression to compile.
29540      * @returns {function(context, locals)} a function which represents the compiled expression:
29541      *
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
29545      *      `context`.
29546      */
29547
29548     /**
29549      * @ngdoc method
29550      * @name $sce#parseAsCss
29551      *
29552      * @description
29553      * Shorthand method.  `$sce.parseAsCss(value)` â†’
29554      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
29555      *
29556      * @param {string} expression String expression to compile.
29557      * @returns {function(context, locals)} a function which represents the compiled expression:
29558      *
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
29562      *      `context`.
29563      */
29564
29565     /**
29566      * @ngdoc method
29567      * @name $sce#parseAsUrl
29568      *
29569      * @description
29570      * Shorthand method.  `$sce.parseAsUrl(value)` â†’
29571      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
29572      *
29573      * @param {string} expression String expression to compile.
29574      * @returns {function(context, locals)} a function which represents the compiled expression:
29575      *
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
29579      *      `context`.
29580      */
29581
29582     /**
29583      * @ngdoc method
29584      * @name $sce#parseAsResourceUrl
29585      *
29586      * @description
29587      * Shorthand method.  `$sce.parseAsResourceUrl(value)` â†’
29588      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
29589      *
29590      * @param {string} expression String expression to compile.
29591      * @returns {function(context, locals)} a function which represents the compiled expression:
29592      *
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
29596      *      `context`.
29597      */
29598
29599     /**
29600      * @ngdoc method
29601      * @name $sce#parseAsJs
29602      *
29603      * @description
29604      * Shorthand method.  `$sce.parseAsJs(value)` â†’
29605      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
29606      *
29607      * @param {string} expression String expression to compile.
29608      * @returns {function(context, locals)} a function which represents the compiled expression:
29609      *
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
29613      *      `context`.
29614      */
29615
29616     // Shorthand delegations.
29617     var parse = sce.parseAs,
29618         getTrusted = sce.getTrusted,
29619         trustAs = sce.trustAs;
29620
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);
29625       };
29626       sce[camelCase('get_trusted_' + lName)] = function(value) {
29627         return getTrusted(enumValue, value);
29628       };
29629       sce[camelCase('trust_as_' + lName)] = function(value) {
29630         return trustAs(enumValue, value);
29631       };
29632     });
29633
29634     return sce;
29635   }];
29636 }
29637
29638 /* exported $SnifferProvider */
29639
29640 /**
29641  * !!! This is an undocumented "private" service !!!
29642  *
29643  * @name $sniffer
29644  * @requires $window
29645  * @requires $document
29646  * @this
29647  *
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 ?
29651  *
29652  * @description
29653  * This is very simple implementation of testing browser's features.
29654  */
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 =
29664             $window.chrome &&
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,
29668         android =
29669           toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
29670         boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
29671         document = $document[0] || {},
29672         vendorPrefix,
29673         vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
29674         bodyStyle = document.body && document.body.style,
29675         transitions = false,
29676         animations = false,
29677         match;
29678
29679     if (bodyStyle) {
29680       for (var prop in bodyStyle) {
29681         if ((match = vendorRegex.exec(prop))) {
29682           vendorPrefix = match[0];
29683           vendorPrefix = vendorPrefix[0].toUpperCase() + vendorPrefix.substr(1);
29684           break;
29685         }
29686       }
29687
29688       if (!vendorPrefix) {
29689         vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
29690       }
29691
29692       transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
29693       animations  = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
29694
29695       if (android && (!transitions ||  !animations)) {
29696         transitions = isString(bodyStyle.webkitTransition);
29697         animations = isString(bodyStyle.webkitAnimation);
29698       }
29699     }
29700
29701
29702     return {
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
29707
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;
29719
29720         if (isUndefined(eventSupport[event])) {
29721           var divElm = document.createElement('div');
29722           eventSupport[event] = 'on' + event in divElm;
29723         }
29724
29725         return eventSupport[event];
29726       },
29727       csp: csp(),
29728       vendorPrefix: vendorPrefix,
29729       transitions: transitions,
29730       animations: animations,
29731       android: android
29732     };
29733   }];
29734 }
29735
29736 var $templateRequestMinErr = minErr('$compile');
29737
29738 /**
29739  * @ngdoc provider
29740  * @name $templateRequestProvider
29741  * @this
29742  *
29743  * @description
29744  * Used to configure the options passed to the {@link $http} service when making a template request.
29745  *
29746  * For example, it can be used for specifying the "Accept" header that is sent to the server, when
29747  * requesting a template.
29748  */
29749 function $TemplateRequestProvider() {
29750
29751   var httpOptions;
29752
29753   /**
29754    * @ngdoc method
29755    * @name $templateRequestProvider#httpOptions
29756    * @description
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.
29759    *
29760    * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
29761    * options if not overridden here.
29762    *
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.
29765    */
29766   this.httpOptions = function(val) {
29767     if (val) {
29768       httpOptions = val;
29769       return this;
29770     }
29771     return httpOptions;
29772   };
29773
29774   /**
29775    * @ngdoc service
29776    * @name $templateRequest
29777    *
29778    * @description
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.
29785    *
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}.
29788    *
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
29791    *
29792    * @return {Promise} a promise for the HTTP response data of the given URL.
29793    *
29794    * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
29795    */
29796   this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
29797
29798     function handleRequestFn(tpl, ignoreRequestError) {
29799       handleRequestFn.totalPendingRequests++;
29800
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
29805       // types.
29806       if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
29807         tpl = $sce.getTrustedResourceUrl(tpl);
29808       }
29809
29810       var transformResponse = $http.defaults && $http.defaults.transformResponse;
29811
29812       if (isArray(transformResponse)) {
29813         transformResponse = transformResponse.filter(function(transformer) {
29814           return transformer !== defaultHttpResponseTransform;
29815         });
29816       } else if (transformResponse === defaultHttpResponseTransform) {
29817         transformResponse = null;
29818       }
29819
29820       return $http.get(tpl, extend({
29821           cache: $templateCache,
29822           transformResponse: transformResponse
29823         }, httpOptions)
29824         )['finally'](function() {
29825           handleRequestFn.totalPendingRequests--;
29826         })
29827         .then(function(response) {
29828           $templateCache.put(tpl, response.data);
29829           return response.data;
29830         }, handleError);
29831
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);
29836         }
29837         return $q.reject(resp);
29838       }
29839     }
29840
29841     handleRequestFn.totalPendingRequests = 0;
29842
29843     return handleRequestFn;
29844   }];
29845 }
29846
29847 /** @this */
29848 function $$TestabilityProvider() {
29849   this.$get = ['$rootScope', '$browser', '$location',
29850        function($rootScope,   $browser,   $location) {
29851
29852     /**
29853      * @name $testability
29854      *
29855      * @description
29856      * The private $$testability service provides a collection of methods for use when debugging
29857      * or by automated test and debugging tools.
29858      */
29859     var testability = {};
29860
29861     /**
29862      * @name $$testability#findBindings
29863      *
29864      * @description
29865      * Returns an array of elements that are bound (via ng-bind or {{}})
29866      * to expressions matching the input.
29867      *
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.
29872      */
29873     testability.findBindings = function(element, expression, opt_exactMatch) {
29874       var bindings = element.getElementsByClassName('ng-binding');
29875       var matches = [];
29876       forEach(bindings, function(binding) {
29877         var dataBinding = angular.element(binding).data('$binding');
29878         if (dataBinding) {
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);
29884               }
29885             } else {
29886               if (bindingName.indexOf(expression) !== -1) {
29887                 matches.push(binding);
29888               }
29889             }
29890           });
29891         }
29892       });
29893       return matches;
29894     };
29895
29896     /**
29897      * @name $$testability#findModels
29898      *
29899      * @description
29900      * Returns an array of elements that are two-way found via ng-model to
29901      * expressions matching the input.
29902      *
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.
29907      */
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) {
29915           return elements;
29916         }
29917       }
29918     };
29919
29920     /**
29921      * @name $$testability#getLocation
29922      *
29923      * @description
29924      * Shortcut for getting the location in a browser agnostic way. Returns
29925      *     the path, search, and hash. (e.g. /path?a=b#hash)
29926      */
29927     testability.getLocation = function() {
29928       return $location.url();
29929     };
29930
29931     /**
29932      * @name $$testability#setLocation
29933      *
29934      * @description
29935      * Shortcut for navigating to a location without doing a full page reload.
29936      *
29937      * @param {string} url The location url (path, search and hash,
29938      *     e.g. /path?a=b#hash) to go to.
29939      */
29940     testability.setLocation = function(url) {
29941       if (url !== $location.url()) {
29942         $location.url(url);
29943         $rootScope.$digest();
29944       }
29945     };
29946
29947     /**
29948      * @name $$testability#whenStable
29949      *
29950      * @description
29951      * Calls the callback when $timeout and $http requests are completed.
29952      *
29953      * @param {function} callback
29954      */
29955     testability.whenStable = function(callback) {
29956       $browser.notifyWhenNoOutstandingRequests(callback);
29957     };
29958
29959     return testability;
29960   }];
29961 }
29962
29963 /** @this */
29964 function $TimeoutProvider() {
29965   this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
29966        function($rootScope,   $browser,   $q,   $$q,   $exceptionHandler) {
29967
29968     var deferreds = {};
29969
29970
29971      /**
29972       * @ngdoc service
29973       * @name $timeout
29974       *
29975       * @description
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.
29979       *
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.
29982       *
29983       * To cancel a timeout request, call `$timeout.cancel(promise)`.
29984       *
29985       * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
29986       * synchronously flush the queue of deferred functions.
29987       *
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.
29990       *
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.
29998       *
29999       */
30000     function timeout(fn, delay, invokeApply) {
30001       if (!isFunction(fn)) {
30002         invokeApply = delay;
30003         delay = fn;
30004         fn = noop;
30005       }
30006
30007       var args = sliceArgs(arguments, 3),
30008           skipApply = (isDefined(invokeApply) && !invokeApply),
30009           deferred = (skipApply ? $$q : $q).defer(),
30010           promise = deferred.promise,
30011           timeoutId;
30012
30013       timeoutId = $browser.defer(function() {
30014         try {
30015           deferred.resolve(fn.apply(null, args));
30016         } catch (e) {
30017           deferred.reject(e);
30018           $exceptionHandler(e);
30019         } finally {
30020           delete deferreds[promise.$$timeoutId];
30021         }
30022
30023         if (!skipApply) $rootScope.$apply();
30024       }, delay);
30025
30026       promise.$$timeoutId = timeoutId;
30027       deferreds[timeoutId] = deferred;
30028
30029       return promise;
30030     }
30031
30032
30033      /**
30034       * @ngdoc method
30035       * @name $timeout#cancel
30036       *
30037       * @description
30038       * Cancels a task associated with the `promise`. As a result of this, the promise will be
30039       * resolved with a rejection.
30040       *
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
30043       *   canceled.
30044       */
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);
30050       }
30051       return false;
30052     };
30053
30054     return timeout;
30055   }];
30056 }
30057
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
30064 // service.
30065 var urlParsingNode = window.document.createElement('a');
30066 var originUrl = urlResolve(window.location.href);
30067
30068
30069 /**
30070  *
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
30080  *
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.
30089  *
30090  * References:
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/
30096  *
30097  * @kind function
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.
30101  *
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 "/"
30112  *
30113  */
30114 function urlResolve(url) {
30115   var href = url;
30116
30117   if (msie) {
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;
30122   }
30123
30124   urlParsingNode.setAttribute('href', href);
30125
30126   // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
30127   return {
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
30138   };
30139 }
30140
30141 /**
30142  * Parse a request URL and determine whether this is a same-origin request as the application document.
30143  *
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.
30147  */
30148 function urlIsSameOrigin(requestUrl) {
30149   var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
30150   return (parsed.protocol === originUrl.protocol &&
30151           parsed.host === originUrl.host);
30152 }
30153
30154 /**
30155  * @ngdoc service
30156  * @name $window
30157  * @this
30158  *
30159  * @description
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.
30164  *
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
30168  * expression.
30169  *
30170  * @example
30171    <example module="windowExample" name="window-service">
30172      <file name="index.html">
30173        <script>
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);
30179              };
30180            }]);
30181        </script>
30182        <div ng-controller="ExampleController">
30183          <input type="text" ng-model="greeting" aria-label="greeting" />
30184          <button ng-click="doGreeting(greeting)">ALERT</button>
30185        </div>
30186      </file>
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();
30192       });
30193      </file>
30194    </example>
30195  */
30196 function $WindowProvider() {
30197   this.$get = valueFn(window);
30198 }
30199
30200 /**
30201  * @name $$cookieReader
30202  * @requires $document
30203  *
30204  * @description
30205  * This is a private service for reading cookies used by $http and ngCookies
30206  *
30207  * @return {Object} a key/value map of the current cookies
30208  */
30209 function $$CookieReader($document) {
30210   var rawDocument = $document[0] || {};
30211   var lastCookies = {};
30212   var lastCookieString = '';
30213
30214   function safeGetCookie(rawDocument) {
30215     try {
30216       return rawDocument.cookie || '';
30217     } catch (e) {
30218       return '';
30219     }
30220   }
30221
30222   function safeDecodeURIComponent(str) {
30223     try {
30224       return decodeURIComponent(str);
30225     } catch (e) {
30226       return str;
30227     }
30228   }
30229
30230   return function() {
30231     var cookieArray, cookie, i, index, name;
30232     var currentCookieString = safeGetCookie(rawDocument);
30233
30234     if (currentCookieString !== lastCookieString) {
30235       lastCookieString = currentCookieString;
30236       cookieArray = lastCookieString.split('; ');
30237       lastCookies = {};
30238
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));
30249           }
30250         }
30251       }
30252     }
30253     return lastCookies;
30254   };
30255 }
30256
30257 $$CookieReader.$inject = ['$document'];
30258
30259 /** @this */
30260 function $$CookieReaderProvider() {
30261   this.$get = $$CookieReader;
30262 }
30263
30264 /* global currencyFilter: true,
30265  dateFilter: true,
30266  filterFilter: true,
30267  jsonFilter: true,
30268  limitToFilter: true,
30269  lowercaseFilter: true,
30270  numberFilter: true,
30271  orderByFilter: true,
30272  uppercaseFilter: true,
30273  */
30274
30275 /**
30276  * @ngdoc provider
30277  * @name $filterProvider
30278  * @description
30279  *
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.
30283  *
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`).
30289  * </div>
30290  *
30291  * ```js
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 + '!';
30297  *     });
30298  *
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;
30307  *       };
30308  *     });
30309  *   }
30310  * ```
30311  *
30312  * The filter function is registered with the `$injector` under the filter name suffix with
30313  * `Filter`.
30314  *
30315  * ```js
30316  *   it('should be the same instance', inject(
30317  *     function($filterProvider) {
30318  *       $filterProvider.register('reverse', function(){
30319  *         return ...;
30320  *       });
30321  *     },
30322  *     function($filter, reverseFilter) {
30323  *       expect($filter('reverse')).toBe(reverseFilter);
30324  *     });
30325  * ```
30326  *
30327  *
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.
30330  */
30331
30332 /**
30333  * @ngdoc service
30334  * @name $filter
30335  * @kind function
30336  * @description
30337  * Filters are used for formatting data displayed to the user.
30338  *
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.
30342  *
30343  * The general syntax in templates is as follows:
30344  *
30345  * ```html
30346  * {{ expression [| filter_name[:parameter_value] ... ] }}
30347  * ```
30348  *
30349  * @param {String} name Name of the filter function to retrieve
30350  * @return {Function} the filter function
30351  * @example
30352    <example name="$filter" module="filterExample">
30353      <file name="index.html">
30354        <div ng-controller="MainCtrl">
30355         <h3>{{ originalText }}</h3>
30356         <h3>{{ filteredText }}</h3>
30357        </div>
30358      </file>
30359
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);
30365       });
30366      </file>
30367    </example>
30368   */
30369 $FilterProvider.$inject = ['$provide'];
30370 /** @this */
30371 function $FilterProvider($provide) {
30372   var suffix = 'Filter';
30373
30374   /**
30375    * @ngdoc method
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.
30379    *
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`).
30385    *    </div>
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.
30389    */
30390   function register(name, factory) {
30391     if (isObject(name)) {
30392       var filters = {};
30393       forEach(name, function(filter, key) {
30394         filters[key] = register(key, filter);
30395       });
30396       return filters;
30397     } else {
30398       return $provide.factory(name + suffix, factory);
30399     }
30400   }
30401   this.register = register;
30402
30403   this.$get = ['$injector', function($injector) {
30404     return function(name) {
30405       return $injector.get(name + suffix);
30406     };
30407   }];
30408
30409   ////////////////////////////////////////
30410
30411   /* global
30412     currencyFilter: false,
30413     dateFilter: false,
30414     filterFilter: false,
30415     jsonFilter: false,
30416     limitToFilter: false,
30417     lowercaseFilter: false,
30418     numberFilter: false,
30419     orderByFilter: false,
30420     uppercaseFilter: false
30421   */
30422
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);
30432 }
30433
30434 /**
30435  * @ngdoc filter
30436  * @name filter
30437  * @kind function
30438  *
30439  * @description
30440  * Selects a subset of items from `array` and returns it as a new array.
30441  *
30442  * @param {Array} array The source array.
30443  * @param {string|Object|function()} expression The predicate to be used for selecting items from
30444  *   `array`.
30445  *
30446  *   Can be one of:
30447  *
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 `!`.
30452  *
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".
30463  *
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'}`.
30468  *
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.
30472  *
30473  *     The final result is an array of those elements that the predicate returned true for.
30474  *
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.
30478  *
30479  *   Can be one of:
30480  *
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.
30484  *
30485  *   - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
30486  *     This is essentially strict comparison of expected and actual.
30487  *
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).
30491  *
30492  *
30493  *   Defaults to `false`.
30494  *
30495  * @param {string} [anyPropertyKey] The special property name that matches against any property.
30496  *     By default `$`.
30497  *
30498  * @example
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>
30507
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>
30514          </tr>
30515        </table>
30516        <hr>
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>
30526          </tr>
30527        </table>
30528      </file>
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]);
30534            });
30535          });
30536        };
30537
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');
30543
30544          searchText.clear();
30545          searchText.sendKeys('76');
30546          expectFriendNames(['John', 'Julie'], 'friend');
30547        });
30548
30549        it('should search in specific fields when filtering with a predicate object', function() {
30550          var searchAny = element(by.model('search.$'));
30551          searchAny.clear();
30552          searchAny.sendKeys('i');
30553          expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
30554        });
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');
30560          strict.click();
30561          expectFriendNames(['Julie'], 'friendObj');
30562        });
30563      </file>
30564    </example>
30565  */
30566
30567 function filterFilter() {
30568   return function(array, expression, comparator, anyPropertyKey) {
30569     if (!isArrayLike(array)) {
30570       if (array == null) {
30571         return array;
30572       } else {
30573         throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
30574       }
30575     }
30576
30577     anyPropertyKey = anyPropertyKey || '$';
30578     var expressionType = getTypeForFilter(expression);
30579     var predicateFn;
30580     var matchAgainstAnyProp;
30581
30582     switch (expressionType) {
30583       case 'function':
30584         predicateFn = expression;
30585         break;
30586       case 'boolean':
30587       case 'null':
30588       case 'number':
30589       case 'string':
30590         matchAgainstAnyProp = true;
30591         // falls through
30592       case 'object':
30593         predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);
30594         break;
30595       default:
30596         return array;
30597     }
30598
30599     return Array.prototype.filter.call(array, predicateFn);
30600   };
30601 }
30602
30603 // Helper functions for `filterFilter`
30604 function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {
30605   var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);
30606   var predicateFn;
30607
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`
30614         return false;
30615       }
30616       if ((actual === null) || (expected === null)) {
30617         // No substring matching against `null`; only match against `null`
30618         return actual === expected;
30619       }
30620       if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
30621         // Should not compare primitives against objects, unless they have custom `toString` method
30622         return false;
30623       }
30624
30625       actual = lowercase('' + actual);
30626       expected = lowercase('' + expected);
30627       return actual.indexOf(expected) !== -1;
30628     };
30629   }
30630
30631   predicateFn = function(item) {
30632     if (shouldMatchPrimitives && !isObject(item)) {
30633       return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);
30634     }
30635     return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);
30636   };
30637
30638   return predicateFn;
30639 }
30640
30641 function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {
30642   var actualType = getTypeForFilter(actual);
30643   var expectedType = getTypeForFilter(expected);
30644
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);
30652     });
30653   }
30654
30655   switch (actualType) {
30656     case 'object':
30657       var key;
30658       if (matchAgainstAnyProp) {
30659         for (key in actual) {
30660           if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {
30661             return true;
30662           }
30663         }
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)) {
30669             continue;
30670           }
30671
30672           var matchAnyProperty = key === anyPropertyKey;
30673           var actualVal = matchAnyProperty ? actual : actual[key];
30674           if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {
30675             return false;
30676           }
30677         }
30678         return true;
30679       } else {
30680         return comparator(actual, expected);
30681       }
30682     case 'function':
30683       return false;
30684     default:
30685       return comparator(actual, expected);
30686   }
30687 }
30688
30689 // Used for easily differentiating between `null` and actual `object`
30690 function getTypeForFilter(val) {
30691   return (val === null) ? 'null' : typeof val;
30692 }
30693
30694 var MAX_DIGITS = 22;
30695 var DECIMAL_SEP = '.';
30696 var ZERO_CHAR = '0';
30697
30698 /**
30699  * @ngdoc filter
30700  * @name currency
30701  * @kind function
30702  *
30703  * @description
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.
30706  *
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.
30711  *
30712  *
30713  * @example
30714    <example module="currencyExample" name="currency-filter">
30715      <file name="index.html">
30716        <script>
30717          angular.module('currencyExample', [])
30718            .controller('ExampleController', ['$scope', function($scope) {
30719              $scope.amount = 1234.56;
30720            }]);
30721        </script>
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>
30727        </div>
30728      </file>
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');
30734        });
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
30739            return;
30740          }
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');
30746        });
30747      </file>
30748    </example>
30749  */
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;
30756     }
30757
30758     if (isUndefined(fractionSize)) {
30759       fractionSize = formats.PATTERNS[1].maxFrac;
30760     }
30761
30762     // if null or undefined pass it through
30763     return (amount == null)
30764         ? amount
30765         : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
30766             replace(/\u00A4/g, currencySymbol);
30767   };
30768 }
30769
30770 /**
30771  * @ngdoc filter
30772  * @name number
30773  * @kind function
30774  *
30775  * @description
30776  * Formats a number as text.
30777  *
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.
30781  *
30782  *
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).
30790  *
30791  * @example
30792    <example module="numberFilterExample" name="number-filter">
30793      <file name="index.html">
30794        <script>
30795          angular.module('numberFilterExample', [])
30796            .controller('ExampleController', ['$scope', function($scope) {
30797              $scope.val = 1234.56789;
30798            }]);
30799        </script>
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>
30805        </div>
30806      </file>
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');
30812        });
30813
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');
30820       });
30821      </file>
30822    </example>
30823  */
30824 numberFilter.$inject = ['$locale'];
30825 function numberFilter($locale) {
30826   var formats = $locale.NUMBER_FORMATS;
30827   return function(number, fractionSize) {
30828
30829     // if null or undefined pass it through
30830     return (number == null)
30831         ? number
30832         : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
30833                        fractionSize);
30834   };
30835 }
30836
30837 /**
30838  * Parse a number (as a string) into three components that can be used
30839  * for formatting the number.
30840  *
30841  * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
30842  *
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`
30848  *
30849  */
30850 function parse(numStr) {
30851   var exponent = 0, digits, numberOfIntegerDigits;
30852   var i, j, zeros;
30853
30854   // Decimal point?
30855   if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
30856     numStr = numStr.replace(DECIMAL_SEP, '');
30857   }
30858
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;
30868   }
30869
30870   // Count the number of leading zeros.
30871   for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }
30872
30873   if (i === (zeros = numStr.length)) {
30874     // The digits are all zero.
30875     digits = [0];
30876     numberOfIntegerDigits = 1;
30877   } else {
30878     // Count the number of trailing zeros
30879     zeros--;
30880     while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;
30881
30882     // Trailing zeros are insignificant so ignore them
30883     numberOfIntegerDigits -= i;
30884     digits = [];
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);
30888     }
30889   }
30890
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;
30896   }
30897
30898   return { d: digits, e: exponent, i: numberOfIntegerDigits };
30899 }
30900
30901 /**
30902  * Round the parsed number to the specified number of decimal places
30903  * This function changed the parsedNumber in-place
30904  */
30905 function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
30906     var digits = parsedNumber.d;
30907     var fractionLen = digits.length - parsedNumber.i;
30908
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;
30911
30912     // The index of the digit to where rounding is to occur
30913     var roundAt = fractionSize + parsedNumber.i;
30914     var digit = digits[roundAt];
30915
30916     if (roundAt > 0) {
30917       // Drop fractional digits beyond `roundAt`
30918       digits.splice(Math.max(parsedNumber.i, roundAt));
30919
30920       // Set non-fractional digits beyond `roundAt` to 0
30921       for (var j = roundAt; j < digits.length; j++) {
30922         digits[j] = 0;
30923       }
30924     } else {
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);
30929       digits[0] = 0;
30930       for (var i = 1; i < roundAt; i++) digits[i] = 0;
30931     }
30932
30933     if (digit >= 5) {
30934       if (roundAt - 1 < 0) {
30935         for (var k = 0; k > roundAt; k--) {
30936           digits.unshift(0);
30937           parsedNumber.i++;
30938         }
30939         digits.unshift(1);
30940         parsedNumber.i++;
30941       } else {
30942         digits[roundAt - 1]++;
30943       }
30944     }
30945
30946     // Pad out with zeros to get the required fraction length
30947     for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
30948
30949
30950     // Do any carrying, e.g. a digit was rounded up to 10
30951     var carry = digits.reduceRight(function(carry, d, i, digits) {
30952       d = d + carry;
30953       digits[i] = d % 10;
30954       return Math.floor(d / 10);
30955     }, 0);
30956     if (carry) {
30957       digits.unshift(carry);
30958       parsedNumber.i++;
30959     }
30960 }
30961
30962 /**
30963  * Format a number into a string
30964  * @param  {number} number       The number to format
30965  * @param  {{
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
30974  *         }} pattern
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
30979  */
30980 function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
30981
30982   if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
30983
30984   var isInfinity = !isFinite(number);
30985   var isZero = false;
30986   var numStr = Math.abs(number) + '',
30987       formattedText = '',
30988       parsedNumber;
30989
30990   if (isInfinity) {
30991     formattedText = '\u221e';
30992   } else {
30993     parsedNumber = parse(numStr);
30994
30995     roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
30996
30997     var digits = parsedNumber.d;
30998     var integerLen = parsedNumber.i;
30999     var exponent = parsedNumber.e;
31000     var decimals = [];
31001     isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
31002
31003     // pad zeros for small numbers
31004     while (integerLen < 0) {
31005       digits.unshift(0);
31006       integerLen++;
31007     }
31008
31009     // extract decimals digits
31010     if (integerLen > 0) {
31011       decimals = digits.splice(integerLen, digits.length);
31012     } else {
31013       decimals = digits;
31014       digits = [0];
31015     }
31016
31017     // format the integer digits with grouping separators
31018     var groups = [];
31019     if (digits.length >= pattern.lgSize) {
31020       groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
31021     }
31022     while (digits.length > pattern.gSize) {
31023       groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
31024     }
31025     if (digits.length) {
31026       groups.unshift(digits.join(''));
31027     }
31028     formattedText = groups.join(groupSep);
31029
31030     // append the decimal digits
31031     if (decimals.length) {
31032       formattedText += decimalSep + decimals.join('');
31033     }
31034
31035     if (exponent) {
31036       formattedText += 'e+' + exponent;
31037     }
31038   }
31039   if (number < 0 && !isZero) {
31040     return pattern.negPre + formattedText + pattern.negSuf;
31041   } else {
31042     return pattern.posPre + formattedText + pattern.posSuf;
31043   }
31044 }
31045
31046 function padNumber(num, digits, trim, negWrap) {
31047   var neg = '';
31048   if (num < 0 || (negWrap && num <= 0)) {
31049     if (negWrap) {
31050       num = -num + 1;
31051     } else {
31052       num = -num;
31053       neg = '-';
31054     }
31055   }
31056   num = '' + num;
31057   while (num.length < digits) num = ZERO_CHAR + num;
31058   if (trim) {
31059     num = num.substr(num.length - digits);
31060   }
31061   return neg + num;
31062 }
31063
31064
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) {
31070       value += offset;
31071     }
31072     if (value === 0 && offset === -12) value = 12;
31073     return padNumber(value, size, trim, negWrap);
31074   };
31075 }
31076
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);
31082
31083     return formats[get][value];
31084   };
31085 }
31086
31087 function timeZoneGetter(date, formats, offset) {
31088   var zone = -1 * offset;
31089   var paddedZone = (zone >= 0) ? '+' : '';
31090
31091   paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
31092                 padNumber(Math.abs(zone % 60), 2);
31093
31094   return paddedZone;
31095 }
31096
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);
31103 }
31104
31105 function getThursdayThisWeek(datetime) {
31106     return new Date(datetime.getFullYear(), datetime.getMonth(),
31107       // 4 = index of Thursday
31108       datetime.getDate() + (4 - datetime.getDay()));
31109 }
31110
31111 function weekGetter(size) {
31112    return function(date) {
31113       var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
31114          thisThurs = getThursdayThisWeek(date);
31115
31116       var diff = +thisThurs - +firstThurs,
31117          result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
31118
31119       return padNumber(result, size);
31120    };
31121 }
31122
31123 function ampmGetter(date, formats) {
31124   return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
31125 }
31126
31127 function eraGetter(date, formats) {
31128   return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
31129 }
31130
31131 function longEraGetter(date, formats) {
31132   return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
31133 }
31134
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),
31159      a: ampmGetter,
31160      Z: timeZoneGetter,
31161     ww: weekGetter(2),
31162      w: weekGetter(1),
31163      G: eraGetter,
31164      GG: eraGetter,
31165      GGG: eraGetter,
31166      GGGG: longEraGetter
31167 };
31168
31169 var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
31170     NUMBER_STRING = /^-?\d+$/;
31171
31172 /**
31173  * @ngdoc filter
31174  * @name date
31175  * @kind function
31176  *
31177  * @description
31178  *   Formats `date` to a string based on the requested `format`.
31179  *
31180  *   `format` string can be composed of the following elements:
31181  *
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')
31209  *
31210  *   `format` string can also be one of the following predefined
31211  *   {@link guide/i18n localizable formats}:
31212  *
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)
31223  *
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'"`).
31227  *
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.
31239  *
31240  * @example
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>
31251      </file>
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)/);
31262        });
31263      </file>
31264    </example>
31265  */
31266 dateFilter.$inject = ['$locale'];
31267 function dateFilter($locale) {
31268
31269
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) {
31273     var match;
31274     if ((match = string.match(R_ISO8601_STR))) {
31275       var date = new Date(0),
31276           tzHour = 0,
31277           tzMin  = 0,
31278           dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
31279           timeSetter = match[8] ? date.setUTCHours : date.setHours;
31280
31281       if (match[9]) {
31282         tzHour = toInt(match[9] + match[10]);
31283         tzMin = toInt(match[9] + match[11]);
31284       }
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);
31291       return date;
31292     }
31293     return string;
31294   }
31295
31296
31297   return function(date, format, timezone) {
31298     var text = '',
31299         parts = [],
31300         fn, match;
31301
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);
31306     }
31307
31308     if (isNumber(date)) {
31309       date = new Date(date);
31310     }
31311
31312     if (!isDate(date) || !isFinite(date.getTime())) {
31313       return date;
31314     }
31315
31316     while (format) {
31317       match = DATE_FORMATS_SPLIT.exec(format);
31318       if (match) {
31319         parts = concat(parts, match, 1);
31320         format = parts.pop();
31321       } else {
31322         parts.push(format);
31323         format = null;
31324       }
31325     }
31326
31327     var dateTimezoneOffset = date.getTimezoneOffset();
31328     if (timezone) {
31329       dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
31330       date = convertTimezoneToLocal(date, timezone, true);
31331     }
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, '\'');
31336     });
31337
31338     return text;
31339   };
31340 }
31341
31342
31343 /**
31344  * @ngdoc filter
31345  * @name json
31346  * @kind function
31347  *
31348  * @description
31349  *   Allows you to convert a JavaScript object into JSON string.
31350  *
31351  *   This filter is mostly useful for debugging. When using the double curly {{value}} notation
31352  *   the binding is automatically converted to JSON.
31353  *
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.
31357  *
31358  *
31359  * @example
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>
31364      </file>
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}/);
31369        });
31370      </file>
31371    </example>
31372  *
31373  */
31374 function jsonFilter() {
31375   return function(object, spacing) {
31376     if (isUndefined(spacing)) {
31377         spacing = 2;
31378     }
31379     return toJson(object, spacing);
31380   };
31381 }
31382
31383
31384 /**
31385  * @ngdoc filter
31386  * @name lowercase
31387  * @kind function
31388  * @description
31389  * Converts string to lowercase.
31390  * @see angular.lowercase
31391  */
31392 var lowercaseFilter = valueFn(lowercase);
31393
31394
31395 /**
31396  * @ngdoc filter
31397  * @name uppercase
31398  * @kind function
31399  * @description
31400  * Converts string to uppercase.
31401  * @see angular.uppercase
31402  */
31403 var uppercaseFilter = valueFn(uppercase);
31404
31405 /**
31406  * @ngdoc filter
31407  * @name limitTo
31408  * @kind function
31409  *
31410  * @description
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.
31416  *
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.
31427  *
31428  * @example
31429    <example module="limitToExample" name="limit-to-filter">
31430      <file name="index.html">
31431        <script>
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;
31440            }]);
31441        </script>
31442        <div ng-controller="ExampleController">
31443          <label>
31444             Limit {{numbers}} to:
31445             <input type="number" step="1" ng-model="numLimit">
31446          </label>
31447          <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
31448          <label>
31449             Limit {{letters}} to:
31450             <input type="number" step="1" ng-model="letterLimit">
31451          </label>
31452          <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
31453          <label>
31454             Limit {{longNumber}} to:
31455             <input type="number" step="1" ng-model="longNumberLimit">
31456          </label>
31457          <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
31458        </div>
31459      </file>
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'));
31467
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');
31475        });
31476
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');
31488        // });
31489
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');
31500        });
31501      </file>
31502    </example>
31503 */
31504 function limitToFilter() {
31505   return function(input, limit, begin) {
31506     if (Math.abs(Number(limit)) === Infinity) {
31507       limit = Number(limit);
31508     } else {
31509       limit = toInt(limit);
31510     }
31511     if (isNumberNaN(limit)) return input;
31512
31513     if (isNumber(input)) input = input.toString();
31514     if (!isArrayLike(input)) return input;
31515
31516     begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
31517     begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
31518
31519     if (limit >= 0) {
31520       return sliceFn(input, begin, begin + limit);
31521     } else {
31522       if (begin === 0) {
31523         return sliceFn(input, limit, input.length);
31524       } else {
31525         return sliceFn(input, Math.max(0, begin + limit), begin);
31526       }
31527     }
31528   };
31529 }
31530
31531 function sliceFn(input, begin, end) {
31532   if (isString(input)) return input.slice(begin, end);
31533
31534   return slice.call(input, begin, end);
31535 }
31536
31537 /**
31538  * @ngdoc filter
31539  * @name orderBy
31540  * @kind function
31541  *
31542  * @description
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.
31545  *
31546  * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
31547  * `[{id: 'bar'}, {id: 'foo'}]`.
31548  *
31549  * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
31550  * String, etc).
31551  *
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.
31555  *
31556  * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
31557  * ascending order.
31558  *
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).
31562  *
31563  * ### Under the hood
31564  *
31565  * Ordering the specified `collection` happens in two phases:
31566  *
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:
31570  *    ```
31571  *    {
31572  *      value: 'foo',
31573  *      type: 'string',
31574  *      index: ...
31575  *    }
31576  *    ```
31577  * 2. The comparator function is used to sort the items, based on the derived values, types and
31578  *    indices.
31579  *
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.
31584  *
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.)
31589  *
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:
31593  *
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.
31603  *
31604  * ### The default comparator
31605  *
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.
31609  *
31610  * More specifically, it follows these steps to determine the relative order of items:
31611  *
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.
31620  *
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
31625  *           other values.
31626  *
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.
31630  *
31631  *    Can be one of:
31632  *
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`
31638  *      property.<br />
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.
31647  *
31648  * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
31649  *
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.
31653  *
31654  * @returns {Array} - The sorted array.
31655  *
31656  *
31657  * @example
31658  * ### Ordering a table with `ngRepeat`
31659  *
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.
31663  *
31664    <example name="orderBy-static" module="orderByExample1">
31665      <file name="index.html">
31666        <div ng-controller="ExampleController">
31667          <table class="friends">
31668            <tr>
31669              <th>Name</th>
31670              <th>Phone Number</th>
31671              <th>Age</th>
31672            </tr>
31673            <tr ng-repeat="friend in friends | orderBy:'-age'">
31674              <td>{{friend.name}}</td>
31675              <td>{{friend.phone}}</td>
31676              <td>{{friend.age}}</td>
31677            </tr>
31678          </table>
31679        </div>
31680      </file>
31681      <file name="script.js">
31682        angular.module('orderByExample1', [])
31683          .controller('ExampleController', ['$scope', function($scope) {
31684            $scope.friends = [
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}
31690            ];
31691          }]);
31692      </file>
31693      <file name="style.css">
31694        .friends {
31695          border-collapse: collapse;
31696        }
31697
31698        .friends th {
31699          border-bottom: 1px solid;
31700        }
31701        .friends td, .friends th {
31702          border-left: 1px solid;
31703          padding: 5px 10px;
31704        }
31705        .friends td:first-child, .friends th:first-child {
31706          border-left: none;
31707        }
31708      </file>
31709      <file name="protractor.js" type="protractor">
31710        // Element locators
31711        var names = element.all(by.repeater('friends').column('friend.name'));
31712
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');
31719        });
31720      </file>
31721    </example>
31722  * <hr />
31723  *
31724  * @example
31725  * ### Changing parameters dynamically
31726  *
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.
31729  *
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>
31734          <hr/>
31735          <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
31736          <hr/>
31737          <table class="friends">
31738            <tr>
31739              <th>
31740                <button ng-click="sortBy('name')">Name</button>
31741                <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
31742              </th>
31743              <th>
31744                <button ng-click="sortBy('phone')">Phone Number</button>
31745                <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
31746              </th>
31747              <th>
31748                <button ng-click="sortBy('age')">Age</button>
31749                <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
31750              </th>
31751            </tr>
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>
31756            </tr>
31757          </table>
31758        </div>
31759      </file>
31760      <file name="script.js">
31761        angular.module('orderByExample2', [])
31762          .controller('ExampleController', ['$scope', function($scope) {
31763            var friends = [
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}
31769            ];
31770
31771            $scope.propertyName = 'age';
31772            $scope.reverse = true;
31773            $scope.friends = friends;
31774
31775            $scope.sortBy = function(propertyName) {
31776              $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
31777              $scope.propertyName = propertyName;
31778            };
31779          }]);
31780      </file>
31781      <file name="style.css">
31782        .friends {
31783          border-collapse: collapse;
31784        }
31785
31786        .friends th {
31787          border-bottom: 1px solid;
31788        }
31789        .friends td, .friends th {
31790          border-left: 1px solid;
31791          padding: 5px 10px;
31792        }
31793        .friends td:first-child, .friends th:first-child {
31794          border-left: none;
31795        }
31796
31797        .sortorder:after {
31798          content: '\25b2';   // BLACK UP-POINTING TRIANGLE
31799        }
31800        .sortorder.reverse:after {
31801          content: '\25bc';   // BLACK DOWN-POINTING TRIANGLE
31802        }
31803      </file>
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));
31812
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');
31816
31817          phoneHeader.click();
31818          expect(firstName.getText()).toBe('John');
31819          expect(lastName.getText()).toBe('Mary');
31820
31821          nameHeader.click();
31822          expect(firstName.getText()).toBe('Adam');
31823          expect(lastName.getText()).toBe('Mike');
31824
31825          ageHeader.click();
31826          expect(firstName.getText()).toBe('John');
31827          expect(lastName.getText()).toBe('Adam');
31828        });
31829
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');
31833
31834          ageHeader.click();
31835          expect(firstName.getText()).toBe('John');
31836          expect(lastName.getText()).toBe('Adam');
31837
31838          ageHeader.click();
31839          expect(firstName.getText()).toBe('Adam');
31840          expect(lastName.getText()).toBe('John');
31841        });
31842
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');
31846
31847          unsortButton.click();
31848          expect(firstName.getText()).toBe('John');
31849          expect(lastName.getText()).toBe('Julie');
31850        });
31851      </file>
31852    </example>
31853  * <hr />
31854  *
31855  * @example
31856  * ### Using `orderBy` inside a controller
31857  *
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')`.)
31861  *
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>
31866          <hr/>
31867          <button ng-click="sortBy(null)">Set to unsorted</button>
31868          <hr/>
31869          <table class="friends">
31870            <tr>
31871              <th>
31872                <button ng-click="sortBy('name')">Name</button>
31873                <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
31874              </th>
31875              <th>
31876                <button ng-click="sortBy('phone')">Phone Number</button>
31877                <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
31878              </th>
31879              <th>
31880                <button ng-click="sortBy('age')">Age</button>
31881                <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
31882              </th>
31883            </tr>
31884            <tr ng-repeat="friend in friends">
31885              <td>{{friend.name}}</td>
31886              <td>{{friend.phone}}</td>
31887              <td>{{friend.age}}</td>
31888            </tr>
31889          </table>
31890        </div>
31891      </file>
31892      <file name="script.js">
31893        angular.module('orderByExample3', [])
31894          .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
31895            var friends = [
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}
31901            ];
31902
31903            $scope.propertyName = 'age';
31904            $scope.reverse = true;
31905            $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
31906
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);
31912            };
31913          }]);
31914      </file>
31915      <file name="style.css">
31916        .friends {
31917          border-collapse: collapse;
31918        }
31919
31920        .friends th {
31921          border-bottom: 1px solid;
31922        }
31923        .friends td, .friends th {
31924          border-left: 1px solid;
31925          padding: 5px 10px;
31926        }
31927        .friends td:first-child, .friends th:first-child {
31928          border-left: none;
31929        }
31930
31931        .sortorder:after {
31932          content: '\25b2';   // BLACK UP-POINTING TRIANGLE
31933        }
31934        .sortorder.reverse:after {
31935          content: '\25bc';   // BLACK DOWN-POINTING TRIANGLE
31936        }
31937      </file>
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));
31946
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');
31950
31951          phoneHeader.click();
31952          expect(firstName.getText()).toBe('John');
31953          expect(lastName.getText()).toBe('Mary');
31954
31955          nameHeader.click();
31956          expect(firstName.getText()).toBe('Adam');
31957          expect(lastName.getText()).toBe('Mike');
31958
31959          ageHeader.click();
31960          expect(firstName.getText()).toBe('John');
31961          expect(lastName.getText()).toBe('Adam');
31962        });
31963
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');
31967
31968          ageHeader.click();
31969          expect(firstName.getText()).toBe('John');
31970          expect(lastName.getText()).toBe('Adam');
31971
31972          ageHeader.click();
31973          expect(firstName.getText()).toBe('Adam');
31974          expect(lastName.getText()).toBe('John');
31975        });
31976
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');
31980
31981          unsortButton.click();
31982          expect(firstName.getText()).toBe('John');
31983          expect(lastName.getText()).toBe('Julie');
31984        });
31985      </file>
31986    </example>
31987  * <hr />
31988  *
31989  * @example
31990  * ### Using a custom comparator
31991  *
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.)
31996  *
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">
32003              <tr>
32004                <th>Name</th>
32005                <th>Favorite Letter</th>
32006              </tr>
32007              <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
32008                <td>{{friend.name}}</td>
32009                <td>{{friend.favoriteLetter}}</td>
32010              </tr>
32011            </table>
32012          </div>
32013          <div class="friends-container default-comparator">
32014            <h3>Default Comparator</h3>
32015            <table class="friends">
32016              <tr>
32017                <th>Name</th>
32018                <th>Favorite Letter</th>
32019              </tr>
32020              <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
32021                <td>{{friend.name}}</td>
32022                <td>{{friend.favoriteLetter}}</td>
32023              </tr>
32024            </table>
32025          </div>
32026        </div>
32027      </file>
32028      <file name="script.js">
32029        angular.module('orderByExample4', [])
32030          .controller('ExampleController', ['$scope', function($scope) {
32031            $scope.friends = [
32032              {name: 'John',   favoriteLetter: 'Ä'},
32033              {name: 'Mary',   favoriteLetter: 'Ãœ'},
32034              {name: 'Mike',   favoriteLetter: 'Ö'},
32035              {name: 'Adam',   favoriteLetter: 'H'},
32036              {name: 'Julie',  favoriteLetter: 'Z'}
32037            ];
32038
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;
32043              }
32044
32045              // Compare strings alphabetically, taking locale into account
32046              return v1.value.localeCompare(v2.value);
32047            };
32048          }]);
32049      </file>
32050      <file name="style.css">
32051        .friends-container {
32052          display: inline-block;
32053          margin: 0 30px;
32054        }
32055
32056        .friends {
32057          border-collapse: collapse;
32058        }
32059
32060        .friends th {
32061          border-bottom: 1px solid;
32062        }
32063        .friends td, .friends th {
32064          border-left: 1px solid;
32065          padding: 5px 10px;
32066        }
32067        .friends td:first-child, .friends th:first-child {
32068          border-left: none;
32069        }
32070      </file>
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'));
32075
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');
32082        });
32083      </file>
32084    </example>
32085  *
32086  */
32087 orderByFilter.$inject = ['$parse'];
32088 function orderByFilter($parse) {
32089   return function(array, sortPredicate, reverseOrder, compareFn) {
32090
32091     if (array == null) return array;
32092     if (!isArrayLike(array)) {
32093       throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
32094     }
32095
32096     if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
32097     if (sortPredicate.length === 0) { sortPredicate = ['+']; }
32098
32099     var predicates = processPredicates(sortPredicate);
32100
32101     var descending = reverseOrder ? -1 : 1;
32102
32103     // Define the `compare()` function. Use a default comparator if none is specified.
32104     var compare = isFunction(compareFn) ? compareFn : defaultCompare;
32105
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; });
32112
32113     return array;
32114
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.
32119       return {
32120         value: value,
32121         tieBreaker: {value: index, type: 'number', index: index},
32122         predicateValues: predicates.map(function(predicate) {
32123           return getPredicateValue(predicate.get(value), index);
32124         })
32125       };
32126     }
32127
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]);
32131         if (result) {
32132           return result * predicates[i].descending * descending;
32133         }
32134       }
32135
32136       return compare(v1.tieBreaker, v2.tieBreaker) * descending;
32137     }
32138   };
32139
32140   function processPredicates(sortPredicates) {
32141     return sortPredicates.map(function(predicate) {
32142       var descending = 1, get = identity;
32143
32144       if (isFunction(predicate)) {
32145         get = 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);
32150         }
32151         if (predicate !== '') {
32152           get = $parse(predicate);
32153           if (get.constant) {
32154             var key = get();
32155             get = function(value) { return value[key]; };
32156           }
32157         }
32158       }
32159       return {get: get, descending: descending};
32160     });
32161   }
32162
32163   function isPrimitive(value) {
32164     switch (typeof value) {
32165       case 'number': /* falls through */
32166       case 'boolean': /* falls through */
32167       case 'string':
32168         return true;
32169       default:
32170         return false;
32171     }
32172   }
32173
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;
32179     }
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;
32184     }
32185
32186     return value;
32187   }
32188
32189   function getPredicateValue(value, index) {
32190     var type = typeof value;
32191     if (value === null) {
32192       type = 'string';
32193       value = 'null';
32194     } else if (type === 'object') {
32195       value = objectValue(value);
32196     }
32197     return {value: value, type: type, index: index};
32198   }
32199
32200   function defaultCompare(v1, v2) {
32201     var result = 0;
32202     var type1 = v1.type;
32203     var type2 = v2.type;
32204
32205     if (type1 === type2) {
32206       var value1 = v1.value;
32207       var value2 = v2.value;
32208
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;
32218       }
32219
32220       if (value1 !== value2) {
32221         result = value1 < value2 ? -1 : 1;
32222       }
32223     } else {
32224       result = type1 < type2 ? -1 : 1;
32225     }
32226
32227     return result;
32228   }
32229 }
32230
32231 function ngDirective(directive) {
32232   if (isFunction(directive)) {
32233     directive = {
32234       link: directive
32235     };
32236   }
32237   directive.restrict = directive.restrict || 'AC';
32238   return valueFn(directive);
32239 }
32240
32241 /**
32242  * @ngdoc directive
32243  * @name a
32244  * @restrict E
32245  *
32246  * @description
32247  * Modifies the default behavior of the html a tag so that the default action is prevented when
32248  * the href attribute is empty.
32249  *
32250  * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive.
32251  */
32252 var htmlAnchorDirective = valueFn({
32253   restrict: 'E',
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;
32259
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();
32267           }
32268         });
32269       };
32270     }
32271   }
32272 });
32273
32274 /**
32275  * @ngdoc directive
32276  * @name ngHref
32277  * @restrict A
32278  * @priority 99
32279  *
32280  * @description
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.
32287  *
32288  * The wrong way to write it:
32289  * ```html
32290  * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
32291  * ```
32292  *
32293  * The correct way to write it:
32294  * ```html
32295  * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
32296  * ```
32297  *
32298  * @element A
32299  * @param {template} ngHref any string which can contain `{{}}` markup.
32300  *
32301  * @example
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)
32313       </file>
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('');
32319         });
32320
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('');
32325         });
32326
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$/);
32329
32330           element(by.id('link-3')).click();
32331
32332           // At this point, we navigate away from an Angular page, so we need
32333           // to use browser.driver to get the base webdriver.
32334
32335           browser.wait(function() {
32336             return browser.driver.getCurrentUrl().then(function(url) {
32337               return url.match(/\/123$/);
32338             });
32339           }, 5000, 'page should navigate to /123');
32340         });
32341
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('');
32346         });
32347
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);
32352         });
32353
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$/);
32358
32359           element(by.id('link-6')).click();
32360
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$/);
32366             });
32367           }, 5000, 'page should navigate to /6');
32368         });
32369       </file>
32370     </example>
32371  */
32372
32373 /**
32374  * @ngdoc directive
32375  * @name ngSrc
32376  * @restrict A
32377  * @priority 99
32378  *
32379  * @description
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.
32384  *
32385  * The buggy way to write it:
32386  * ```html
32387  * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
32388  * ```
32389  *
32390  * The correct way to write it:
32391  * ```html
32392  * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
32393  * ```
32394  *
32395  * @element IMG
32396  * @param {template} ngSrc any string which can contain `{{}}` markup.
32397  */
32398
32399 /**
32400  * @ngdoc directive
32401  * @name ngSrcset
32402  * @restrict A
32403  * @priority 99
32404  *
32405  * @description
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.
32410  *
32411  * The buggy way to write it:
32412  * ```html
32413  * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
32414  * ```
32415  *
32416  * The correct way to write it:
32417  * ```html
32418  * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
32419  * ```
32420  *
32421  * @element IMG
32422  * @param {template} ngSrcset any string which can contain `{{}}` markup.
32423  */
32424
32425 /**
32426  * @ngdoc directive
32427  * @name ngDisabled
32428  * @restrict A
32429  * @priority 100
32430  *
32431  * @description
32432  *
32433  * This directive sets the `disabled` attribute on the element if the
32434  * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
32435  *
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.
32438  *
32439  * @example
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>
32444       </file>
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();
32450         });
32451       </file>
32452     </example>
32453  *
32454  * @element INPUT
32455  * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
32456  *     then the `disabled` attribute will be set on the element
32457  */
32458
32459
32460 /**
32461  * @ngdoc directive
32462  * @name ngChecked
32463  * @restrict A
32464  * @priority 100
32465  *
32466  * @description
32467  * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
32468  *
32469  * Note that this directive should not be used together with {@link ngModel `ngModel`},
32470  * as this can lead to unexpected behavior.
32471  *
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.
32474  *
32475  * @example
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">
32480       </file>
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();
32486         });
32487       </file>
32488     </example>
32489  *
32490  * @element INPUT
32491  * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
32492  *     then the `checked` attribute will be set on the element
32493  */
32494
32495
32496 /**
32497  * @ngdoc directive
32498  * @name ngReadonly
32499  * @restrict A
32500  * @priority 100
32501  *
32502  * @description
32503  *
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.
32507  *
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.
32510  *
32511  * @example
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" />
32516       </file>
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();
32522         });
32523       </file>
32524     </example>
32525  *
32526  * @element INPUT
32527  * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
32528  *     then special attribute "readonly" will be set on the element
32529  */
32530
32531
32532 /**
32533  * @ngdoc directive
32534  * @name ngSelected
32535  * @restrict A
32536  * @priority 100
32537  *
32538  * @description
32539  *
32540  * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
32541  *
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.
32544  *
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.
32550  * </div>
32551  *
32552  * @example
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>
32559         </select>
32560       </file>
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();
32566         });
32567       </file>
32568     </example>
32569  *
32570  * @element OPTION
32571  * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
32572  *     then special attribute "selected" will be set on the element
32573  */
32574
32575 /**
32576  * @ngdoc directive
32577  * @name ngOpen
32578  * @restrict A
32579  * @priority 100
32580  *
32581  * @description
32582  *
32583  * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
32584  *
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.
32587  *
32588  * ## A note about browser compatibility
32589  *
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.
32592  *
32593  * @example
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>
32599          </details>
32600        </file>
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();
32606          });
32607        </file>
32608      </example>
32609  *
32610  * @element DETAILS
32611  * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
32612  *     then special attribute "open" will be set on the element
32613  */
32614
32615 var ngAttributeAliasDirectives = {};
32616
32617 // boolean attrs are evaluated
32618 forEach(BOOLEAN_ATTR, function(propName, attrName) {
32619   // binding to multiple is not supported
32620   if (propName === 'multiple') return;
32621
32622   function defaultLinkFn(scope, element, attr) {
32623     scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
32624       attr.$set(attrName, !!value);
32625     });
32626   }
32627
32628   var normalized = directiveNormalize('ng-' + attrName);
32629   var linkFn = defaultLinkFn;
32630
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);
32636       }
32637     };
32638   }
32639
32640   ngAttributeAliasDirectives[normalized] = function() {
32641     return {
32642       restrict: 'A',
32643       priority: 100,
32644       link: linkFn
32645     };
32646   };
32647 });
32648
32649 // aliased input attrs are evaluated
32650 forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
32651   ngAttributeAliasDirectives[ngAttr] = function() {
32652     return {
32653       priority: 100,
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);
32659           if (match) {
32660             attr.$set('ngPattern', new RegExp(match[1], match[2]));
32661             return;
32662           }
32663         }
32664
32665         scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
32666           attr.$set(ngAttr, value);
32667         });
32668       }
32669     };
32670   };
32671 });
32672
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() {
32677     return {
32678       priority: 99, // it needs to run after the attributes are interpolated
32679       link: function(scope, element, attr) {
32680         var propName = attrName,
32681             name = attrName;
32682
32683         if (attrName === 'href' &&
32684             toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
32685           name = 'xlinkHref';
32686           attr.$attr[name] = 'xlink:href';
32687           propName = null;
32688         }
32689
32690         attr.$observe(normalized, function(value) {
32691           if (!value) {
32692             if (attrName === 'href') {
32693               attr.$set(name, null);
32694             }
32695             return;
32696           }
32697
32698           attr.$set(name, value);
32699
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]);
32705         });
32706       }
32707     };
32708   };
32709 });
32710
32711 /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
32712  */
32713 var nullFormCtrl = {
32714   $addControl: noop,
32715   $$renameControl: nullFormRenameControl,
32716   $removeControl: noop,
32717   $setValidity: noop,
32718   $setDirty: noop,
32719   $setPristine: noop,
32720   $setSubmitted: noop
32721 },
32722 SUBMITTED_CLASS = 'ng-submitted';
32723
32724 function nullFormRenameControl(control, name) {
32725   control.$name = name;
32726 }
32727
32728 /**
32729  * @ngdoc type
32730  * @name form.FormController
32731  *
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.
32738  *
32739  * @property {Object} $error Is an object hash, containing references to controls or
32740  *  forms with failing validators, where:
32741  *
32742  *  - keys are validation tokens (error names),
32743  *  - values are arrays of controls or forms that have a failing validator for given error name.
32744  *
32745  *  Built-in validation tokens:
32746  *
32747  *  - `email`
32748  *  - `max`
32749  *  - `maxlength`
32750  *  - `min`
32751  *  - `minlength`
32752  *  - `number`
32753  *  - `pattern`
32754  *  - `required`
32755  *  - `url`
32756  *  - `date`
32757  *  - `datetimelocal`
32758  *  - `time`
32759  *  - `week`
32760  *  - `month`
32761  *
32762  * @description
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.
32765  *
32766  * Each {@link ng.directive:form form} directive creates an instance
32767  * of `FormController`.
32768  *
32769  */
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) {
32773   var form = this,
32774       controls = [];
32775
32776   // init state
32777   form.$error = {};
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;
32787
32788   /**
32789    * @ngdoc method
32790    * @name form.FormController#$rollbackViewValue
32791    *
32792    * @description
32793    * Rollback all form controls pending updates to the `$modelValue`.
32794    *
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.
32798    */
32799   form.$rollbackViewValue = function() {
32800     forEach(controls, function(control) {
32801       control.$rollbackViewValue();
32802     });
32803   };
32804
32805   /**
32806    * @ngdoc method
32807    * @name form.FormController#$commitViewValue
32808    *
32809    * @description
32810    * Commit all form controls pending updates to the `$modelValue`.
32811    *
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.
32815    */
32816   form.$commitViewValue = function() {
32817     forEach(controls, function(control) {
32818       control.$commitViewValue();
32819     });
32820   };
32821
32822   /**
32823    * @ngdoc method
32824    * @name form.FormController#$addControl
32825    * @param {object} control control object, either a {@link form.FormController} or an
32826    * {@link ngModel.NgModelController}
32827    *
32828    * @description
32829    * Register a control with the form. Input elements using ngModelController do this automatically
32830    * when they are linked.
32831    *
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`
32834    * state.
32835    *
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.
32839    *
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.
32842    */
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);
32848
32849     if (control.$name) {
32850       form[control.$name] = control;
32851     }
32852
32853     control.$$parentForm = form;
32854   };
32855
32856   // Private API: rename a form control
32857   form.$$renameControl = function(control, newName) {
32858     var oldName = control.$name;
32859
32860     if (form[oldName] === control) {
32861       delete form[oldName];
32862     }
32863     form[newName] = control;
32864     control.$name = newName;
32865   };
32866
32867   /**
32868    * @ngdoc method
32869    * @name form.FormController#$removeControl
32870    * @param {object} control control object, either a {@link form.FormController} or an
32871    * {@link ngModel.NgModelController}
32872    *
32873    * @description
32874    * Deregister a control from the form.
32875    *
32876    * Input elements using ngModelController do this automatically when they are destroyed.
32877    *
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`.
32882    */
32883   form.$removeControl = function(control) {
32884     if (control.$name && form[control.$name] === control) {
32885       delete form[control.$name];
32886     }
32887     forEach(form.$pending, function(value, name) {
32888       form.$setValidity(name, null, control);
32889     });
32890     forEach(form.$error, function(value, name) {
32891       form.$setValidity(name, null, control);
32892     });
32893     forEach(form.$$success, function(value, name) {
32894       form.$setValidity(name, null, control);
32895     });
32896
32897     arrayRemove(controls, control);
32898     control.$$parentForm = nullFormCtrl;
32899   };
32900
32901
32902   /**
32903    * @ngdoc method
32904    * @name form.FormController#$setValidity
32905    *
32906    * @description
32907    * Sets the validity of a form control.
32908    *
32909    * This method will also propagate to parent forms.
32910    */
32911   addSetValidityMethod({
32912     ctrl: this,
32913     $element: element,
32914     set: function(object, property, controller) {
32915       var list = object[property];
32916       if (!list) {
32917         object[property] = [controller];
32918       } else {
32919         var index = list.indexOf(controller);
32920         if (index === -1) {
32921           list.push(controller);
32922         }
32923       }
32924     },
32925     unset: function(object, property, controller) {
32926       var list = object[property];
32927       if (!list) {
32928         return;
32929       }
32930       arrayRemove(list, controller);
32931       if (list.length === 0) {
32932         delete object[property];
32933       }
32934     },
32935     $animate: $animate
32936   });
32937
32938   /**
32939    * @ngdoc method
32940    * @name form.FormController#$setDirty
32941    *
32942    * @description
32943    * Sets the form to a dirty state.
32944    *
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.
32947    */
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();
32954   };
32955
32956   /**
32957    * @ngdoc method
32958    * @name form.FormController#$setPristine
32959    *
32960    * @description
32961    * Sets the form to its pristine state.
32962    *
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`
32965    * state to false.
32966    *
32967    * This method will also propagate to all the controls contained in this form.
32968    *
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.
32971    */
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();
32979     });
32980   };
32981
32982   /**
32983    * @ngdoc method
32984    * @name form.FormController#$setUntouched
32985    *
32986    * @description
32987    * Sets the form to its untouched state.
32988    *
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).
32991    *
32992    * Setting a form controls back to their untouched state is often useful when setting the form
32993    * back to its pristine state.
32994    */
32995   form.$setUntouched = function() {
32996     forEach(controls, function(control) {
32997       control.$setUntouched();
32998     });
32999   };
33000
33001   /**
33002    * @ngdoc method
33003    * @name form.FormController#$setSubmitted
33004    *
33005    * @description
33006    * Sets the form to its submitted state.
33007    */
33008   form.$setSubmitted = function() {
33009     $animate.addClass(element, SUBMITTED_CLASS);
33010     form.$submitted = true;
33011     form.$$parentForm.$setSubmitted();
33012   };
33013 }
33014
33015 /**
33016  * @ngdoc directive
33017  * @name ngForm
33018  * @restrict EAC
33019  *
33020  * @description
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.
33024  *
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, ...).
33028  *
33029  * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
33030  *                       related scope, under this name.
33031  *
33032  */
33033
33034  /**
33035  * @ngdoc directive
33036  * @name form
33037  * @restrict E
33038  *
33039  * @description
33040  * Directive that instantiates
33041  * {@link form.FormController FormController}.
33042  *
33043  * If the `name` attribute is specified, the form controller is published onto the current scope under
33044  * this name.
33045  *
33046  * # Alias: {@link ng.directive:ngForm `ngForm`}
33047  *
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.
33053  *
33054  * # CSS classes
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.
33061  *
33062  * Keep in mind that ngAnimate can detect each of these classes when added and removed.
33063  *
33064  *
33065  * # Submitting a form and preventing the default action
33066  *
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.
33071  *
33072  * For this reason, Angular prevents the default action (form submission to the server) unless the
33073  * `<form>` element has an `action` attribute specified.
33074  *
33075  * You can use one of the following two ways to specify what javascript method should be called when
33076  * a form is submitted:
33077  *
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])
33081  *
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:
33085  *
33086  * - If a form has only one input field then hitting enter in this field triggers form submit
33087  * (`ngSubmit`)
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`)
33093  *
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.
33097  *
33098  * ## Animation Hooks
33099  *
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.
33105  *
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:
33108  *
33109  * <pre>
33110  * //be sure to include ngAnimate as a module to hook into more
33111  * //advanced animations
33112  * .my-form {
33113  *   transition:0.5s linear all;
33114  *   background: white;
33115  * }
33116  * .my-form.ng-invalid {
33117  *   background: red;
33118  *   color:white;
33119  * }
33120  * </pre>
33121  *
33122  * @example
33123     <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
33124       <file name="index.html">
33125        <script>
33126          angular.module('formExample', [])
33127            .controller('FormController', ['$scope', function($scope) {
33128              $scope.userType = 'guest';
33129            }]);
33130        </script>
33131        <style>
33132         .my-form {
33133           transition:all linear 0.5s;
33134           background: transparent;
33135         }
33136         .my-form.ng-invalid {
33137           background: red;
33138         }
33139        </style>
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>
33148         </form>
33149       </file>
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'));
33154
33155           expect(userType.getText()).toContain('guest');
33156           expect(valid.getText()).toContain('true');
33157         });
33158
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'));
33163
33164           userInput.clear();
33165           userInput.sendKeys('');
33166
33167           expect(userType.getText()).toEqual('userType =');
33168           expect(valid.getText()).toContain('false');
33169         });
33170       </file>
33171     </example>
33172  *
33173  * @param {string=} name Name of the form. If specified, the form controller will be published into
33174  *                       related scope, under this name.
33175  */
33176 var formDirectiveFactory = function(isNgForm) {
33177   return ['$timeout', '$parse', function($timeout, $parse) {
33178     var formDirective = {
33179       name: 'form',
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);
33186
33187         var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
33188
33189         return {
33190           pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
33191             var controller = ctrls[0];
33192
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
33197               //
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();
33205                 });
33206
33207                 event.preventDefault();
33208               };
33209
33210               addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
33211
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);
33217                 }, 0, false);
33218               });
33219             }
33220
33221             var parentFormCtrl = ctrls[1] || controller.$$parentForm;
33222             parentFormCtrl.$addControl(controller);
33223
33224             var setter = nameAttr ? getSetter(controller.$name) : noop;
33225
33226             if (nameAttr) {
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);
33234               });
33235             }
33236             formElement.on('$destroy', function() {
33237               controller.$$parentForm.$removeControl(controller);
33238               setter(scope, undefined);
33239               extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
33240             });
33241           }
33242         };
33243       }
33244     };
33245
33246     return formDirective;
33247
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;
33252       }
33253       return $parse(expression).assign || noop;
33254     }
33255   }];
33256 };
33257
33258 var formDirective = formDirectiveFactory();
33259 var ngFormDirective = formDirectiveFactory(true);
33260
33261 /* global
33262   VALID_CLASS: false,
33263   INVALID_CLASS: false,
33264   PRISTINE_CLASS: false,
33265   DIRTY_CLASS: false,
33266   ngModelMinErr: false
33267 */
33268
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.
33273 //   1. Scheme
33274 //   2. Slashes
33275 //   3. Username
33276 //   4. Password
33277 //   5. Hostname
33278 //   6. Port
33279 //   7. Path
33280 //   8. Query
33281 //   9. Fragment
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})?)?$/;
33292
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;
33297 });
33298
33299 var inputType = {
33300
33301   /**
33302    * @ngdoc input
33303    * @name input[text]
33304    *
33305    * @description
33306    * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
33307    *
33308    *
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
33316    *    minlength.
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
33319    *    any length.
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
33331    *    account.
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
33336    *    input.
33337    *
33338    * @example
33339       <example name="text-input-directive" module="textInputExample">
33340         <file name="index.html">
33341          <script>
33342            angular.module('textInputExample', [])
33343              .controller('ExampleController', ['$scope', function($scope) {
33344                $scope.example = {
33345                  text: 'guest',
33346                  word: /^\s*\w*\s*$/
33347                };
33348              }]);
33349          </script>
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">
33354            </label>
33355            <div role="alert">
33356              <span class="error" ng-show="myForm.input.$error.required">
33357                Required!</span>
33358              <span class="error" ng-show="myForm.input.$error.pattern">
33359                Single word only!</span>
33360            </div>
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/>
33366           </form>
33367         </file>
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'));
33372
33373           it('should initialize to model', function() {
33374             expect(text.getText()).toContain('guest');
33375             expect(valid.getText()).toContain('true');
33376           });
33377
33378           it('should be invalid if empty', function() {
33379             input.clear();
33380             input.sendKeys('');
33381
33382             expect(text.getText()).toEqual('text =');
33383             expect(valid.getText()).toContain('false');
33384           });
33385
33386           it('should be invalid if multi word', function() {
33387             input.clear();
33388             input.sendKeys('hello world');
33389
33390             expect(valid.getText()).toContain('false');
33391           });
33392         </file>
33393       </example>
33394    */
33395   'text': textInputType,
33396
33397     /**
33398      * @ngdoc input
33399      * @name input[date]
33400      *
33401      * @description
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.
33407      *
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.
33410      *
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.
33413      *
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.
33434      *
33435      * @example
33436      <example name="date-input-directive" module="dateInputExample">
33437      <file name="index.html">
33438        <script>
33439           angular.module('dateInputExample', [])
33440             .controller('DateController', ['$scope', function($scope) {
33441               $scope.example = {
33442                 value: new Date(2013, 9, 22)
33443               };
33444             }]);
33445        </script>
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 />
33450           <div role="alert">
33451             <span class="error" ng-show="myForm.input.$error.required">
33452                 Required!</span>
33453             <span class="error" ng-show="myForm.input.$error.date">
33454                 Not a valid date!</span>
33455            </div>
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/>
33461        </form>
33462      </file>
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'));
33466
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);
33476         }
33477
33478         it('should initialize to model', function() {
33479           expect(value.getText()).toContain('2013-10-22');
33480           expect(valid.getText()).toContain('myForm.input.$valid = true');
33481         });
33482
33483         it('should be invalid if empty', function() {
33484           setInput('');
33485           expect(value.getText()).toEqual('value =');
33486           expect(valid.getText()).toContain('myForm.input.$valid = false');
33487         });
33488
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');
33493         });
33494      </file>
33495      </example>
33496      */
33497   'date': createDateInputType('date', DATE_REGEXP,
33498          createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
33499          'yyyy-MM-dd'),
33500
33501    /**
33502     * @ngdoc input
33503     * @name input[datetime-local]
33504     *
33505     * @description
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`.
33509     *
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.
33512     *
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.
33515     *
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.
33536     *
33537     * @example
33538     <example name="datetimelocal-input-directive" module="dateExample">
33539     <file name="index.html">
33540       <script>
33541         angular.module('dateExample', [])
33542           .controller('DateController', ['$scope', function($scope) {
33543             $scope.example = {
33544               value: new Date(2010, 11, 28, 14, 57)
33545             };
33546           }]);
33547       </script>
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 />
33552         <div role="alert">
33553           <span class="error" ng-show="myForm.input.$error.required">
33554               Required!</span>
33555           <span class="error" ng-show="myForm.input.$error.datetimelocal">
33556               Not a valid date!</span>
33557         </div>
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/>
33563       </form>
33564     </file>
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'));
33568
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);
33578       }
33579
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');
33583       });
33584
33585       it('should be invalid if empty', function() {
33586         setInput('');
33587         expect(value.getText()).toEqual('value =');
33588         expect(valid.getText()).toContain('myForm.input.$valid = false');
33589       });
33590
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');
33595       });
33596     </file>
33597     </example>
33598     */
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'),
33602
33603   /**
33604    * @ngdoc input
33605    * @name input[time]
33606    *
33607    * @description
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)`.
33612    *
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.
33615    *
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.
33618    *
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.
33639    *
33640    * @example
33641    <example name="time-input-directive" module="timeExample">
33642    <file name="index.html">
33643      <script>
33644       angular.module('timeExample', [])
33645         .controller('DateController', ['$scope', function($scope) {
33646           $scope.example = {
33647             value: new Date(1970, 0, 1, 14, 57, 0)
33648           };
33649         }]);
33650      </script>
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 />
33655         <div role="alert">
33656           <span class="error" ng-show="myForm.input.$error.required">
33657               Required!</span>
33658           <span class="error" ng-show="myForm.input.$error.time">
33659               Not a valid date!</span>
33660         </div>
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/>
33666      </form>
33667    </file>
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'));
33671
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);
33681       }
33682
33683       it('should initialize to model', function() {
33684         expect(value.getText()).toContain('14:57:00');
33685         expect(valid.getText()).toContain('myForm.input.$valid = true');
33686       });
33687
33688       it('should be invalid if empty', function() {
33689         setInput('');
33690         expect(value.getText()).toEqual('value =');
33691         expect(valid.getText()).toContain('myForm.input.$valid = false');
33692       });
33693
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');
33698       });
33699    </file>
33700    </example>
33701    */
33702   'time': createDateInputType('time', TIME_REGEXP,
33703       createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
33704      'HH:mm:ss.sss'),
33705
33706    /**
33707     * @ngdoc input
33708     * @name input[week]
33709     *
33710     * @description
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`.
33714     *
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.
33717     *
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.
33720     *
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.
33741     *
33742     * @example
33743     <example name="week-input-directive" module="weekExample">
33744     <file name="index.html">
33745       <script>
33746       angular.module('weekExample', [])
33747         .controller('DateController', ['$scope', function($scope) {
33748           $scope.example = {
33749             value: new Date(2013, 0, 3)
33750           };
33751         }]);
33752       </script>
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 />
33758         </label>
33759         <div role="alert">
33760           <span class="error" ng-show="myForm.input.$error.required">
33761               Required!</span>
33762           <span class="error" ng-show="myForm.input.$error.week">
33763               Not a valid date!</span>
33764         </div>
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/>
33770       </form>
33771     </file>
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'));
33775
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);
33785       }
33786
33787       it('should initialize to model', function() {
33788         expect(value.getText()).toContain('2013-W01');
33789         expect(valid.getText()).toContain('myForm.input.$valid = true');
33790       });
33791
33792       it('should be invalid if empty', function() {
33793         setInput('');
33794         expect(value.getText()).toEqual('value =');
33795         expect(valid.getText()).toContain('myForm.input.$valid = false');
33796       });
33797
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');
33802       });
33803     </file>
33804     </example>
33805     */
33806   'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
33807
33808   /**
33809    * @ngdoc input
33810    * @name input[month]
33811    *
33812    * @description
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`.
33816    *
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.
33821    *
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.
33824    *
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.
33839
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.
33846    *
33847    * @example
33848    <example name="month-input-directive" module="monthExample">
33849    <file name="index.html">
33850      <script>
33851       angular.module('monthExample', [])
33852         .controller('DateController', ['$scope', function($scope) {
33853           $scope.example = {
33854             value: new Date(2013, 9, 1)
33855           };
33856         }]);
33857      </script>
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 />
33862        <div role="alert">
33863          <span class="error" ng-show="myForm.input.$error.required">
33864             Required!</span>
33865          <span class="error" ng-show="myForm.input.$error.month">
33866             Not a valid month!</span>
33867        </div>
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/>
33873      </form>
33874    </file>
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'));
33878
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);
33888       }
33889
33890       it('should initialize to model', function() {
33891         expect(value.getText()).toContain('2013-10');
33892         expect(valid.getText()).toContain('myForm.input.$valid = true');
33893       });
33894
33895       it('should be invalid if empty', function() {
33896         setInput('');
33897         expect(value.getText()).toEqual('value =');
33898         expect(valid.getText()).toContain('myForm.input.$valid = false');
33899       });
33900
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');
33905       });
33906    </file>
33907    </example>
33908    */
33909   'month': createDateInputType('month', MONTH_REGEXP,
33910      createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
33911      'yyyy-MM'),
33912
33913   /**
33914    * @ngdoc input
33915    * @name input[number]
33916    *
33917    * @description
33918    * Text input with number validation and transformation. Sets the `number` validation
33919    * error if not a valid number.
33920    *
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.
33925    * </div>
33926    *
33927    * ## Issues with HTML5 constraint validation
33928    *
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.
33935    *
33936    *
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
33946    *    minlength.
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
33949    *    any length.
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
33961    *    account.
33962    * @param {string=} ngChange Angular expression to be executed when input changes due to user
33963    *    interaction with the input element.
33964    *
33965    * @example
33966       <example name="number-input-directive" module="numberExample">
33967         <file name="index.html">
33968          <script>
33969            angular.module('numberExample', [])
33970              .controller('ExampleController', ['$scope', function($scope) {
33971                $scope.example = {
33972                  value: 12
33973                };
33974              }]);
33975          </script>
33976          <form name="myForm" ng-controller="ExampleController">
33977            <label>Number:
33978              <input type="number" name="input" ng-model="example.value"
33979                     min="0" max="99" required>
33980           </label>
33981            <div role="alert">
33982              <span class="error" ng-show="myForm.input.$error.required">
33983                Required!</span>
33984              <span class="error" ng-show="myForm.input.$error.number">
33985                Not valid number!</span>
33986            </div>
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/>
33992           </form>
33993         </file>
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'));
33998
33999           it('should initialize to model', function() {
34000             expect(value.getText()).toContain('12');
34001             expect(valid.getText()).toContain('true');
34002           });
34003
34004           it('should be invalid if empty', function() {
34005             input.clear();
34006             input.sendKeys('');
34007             expect(value.getText()).toEqual('value =');
34008             expect(valid.getText()).toContain('false');
34009           });
34010
34011           it('should be invalid if over max', function() {
34012             input.clear();
34013             input.sendKeys('123');
34014             expect(value.getText()).toEqual('value =');
34015             expect(valid.getText()).toContain('false');
34016           });
34017         </file>
34018       </example>
34019    */
34020   'number': numberInputType,
34021
34022
34023   /**
34024    * @ngdoc input
34025    * @name input[url]
34026    *
34027    * @description
34028    * Text input with URL validation. Sets the `url` validation error key if the content is not a
34029    * valid URL.
34030    *
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})
34035    * </div>
34036    *
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
34044    *    minlength.
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
34047    *    any length.
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
34059    *    account.
34060    * @param {string=} ngChange Angular expression to be executed when input changes due to user
34061    *    interaction with the input element.
34062    *
34063    * @example
34064       <example name="url-input-directive" module="urlExample">
34065         <file name="index.html">
34066          <script>
34067            angular.module('urlExample', [])
34068              .controller('ExampleController', ['$scope', function($scope) {
34069                $scope.url = {
34070                  text: 'http://google.com'
34071                };
34072              }]);
34073          </script>
34074          <form name="myForm" ng-controller="ExampleController">
34075            <label>URL:
34076              <input type="url" name="input" ng-model="url.text" required>
34077            <label>
34078            <div role="alert">
34079              <span class="error" ng-show="myForm.input.$error.required">
34080                Required!</span>
34081              <span class="error" ng-show="myForm.input.$error.url">
34082                Not valid url!</span>
34083            </div>
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/>
34090           </form>
34091         </file>
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'));
34096
34097           it('should initialize to model', function() {
34098             expect(text.getText()).toContain('http://google.com');
34099             expect(valid.getText()).toContain('true');
34100           });
34101
34102           it('should be invalid if empty', function() {
34103             input.clear();
34104             input.sendKeys('');
34105
34106             expect(text.getText()).toEqual('text =');
34107             expect(valid.getText()).toContain('false');
34108           });
34109
34110           it('should be invalid if not url', function() {
34111             input.clear();
34112             input.sendKeys('box');
34113
34114             expect(valid.getText()).toContain('false');
34115           });
34116         </file>
34117       </example>
34118    */
34119   'url': urlInputType,
34120
34121
34122   /**
34123    * @ngdoc input
34124    * @name input[email]
34125    *
34126    * @description
34127    * Text input with email validation. Sets the `email` validation error key if not a valid email
34128    * address.
34129    *
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})
34134    * </div>
34135    *
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
34143    *    minlength.
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
34146    *    any length.
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
34158    *    account.
34159    * @param {string=} ngChange Angular expression to be executed when input changes due to user
34160    *    interaction with the input element.
34161    *
34162    * @example
34163       <example name="email-input-directive" module="emailExample">
34164         <file name="index.html">
34165          <script>
34166            angular.module('emailExample', [])
34167              .controller('ExampleController', ['$scope', function($scope) {
34168                $scope.email = {
34169                  text: 'me@example.com'
34170                };
34171              }]);
34172          </script>
34173            <form name="myForm" ng-controller="ExampleController">
34174              <label>Email:
34175                <input type="email" name="input" ng-model="email.text" required>
34176              </label>
34177              <div role="alert">
34178                <span class="error" ng-show="myForm.input.$error.required">
34179                  Required!</span>
34180                <span class="error" ng-show="myForm.input.$error.email">
34181                  Not valid email!</span>
34182              </div>
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/>
34189            </form>
34190          </file>
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'));
34195
34196           it('should initialize to model', function() {
34197             expect(text.getText()).toContain('me@example.com');
34198             expect(valid.getText()).toContain('true');
34199           });
34200
34201           it('should be invalid if empty', function() {
34202             input.clear();
34203             input.sendKeys('');
34204             expect(text.getText()).toEqual('text =');
34205             expect(valid.getText()).toContain('false');
34206           });
34207
34208           it('should be invalid if not email', function() {
34209             input.clear();
34210             input.sendKeys('xxx');
34211
34212             expect(valid.getText()).toContain('false');
34213           });
34214         </file>
34215       </example>
34216    */
34217   'email': emailInputType,
34218
34219
34220   /**
34221    * @ngdoc input
34222    * @name input[radio]
34223    *
34224    * @description
34225    * HTML radio button.
34226    *
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`, ...).
34237    *
34238    * @example
34239       <example name="radio-input-directive" module="radioExample">
34240         <file name="index.html">
34241          <script>
34242            angular.module('radioExample', [])
34243              .controller('ExampleController', ['$scope', function($scope) {
34244                $scope.color = {
34245                  name: 'blue'
34246                };
34247                $scope.specialValue = {
34248                  "id": "12345",
34249                  "value": "green"
34250                };
34251              }]);
34252          </script>
34253          <form name="myForm" ng-controller="ExampleController">
34254            <label>
34255              <input type="radio" ng-model="color.name" value="red">
34256              Red
34257            </label><br/>
34258            <label>
34259              <input type="radio" ng-model="color.name" ng-value="specialValue">
34260              Green
34261            </label><br/>
34262            <label>
34263              <input type="radio" ng-model="color.name" value="blue">
34264              Blue
34265            </label><br/>
34266            <tt>color = {{color.name | json}}</tt><br/>
34267           </form>
34268           Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
34269         </file>
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'));
34274
34275             expect(color.getText()).toContain('blue');
34276
34277             inputs.get(0).click();
34278             expect(color.getText()).toContain('red');
34279
34280             inputs.get(1).click();
34281             expect(color.getText()).toContain('green');
34282           });
34283         </file>
34284       </example>
34285    */
34286   'radio': radioInputType,
34287
34288   /**
34289    * @ngdoc input
34290    * @name input[range]
34291    *
34292    * @description
34293    * Native range input with validation and transformation.
34294    *
34295    * <div class="alert alert-warning">
34296    *   <p>
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 ... />`
34301    *   </p><br />
34302    *   <p>
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).
34306    *   </p><br />
34307    *   <p>
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.
34310    *   </p><br />
34311    *   <p>
34312    *     This documentation page refers to elements which have the built-in support enabled; i.e.
34313    *     elements _with_ the `ng-input-range` attribute.
34314    *   </p>
34315    * </div>
34316    *
34317    * The model for the range input must always be a `Number`.
34318    *
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.
34322    *
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
34329    * is used.
34330    *
34331    * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))
34332    * for more info.
34333    *
34334    * This has the following consequences for Angular:
34335    *
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.
34341    *
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.
34344    *
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.
34348    *
34349    * Automatic value adjustment also means that a range input element can never have the `required`,
34350    * `min`, or `max` errors.
34351    *
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`.
34356    *
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.
34360    *
34361    * @param           ngInputRange The presense of this attribute enables the built-in support for
34362    *                  `input[range]`.
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.
34376    *
34377    * @example
34378       <example name="range-input-directive" module="rangeExample">
34379         <file name="index.html">
34380           <script>
34381             angular.module('rangeExample', [])
34382               .controller('ExampleController', ['$scope', function($scope) {
34383                 $scope.value = 75;
34384                 $scope.min = 10;
34385                 $scope.max = 90;
34386               }]);
34387           </script>
34388           <form name="myForm" ng-controller="ExampleController">
34389
34390             Model as range: <input type="range" ng-input-range name="range" ng-model="value" min="{{min}}"  max="{{max}}">
34391             <hr>
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>
34398           </form>
34399         </file>
34400       </example>
34401
34402    * ## Range Input with ngMin & ngMax attributes
34403
34404    * @example
34405       <example name="range-input-directive-ng" module="rangeExample">
34406         <file name="index.html">
34407           <script>
34408             angular.module('rangeExample', [])
34409               .controller('ExampleController', ['$scope', function($scope) {
34410                 $scope.value = 75;
34411                 $scope.min = 10;
34412                 $scope.max = 90;
34413               }]);
34414           </script>
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">
34417             <hr>
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>
34424           </form>
34425         </file>
34426       </example>
34427
34428    */
34429   'range': rangeInputType,
34430
34431   /**
34432    * @ngdoc input
34433    * @name input[checkbox]
34434    *
34435    * @description
34436    * HTML checkbox.
34437    *
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.
34444    *
34445    * @example
34446       <example name="checkbox-input-directive" module="checkboxExample">
34447         <file name="index.html">
34448          <script>
34449            angular.module('checkboxExample', [])
34450              .controller('ExampleController', ['$scope', function($scope) {
34451                $scope.checkboxModel = {
34452                 value1 : true,
34453                 value2 : 'YES'
34454               };
34455              }]);
34456          </script>
34457          <form name="myForm" ng-controller="ExampleController">
34458            <label>Value1:
34459              <input type="checkbox" ng-model="checkboxModel.value1">
34460            </label><br/>
34461            <label>Value2:
34462              <input type="checkbox" ng-model="checkboxModel.value2"
34463                     ng-true-value="'YES'" ng-false-value="'NO'">
34464             </label><br/>
34465            <tt>value1 = {{checkboxModel.value1}}</tt><br/>
34466            <tt>value2 = {{checkboxModel.value2}}</tt><br/>
34467           </form>
34468         </file>
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'));
34473
34474             expect(value1.getText()).toContain('true');
34475             expect(value2.getText()).toContain('YES');
34476
34477             element(by.model('checkboxModel.value1')).click();
34478             element(by.model('checkboxModel.value2')).click();
34479
34480             expect(value1.getText()).toContain('false');
34481             expect(value2.getText()).toContain('NO');
34482           });
34483         </file>
34484       </example>
34485    */
34486   'checkbox': checkboxInputType,
34487
34488   'hidden': noop,
34489   'button': noop,
34490   'submit': noop,
34491   'reset': noop,
34492   'file': noop
34493 };
34494
34495 function stringBasedInputType(ctrl) {
34496   ctrl.$formatters.push(function(value) {
34497     return ctrl.$isEmpty(value) ? value : value.toString();
34498   });
34499 }
34500
34501 function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
34502   baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
34503   stringBasedInputType(ctrl);
34504 }
34505
34506 function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
34507   var type = lowercase(element[0].type);
34508
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;
34514
34515     element.on('compositionstart', function() {
34516       composing = true;
34517     });
34518
34519     element.on('compositionend', function() {
34520       composing = false;
34521       listener();
34522     });
34523   }
34524
34525   var timeout;
34526
34527   var listener = function(ev) {
34528     if (timeout) {
34529       $browser.defer.cancel(timeout);
34530       timeout = null;
34531     }
34532     if (composing) return;
34533     var value = element.val(),
34534         event = ev && ev.type;
34535
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);
34541     }
34542
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);
34548     }
34549   };
34550
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);
34555   } else {
34556     var deferListener = function(ev, input, origValue) {
34557       if (!timeout) {
34558         timeout = $browser.defer(function() {
34559           timeout = null;
34560           if (!input || input.value !== origValue) {
34561             listener(ev);
34562           }
34563         });
34564       }
34565     };
34566
34567     element.on('keydown', /** @this */ function(event) {
34568       var key = event.keyCode;
34569
34570       // ignore
34571       //    command            modifiers                   arrows
34572       if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
34573
34574       deferListener(event, this, this.value);
34575     });
34576
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);
34580     }
34581   }
34582
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);
34586
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) {
34593       if (!timeout) {
34594         var validity = this[VALIDITY_STATE_PROPERTY];
34595         var origBadInput = validity.badInput;
34596         var origTypeMismatch = validity.typeMismatch;
34597         timeout = $browser.defer(function() {
34598           timeout = null;
34599           if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
34600             listener(ev);
34601           }
34602         });
34603       }
34604     });
34605   }
34606
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);
34612     }
34613   };
34614 }
34615
34616 function weekParser(isoWeek, existingDate) {
34617   if (isDate(isoWeek)) {
34618     return isoWeek;
34619   }
34620
34621   if (isString(isoWeek)) {
34622     WEEK_REGEXP.lastIndex = 0;
34623     var parts = WEEK_REGEXP.exec(isoWeek);
34624     if (parts) {
34625       var year = +parts[1],
34626           week = +parts[2],
34627           hours = 0,
34628           minutes = 0,
34629           seconds = 0,
34630           milliseconds = 0,
34631           firstThurs = getFirstThursdayOfYear(year),
34632           addDays = (week - 1) * 7;
34633
34634       if (existingDate) {
34635         hours = existingDate.getHours();
34636         minutes = existingDate.getMinutes();
34637         seconds = existingDate.getSeconds();
34638         milliseconds = existingDate.getMilliseconds();
34639       }
34640
34641       return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
34642     }
34643   }
34644
34645   return NaN;
34646 }
34647
34648 function createDateParser(regexp, mapping) {
34649   return function(iso, date) {
34650     var parts, map;
34651
34652     if (isDate(iso)) {
34653       return iso;
34654     }
34655
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);
34662       }
34663       if (ISO_DATE_REGEXP.test(iso)) {
34664         return new Date(iso);
34665       }
34666       regexp.lastIndex = 0;
34667       parts = regexp.exec(iso);
34668
34669       if (parts) {
34670         parts.shift();
34671         if (date) {
34672           map = {
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
34680           };
34681         } else {
34682           map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
34683         }
34684
34685         forEach(parts, function(part, index) {
34686           if (index < mapping.length) {
34687             map[mapping[index]] = +part;
34688           }
34689         });
34690         return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
34691       }
34692     }
34693
34694     return NaN;
34695   };
34696 }
34697
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;
34703     var previousDate;
34704
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);
34713         if (timezone) {
34714           parsedDate = convertTimezoneToLocal(parsedDate, timezone);
34715         }
34716         return parsedDate;
34717       }
34718       return undefined;
34719     });
34720
34721     ctrl.$formatters.push(function(value) {
34722       if (value && !isDate(value)) {
34723         throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
34724       }
34725       if (isValidDate(value)) {
34726         previousDate = value;
34727         if (previousDate && timezone) {
34728           previousDate = convertTimezoneToLocal(previousDate, timezone, true);
34729         }
34730         return $filter('date')(value, format, timezone);
34731       } else {
34732         previousDate = null;
34733         return '';
34734       }
34735     });
34736
34737     if (isDefined(attr.min) || attr.ngMin) {
34738       var minVal;
34739       ctrl.$validators.min = function(value) {
34740         return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
34741       };
34742       attr.$observe('min', function(val) {
34743         minVal = parseObservedDateValue(val);
34744         ctrl.$validate();
34745       });
34746     }
34747
34748     if (isDefined(attr.max) || attr.ngMax) {
34749       var maxVal;
34750       ctrl.$validators.max = function(value) {
34751         return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
34752       };
34753       attr.$observe('max', function(val) {
34754         maxVal = parseObservedDateValue(val);
34755         ctrl.$validate();
34756       });
34757     }
34758
34759     function isValidDate(value) {
34760       // Invalid Date: getTime() returns NaN
34761       return value && !(value.getTime && value.getTime() !== value.getTime());
34762     }
34763
34764     function parseObservedDateValue(val) {
34765       return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
34766     }
34767   };
34768 }
34769
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;
34777     });
34778   }
34779 }
34780
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);
34786     return undefined;
34787   });
34788
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);
34793       }
34794       value = value.toString();
34795     }
34796     return value;
34797   });
34798 }
34799
34800 function parseNumberAttrVal(val) {
34801   if (isDefined(val) && !isNumber(val)) {
34802     val = parseFloat(val);
34803   }
34804   return !isNumberNaN(val) ? val : undefined;
34805 }
34806
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)
34810
34811   // eslint-disable-next-line no-bitwise
34812   return (num | 0) === num;
34813 }
34814
34815 function countDecimals(num) {
34816   var numString = num.toString();
34817   var decimalSymbolIndex = numString.indexOf('.');
34818
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);
34823
34824       if (match) {
34825         return Number(match[1]);
34826       }
34827     }
34828
34829     return 0;
34830   }
34831
34832   return numString.length - decimalSymbolIndex - 1;
34833 }
34834
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);
34839
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);
34845
34846     value = value * multiplier;
34847     stepBase = stepBase * multiplier;
34848     step = step * multiplier;
34849   }
34850
34851   return (value - stepBase) % step === 0;
34852 }
34853
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);
34858
34859   var minVal;
34860   var maxVal;
34861
34862   if (isDefined(attr.min) || attr.ngMin) {
34863     ctrl.$validators.min = function(value) {
34864       return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
34865     };
34866
34867     attr.$observe('min', function(val) {
34868       minVal = parseNumberAttrVal(val);
34869       // TODO(matsko): implement validateLater to reduce number of validations
34870       ctrl.$validate();
34871     });
34872   }
34873
34874   if (isDefined(attr.max) || attr.ngMax) {
34875     ctrl.$validators.max = function(value) {
34876       return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
34877     };
34878
34879     attr.$observe('max', function(val) {
34880       maxVal = parseNumberAttrVal(val);
34881       // TODO(matsko): implement validateLater to reduce number of validations
34882       ctrl.$validate();
34883     });
34884   }
34885 }
34886
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);
34891
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);
34900
34901   var originalRender = ctrl.$render;
34902
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() {
34907       originalRender();
34908       ctrl.$setViewValue(element.val());
34909     } :
34910     originalRender;
34911
34912   if (hasMinAttr) {
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;
34919       };
34920
34921     setInitialValueAndObserver('min', minChange);
34922   }
34923
34924   if (hasMaxAttr) {
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;
34931       };
34932
34933     setInitialValueAndObserver('max', maxChange);
34934   }
34935
34936   if (hasStepAttr) {
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;
34943       } :
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);
34948       };
34949
34950     setInitialValueAndObserver('step', stepChange);
34951   }
34952
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);
34959   }
34960
34961   function minChange(val) {
34962     minVal = parseNumberAttrVal(val);
34963     // ignore changes before model is initialized
34964     if (isNumberNaN(ctrl.$modelValue)) {
34965       return;
34966     }
34967
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) {
34972         elVal = minVal;
34973         element.val(elVal);
34974       }
34975       ctrl.$setViewValue(elVal);
34976     } else {
34977       // TODO(matsko): implement validateLater to reduce number of validations
34978       ctrl.$validate();
34979     }
34980   }
34981
34982   function maxChange(val) {
34983     maxVal = parseNumberAttrVal(val);
34984     // ignore changes before model is initialized
34985     if (isNumberNaN(ctrl.$modelValue)) {
34986       return;
34987     }
34988
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;
34996       }
34997       ctrl.$setViewValue(elVal);
34998     } else {
34999       // TODO(matsko): implement validateLater to reduce number of validations
35000       ctrl.$validate();
35001     }
35002   }
35003
35004   function stepChange(val) {
35005     stepVal = parseNumberAttrVal(val);
35006     // ignore changes before model is initialized
35007     if (isNumberNaN(ctrl.$modelValue)) {
35008       return;
35009     }
35010
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());
35014     } else {
35015       // TODO(matsko): implement validateLater to reduce number of validations
35016       ctrl.$validate();
35017     }
35018   }
35019 }
35020
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);
35026
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);
35031   };
35032 }
35033
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);
35039
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);
35044   };
35045 }
35046
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());
35051   }
35052
35053   var listener = function(ev) {
35054     if (element[0].checked) {
35055       ctrl.$setViewValue(attr.value, ev && ev.type);
35056     }
35057   };
35058
35059   element.on('click', listener);
35060
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);
35066   };
35067
35068   attr.$observe('value', ctrl.$render);
35069 }
35070
35071 function parseConstantExpr($parse, context, name, expression, fallback) {
35072   var parseFn;
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);
35078     }
35079     return parseFn(context);
35080   }
35081   return fallback;
35082 }
35083
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);
35087
35088   var listener = function(ev) {
35089     ctrl.$setViewValue(element[0].checked, ev && ev.type);
35090   };
35091
35092   element.on('click', listener);
35093
35094   ctrl.$render = function() {
35095     element[0].checked = ctrl.$viewValue;
35096   };
35097
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;
35103   };
35104
35105   ctrl.$formatters.push(function(value) {
35106     return equals(value, trueValue);
35107   });
35108
35109   ctrl.$parsers.push(function(value) {
35110     return value ? trueValue : falseValue;
35111   });
35112 }
35113
35114
35115 /**
35116  * @ngdoc directive
35117  * @name textarea
35118  * @restrict E
35119  *
35120  * @description
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}.
35124  *
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
35132  *    minlength.
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
35135  *    length.
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
35144  *    account.
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.
35148  *
35149  * @knownIssue
35150  *
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.
35156  *
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
35161  * Developer Guide.
35162  */
35163
35164
35165 /**
35166  * @ngdoc directive
35167  * @name input
35168  * @restrict E
35169  *
35170  * @description
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.
35174  *
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]`.
35178  * </div>
35179  *
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
35185  *    minlength.
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
35188  *    length.
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
35197  *    account.
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
35202  *    input.
35203  *
35204  * @example
35205     <example name="input-directive" module="inputExample">
35206       <file name="index.html">
35207        <script>
35208           angular.module('inputExample', [])
35209             .controller('ExampleController', ['$scope', function($scope) {
35210               $scope.user = {name: 'guest', last: 'visitor'};
35211             }]);
35212        </script>
35213        <div ng-controller="ExampleController">
35214          <form name="myForm">
35215            <label>
35216               User name:
35217               <input type="text" name="userName" ng-model="user.name" required>
35218            </label>
35219            <div role="alert">
35220              <span class="error" ng-show="myForm.userName.$error.required">
35221               Required!</span>
35222            </div>
35223            <label>
35224               Last name:
35225               <input type="text" name="lastName" ng-model="user.last"
35226               ng-minlength="3" ng-maxlength="10">
35227            </label>
35228            <div role="alert">
35229              <span class="error" ng-show="myForm.lastName.$error.minlength">
35230                Too short!</span>
35231              <span class="error" ng-show="myForm.lastName.$error.maxlength">
35232                Too long!</span>
35233            </div>
35234          </form>
35235          <hr>
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/>
35245        </div>
35246       </file>
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'));
35255
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');
35260         });
35261
35262         it('should be invalid if empty when required', function() {
35263           userNameInput.clear();
35264           userNameInput.sendKeys('');
35265
35266           expect(user.getText()).toContain('{"last":"visitor"}');
35267           expect(userNameValid.getText()).toContain('false');
35268           expect(formValid.getText()).toContain('false');
35269         });
35270
35271         it('should be valid if empty when min length is set', function() {
35272           userLastInput.clear();
35273           userLastInput.sendKeys('');
35274
35275           expect(user.getText()).toContain('{"name":"guest","last":""}');
35276           expect(lastNameValid.getText()).toContain('true');
35277           expect(formValid.getText()).toContain('true');
35278         });
35279
35280         it('should be invalid if less than required min length', function() {
35281           userLastInput.clear();
35282           userLastInput.sendKeys('xx');
35283
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');
35288         });
35289
35290         it('should be invalid if longer than max length', function() {
35291           userLastInput.clear();
35292           userLastInput.sendKeys('some ridiculously long name');
35293
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');
35298         });
35299       </file>
35300     </example>
35301  */
35302 var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
35303     function($browser, $sniffer, $filter, $parse) {
35304   return {
35305     restrict: 'E',
35306     require: ['?ngModel'],
35307     link: {
35308       pre: function(scope, element, attr, ctrls) {
35309         if (ctrls[0]) {
35310           var type = lowercase(attr.type);
35311           if ((type === 'range') && !attr.hasOwnProperty('ngInputRange')) {
35312             type = 'text';
35313           }
35314           (inputType[type] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
35315                                                               $browser, $filter, $parse);
35316         }
35317       }
35318     }
35319   };
35320 }];
35321
35322
35323
35324 var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
35325 /**
35326  * @ngdoc directive
35327  * @name ngValue
35328  *
35329  * @description
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
35332  * the bound value.
35333  *
35334  * `ngValue` is useful when dynamically generating lists of radio buttons using
35335  * {@link ngRepeat `ngRepeat`}, as shown below.
35336  *
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`.
35341  *
35342  * @element input
35343  * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
35344  *   of the `input` element
35345  *
35346  * @example
35347     <example name="ngValue-directive" module="valueExample">
35348       <file name="index.html">
35349        <script>
35350           angular.module('valueExample', [])
35351             .controller('ExampleController', ['$scope', function($scope) {
35352               $scope.names = ['pizza', 'unicorns', 'robots'];
35353               $scope.my = { favorite: 'unicorns' };
35354             }]);
35355        </script>
35356         <form ng-controller="ExampleController">
35357           <h2>Which is your favorite?</h2>
35358             <label ng-repeat="name in names" for="{{name}}">
35359               {{name}}
35360               <input type="radio"
35361                      ng-model="my.favorite"
35362                      ng-value="name"
35363                      id="{{name}}"
35364                      name="favorite">
35365             </label>
35366           <div>You chose {{my.favorite}}</div>
35367         </form>
35368       </file>
35369       <file name="protractor.js" type="protractor">
35370         var favorite = element(by.binding('my.favorite'));
35371
35372         it('should initialize to model', function() {
35373           expect(favorite.getText()).toContain('unicorns');
35374         });
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');
35378         });
35379       </file>
35380     </example>
35381  */
35382 var ngValueDirective = function() {
35383   return {
35384     restrict: 'A',
35385     priority: 100,
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));
35390         };
35391       } else {
35392         return function ngValueLink(scope, elm, attr) {
35393           scope.$watch(attr.ngValue, function valueWatchAction(value) {
35394             attr.$set('value', value);
35395           });
35396         };
35397       }
35398     }
35399   };
35400 };
35401
35402 /**
35403  * @ngdoc directive
35404  * @name ngBind
35405  * @restrict AC
35406  *
35407  * @description
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.
35411  *
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.
35414  *
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.
35418  *
35419  * An alternative solution to this problem would be using the
35420  * {@link ng.directive:ngCloak ngCloak} directive.
35421  *
35422  *
35423  * @element ANY
35424  * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
35425  *
35426  * @example
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">
35430        <script>
35431          angular.module('bindExample', [])
35432            .controller('ExampleController', ['$scope', function($scope) {
35433              $scope.name = 'Whirled';
35434            }]);
35435        </script>
35436        <div ng-controller="ExampleController">
35437          <label>Enter name: <input type="text" ng-model="name"></label><br>
35438          Hello <span ng-bind="name"></span>!
35439        </div>
35440      </file>
35441      <file name="protractor.js" type="protractor">
35442        it('should check ng-bind', function() {
35443          var nameInput = element(by.model('name'));
35444
35445          expect(element(by.binding('name')).getText()).toBe('Whirled');
35446          nameInput.clear();
35447          nameInput.sendKeys('world');
35448          expect(element(by.binding('name')).getText()).toBe('world');
35449        });
35450      </file>
35451    </example>
35452  */
35453 var ngBindDirective = ['$compile', function($compile) {
35454   return {
35455     restrict: 'AC',
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;
35463         });
35464       };
35465     }
35466   };
35467 }];
35468
35469
35470 /**
35471  * @ngdoc directive
35472  * @name ngBindTemplate
35473  *
35474  * @description
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.
35481  *
35482  * @element ANY
35483  * @param {string} ngBindTemplate template of form
35484  *   <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
35485  *
35486  * @example
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">
35490        <script>
35491          angular.module('bindExample', [])
35492            .controller('ExampleController', ['$scope', function($scope) {
35493              $scope.salutation = 'Hello';
35494              $scope.name = 'World';
35495            }]);
35496        </script>
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>
35501        </div>
35502      </file>
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'));
35508
35509          expect(salutationElem.getText()).toBe('Hello World!');
35510
35511          salutationInput.clear();
35512          salutationInput.sendKeys('Greetings');
35513          nameInput.clear();
35514          nameInput.sendKeys('user');
35515
35516          expect(salutationElem.getText()).toBe('Greetings user!');
35517        });
35518      </file>
35519    </example>
35520  */
35521 var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
35522   return {
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;
35531         });
35532       };
35533     }
35534   };
35535 }];
35536
35537
35538 /**
35539  * @ngdoc directive
35540  * @name ngBindHtml
35541  *
35542  * @description
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.
35548  *
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)}.
35552  *
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.)
35555  *
35556  * @element ANY
35557  * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
35558  *
35559  * @example
35560
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>
35565        </div>
35566      </file>
35567
35568      <file name="script.js">
35569        angular.module('bindHtmlExample', ['ngSanitize'])
35570          .controller('ExampleController', ['$scope', function($scope) {
35571            $scope.myHTML =
35572               'I am an <code>HTML</code>string with ' +
35573               '<a href="#">links!</a> and other <em>stuff</em>';
35574          }]);
35575      </file>
35576
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');
35581        });
35582      </file>
35583    </example>
35584  */
35585 var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
35586   return {
35587     restrict: 'A',
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);
35593       });
35594       $compile.$$addBindingClass(tElement);
35595
35596       return function ngBindHtmlLink(scope, element, attr) {
35597         $compile.$$addBindingInfo(element, attr.ngBindHtml);
35598
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) || '');
35603         });
35604       };
35605     }
35606   };
35607 }];
35608
35609 /**
35610  * @ngdoc directive
35611  * @name ngChange
35612  *
35613  * @description
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).
35618  *
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.
35621  *
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
35626  *
35627  *
35628  * Note, this directive requires `ngModel` to be present.
35629  *
35630  * @element input
35631  * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
35632  * in input value.
35633  *
35634  * @example
35635  * <example name="ngChange-directive" module="changeExample">
35636  *   <file name="index.html">
35637  *     <script>
35638  *       angular.module('changeExample', [])
35639  *         .controller('ExampleController', ['$scope', function($scope) {
35640  *           $scope.counter = 0;
35641  *           $scope.change = function() {
35642  *             $scope.counter++;
35643  *           };
35644  *         }]);
35645  *     </script>
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/>
35652  *     </div>
35653  *   </file>
35654  *   <file name="protractor.js" type="protractor">
35655  *     var counter = element(by.binding('counter'));
35656  *     var debug = element(by.binding('confirmed'));
35657  *
35658  *     it('should evaluate the expression if changing from view', function() {
35659  *       expect(counter.getText()).toContain('0');
35660  *
35661  *       element(by.id('ng-change-example1')).click();
35662  *
35663  *       expect(counter.getText()).toContain('1');
35664  *       expect(debug.getText()).toContain('true');
35665  *     });
35666  *
35667  *     it('should not evaluate the expression if changing from model', function() {
35668  *       element(by.id('ng-change-example2')).click();
35669
35670  *       expect(counter.getText()).toContain('0');
35671  *       expect(debug.getText()).toContain('true');
35672  *     });
35673  *   </file>
35674  * </example>
35675  */
35676 var ngChangeDirective = valueFn({
35677   restrict: 'A',
35678   require: 'ngModel',
35679   link: function(scope, element, attr, ctrl) {
35680     ctrl.$viewChangeListeners.push(function() {
35681       scope.$eval(attr.ngChange);
35682     });
35683   }
35684 });
35685
35686 /* exported
35687   ngClassDirective,
35688   ngClassEvenDirective,
35689   ngClassOddDirective
35690 */
35691
35692 function classDirective(name, selector) {
35693   name = 'ngClass' + name;
35694   return ['$animate', function($animate) {
35695     return {
35696       restrict: 'AC',
35697       link: function(scope, element, attr) {
35698         var oldVal;
35699
35700         attr.$observe('class', function(value) {
35701           ngClassWatchAction(scope.$eval(attr[name]));
35702         });
35703
35704
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);
35713               } else {
35714                 removeClasses(classes);
35715               }
35716             }
35717             /* eslint-enable */
35718           });
35719         }
35720
35721         scope.$watch(attr[name], ngClassWatchAction, true);
35722
35723         function addClasses(classes) {
35724           var newClasses = digestClassCounts(classes, 1);
35725           attr.$addClass(newClasses);
35726         }
35727
35728         function removeClasses(classes) {
35729           var newClasses = digestClassCounts(classes, -1);
35730           attr.$removeClass(newClasses);
35731         }
35732
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);
35743               }
35744             }
35745           });
35746           element.data('$classCounts', classCounts);
35747           return classesToUpdate.join(' ');
35748         }
35749
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);
35757           }
35758           if (toRemove && toRemove.length) {
35759             $animate.removeClass(element, toRemove);
35760           }
35761         }
35762
35763         function ngClassWatchAction(newVal) {
35764           // eslint-disable-next-line no-bitwise
35765           if (selector === true || (scope.$index & 1) === selector) {
35766             var newClasses = arrayClasses(newVal || []);
35767             if (!oldVal) {
35768               addClasses(newClasses);
35769             } else if (!equals(newVal,oldVal)) {
35770               var oldClasses = arrayClasses(oldVal);
35771               updateClasses(oldClasses, newClasses);
35772             }
35773           }
35774           if (isArray(newVal)) {
35775             oldVal = newVal.map(function(v) { return shallowCopy(v); });
35776           } else {
35777             oldVal = shallowCopy(newVal);
35778           }
35779         }
35780       }
35781     };
35782
35783     function arrayDifference(tokens1, tokens2) {
35784       var values = [];
35785
35786       outer:
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;
35791         }
35792         values.push(token);
35793       }
35794       return values;
35795     }
35796
35797     function arrayClasses(classVal) {
35798       var classes = [];
35799       if (isArray(classVal)) {
35800         forEach(classVal, function(v) {
35801           classes = classes.concat(arrayClasses(v));
35802         });
35803         return classes;
35804       } else if (isString(classVal)) {
35805         return classVal.split(' ');
35806       } else if (isObject(classVal)) {
35807         forEach(classVal, function(v, k) {
35808           if (v) {
35809             classes = classes.concat(k.split(' '));
35810           }
35811         });
35812         return classes;
35813       }
35814       return classVal;
35815     }
35816   }];
35817 }
35818
35819 /**
35820  * @ngdoc directive
35821  * @name ngClass
35822  * @restrict AC
35823  *
35824  * @description
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.
35827  *
35828  * The directive operates in three different ways, depending on which of three types the expression
35829  * evaluates to:
35830  *
35831  * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
35832  * names.
35833  *
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.
35836  *
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.
35840  *
35841  *
35842  * The directive won't add duplicate classes if a particular class was already set.
35843  *
35844  * When the expression changes, the previously added classes are removed and only then are the
35845  * new classes added.
35846  *
35847  * @knownIssue
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.
35851  *
35852  * @animations
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 |
35857  *
35858  * @element ANY
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
35863  *   element.
35864  *
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>
35869        <label>
35870           <input type="checkbox" ng-model="deleted">
35871           deleted (apply "strike" class)
35872        </label><br>
35873        <label>
35874           <input type="checkbox" ng-model="important">
35875           important (apply "bold" class)
35876        </label><br>
35877        <label>
35878           <input type="checkbox" ng-model="error">
35879           error (apply "has-error" class)
35880        </label>
35881        <hr>
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">
35885        <hr>
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>
35893        <hr>
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>
35897      </file>
35898      <file name="style.css">
35899        .strike {
35900            text-decoration: line-through;
35901        }
35902        .bold {
35903            font-weight: bold;
35904        }
35905        .red {
35906            color: red;
35907        }
35908        .has-error {
35909            color: red;
35910            background-color: yellow;
35911        }
35912        .orange {
35913            color: orange;
35914        }
35915      </file>
35916      <file name="protractor.js" type="protractor">
35917        var ps = element.all(by.css('p'));
35918
35919        it('should let you toggle the class', function() {
35920
35921          expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
35922          expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
35923
35924          element(by.model('important')).click();
35925          expect(ps.first().getAttribute('class')).toMatch(/bold/);
35926
35927          element(by.model('error')).click();
35928          expect(ps.first().getAttribute('class')).toMatch(/has-error/);
35929        });
35930
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');
35936        });
35937
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');
35944        });
35945
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');
35951        });
35952      </file>
35953    </example>
35954
35955    ## Animations
35956
35957    The example below demonstrates how to perform animations using ngClass.
35958
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=''">
35963       <br>
35964       <span class="base-class" ng-class="myVar">Sample Text</span>
35965      </file>
35966      <file name="style.css">
35967        .base-class {
35968          transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
35969        }
35970
35971        .base-class.my-class {
35972          color: red;
35973          font-size:3em;
35974        }
35975      </file>
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/);
35980
35981          element(by.id('setbtn')).click();
35982
35983          expect(element(by.css('.base-class')).getAttribute('class')).
35984            toMatch(/my-class/);
35985
35986          element(by.id('clearbtn')).click();
35987
35988          expect(element(by.css('.base-class')).getAttribute('class')).not.
35989            toMatch(/my-class/);
35990        });
35991      </file>
35992    </example>
35993
35994
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}.
36001  */
36002 var ngClassDirective = classDirective('', true);
36003
36004 /**
36005  * @ngdoc directive
36006  * @name ngClassOdd
36007  * @restrict AC
36008  *
36009  * @description
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.
36013  *
36014  * This directive can be applied only within the scope of an
36015  * {@link ng.directive:ngRepeat ngRepeat}.
36016  *
36017  * @element ANY
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.
36020  *
36021  * @example
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'">
36027              {{name}}
36028            </span>
36029           </li>
36030         </ol>
36031      </file>
36032      <file name="style.css">
36033        .odd {
36034          color: red;
36035        }
36036        .even {
36037          color: blue;
36038        }
36039      </file>
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')).
36043            toMatch(/odd/);
36044          expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
36045            toMatch(/even/);
36046        });
36047      </file>
36048    </example>
36049  */
36050 var ngClassOddDirective = classDirective('Odd', 0);
36051
36052 /**
36053  * @ngdoc directive
36054  * @name ngClassEven
36055  * @restrict AC
36056  *
36057  * @description
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.
36061  *
36062  * This directive can be applied only within the scope of an
36063  * {@link ng.directive:ngRepeat ngRepeat}.
36064  *
36065  * @element ANY
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.
36068  *
36069  * @example
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}} &nbsp; &nbsp; &nbsp;
36076            </span>
36077           </li>
36078         </ol>
36079      </file>
36080      <file name="style.css">
36081        .odd {
36082          color: red;
36083        }
36084        .even {
36085          color: blue;
36086        }
36087      </file>
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')).
36091            toMatch(/odd/);
36092          expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
36093            toMatch(/even/);
36094        });
36095      </file>
36096    </example>
36097  */
36098 var ngClassEvenDirective = classDirective('Even', 1);
36099
36100 /**
36101  * @ngdoc directive
36102  * @name ngCloak
36103  * @restrict AC
36104  *
36105  * @description
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.
36109  *
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.
36113  *
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}).
36117  *
36118  * ```css
36119  * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
36120  *   display: none !important;
36121  * }
36122  * ```
36123  *
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.
36128  *
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
36131  * application.
36132  *
36133  * @element ANY
36134  *
36135  * @example
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>
36140      </file>
36141      <file name="protractor.js" type="protractor">
36142        it('should remove the template directive and css class', function() {
36143          expect($('#template1').getAttribute('ng-cloak')).
36144            toBeNull();
36145          expect($('#template2').getAttribute('ng-cloak')).
36146            toBeNull();
36147        });
36148      </file>
36149    </example>
36150  *
36151  */
36152 var ngCloakDirective = ngDirective({
36153   compile: function(element, attr) {
36154     attr.$set('ngCloak', undefined);
36155     element.removeClass('ng-cloak');
36156   }
36157 });
36158
36159 /**
36160  * @ngdoc directive
36161  * @name ngController
36162  *
36163  * @description
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.
36166  *
36167  * MVC components in angular:
36168  *
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
36174  *
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.
36179  *
36180  * @element ANY
36181  * @scope
36182  * @priority 500
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.
36186  *
36187  * The controller instance can be published into a scope property by specifying
36188  * `ng-controller="as propertyName"`.
36189  *
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).
36193  *
36194  * @example
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.
36199  *
36200  * Two different declaration styles are included below:
36201  *
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"`
36206  *
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.
36210  *
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.
36217  *
36218  * This example demonstrates the `controller as` syntax.
36219  *
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/>
36225  *      Contact:
36226  *      <ul>
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>
36231  *          </select>
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>
36235  *        </li>
36236  *        <li><button ng-click="settings.addContact()">add</button></li>
36237  *     </ul>
36238  *    </div>
36239  *   </file>
36240  *   <file name="app.js">
36241  *    angular.module('controllerAsExample', [])
36242  *      .controller('SettingsController1', SettingsController1);
36243  *
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'}
36249  *      ];
36250  *    }
36251  *
36252  *    SettingsController1.prototype.greet = function() {
36253  *      alert(this.name);
36254  *    };
36255  *
36256  *    SettingsController1.prototype.addContact = function() {
36257  *      this.contacts.push({type: 'email', value: 'yourname@example.org'});
36258  *    };
36259  *
36260  *    SettingsController1.prototype.removeContact = function(contactToRemove) {
36261  *     var index = this.contacts.indexOf(contactToRemove);
36262  *      this.contacts.splice(index, 1);
36263  *    };
36264  *
36265  *    SettingsController1.prototype.clearContact = function(contact) {
36266  *      contact.type = 'phone';
36267  *      contact.value = '';
36268  *    };
36269  *   </file>
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');
36275  *
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));
36280  *
36281  *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
36282  *           .toBe('408 555 1212');
36283  *
36284  *       expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
36285  *           .toBe('john.smith@example.org');
36286  *
36287  *       firstRepeat.element(by.buttonText('clear')).click();
36288  *
36289  *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
36290  *           .toBe('');
36291  *
36292  *       container.element(by.buttonText('add')).click();
36293  *
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');
36298  *     });
36299  *   </file>
36300  * </example>
36301  *
36302  * This example demonstrates the "attach to `$scope`" style of controller.
36303  *
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/>
36309  *     Contact:
36310  *     <ul>
36311  *       <li ng-repeat="contact in contacts">
36312  *         <select ng-model="contact.type" id="select_{{$index}}">
36313  *            <option>phone</option>
36314  *            <option>email</option>
36315  *         </select>
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>
36319  *       </li>
36320  *       <li>[ <button ng-click="addContact()">add</button> ]</li>
36321  *    </ul>
36322  *   </div>
36323  *  </file>
36324  *  <file name="app.js">
36325  *   angular.module('controllerExample', [])
36326  *     .controller('SettingsController2', ['$scope', SettingsController2]);
36327  *
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'}
36333  *     ];
36334  *
36335  *     $scope.greet = function() {
36336  *       alert($scope.name);
36337  *     };
36338  *
36339  *     $scope.addContact = function() {
36340  *       $scope.contacts.push({type:'email', value:'yourname@example.org'});
36341  *     };
36342  *
36343  *     $scope.removeContact = function(contactToRemove) {
36344  *       var index = $scope.contacts.indexOf(contactToRemove);
36345  *       $scope.contacts.splice(index, 1);
36346  *     };
36347  *
36348  *     $scope.clearContact = function(contact) {
36349  *       contact.type = 'phone';
36350  *       contact.value = '';
36351  *     };
36352  *   }
36353  *  </file>
36354  *  <file name="protractor.js" type="protractor">
36355  *    it('should check controller', function() {
36356  *      var container = element(by.id('ctrl-exmpl'));
36357  *
36358  *      expect(container.element(by.model('name'))
36359  *          .getAttribute('value')).toBe('John Smith');
36360  *
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));
36365  *
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');
36370  *
36371  *      firstRepeat.element(by.buttonText('clear')).click();
36372  *
36373  *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
36374  *          .toBe('');
36375  *
36376  *      container.element(by.buttonText('add')).click();
36377  *
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');
36382  *    });
36383  *  </file>
36384  *</example>
36385
36386  */
36387 var ngControllerDirective = [function() {
36388   return {
36389     restrict: 'A',
36390     scope: true,
36391     controller: '@',
36392     priority: 500
36393   };
36394 }];
36395
36396 /**
36397  * @ngdoc directive
36398  * @name ngCsp
36399  *
36400  * @restrict A
36401  * @element ANY
36402  * @description
36403  *
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.
36406  *
36407  * If you intend to implement CSP with these rules then you must tell Angular not to use these
36408  * features.
36409  *
36410  * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
36411  *
36412  *
36413  * The following default rules in CSP affect Angular:
36414  *
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.)
36420  *
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.)
36427  *
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:
36432  *
36433  * ```
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.
36437  * ```
36438  *
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.
36442  *
36443  * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
36444  *
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:
36447  *
36448  * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
36449  *
36450  * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
36451  *
36452  * You can use these values in the following combinations:
36453  *
36454  *
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.
36458  *
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.
36462  *
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">`.
36465  *
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">`
36468  *
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">`
36472  *
36473  * @example
36474  * This example shows how to apply the `ngCsp` directive to the `html` tag.
36475    ```html
36476      <!doctype html>
36477      <html ng-app ng-csp>
36478      ...
36479      ...
36480      </html>
36481    ```
36482   * @example
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">
36487             <div>
36488               <button ng-click="ctrl.inc()" id="inc">Increment</button>
36489               <span id="counter">
36490                 {{ctrl.counter}}
36491               </span>
36492             </div>
36493
36494             <div>
36495               <button ng-click="ctrl.evil()" id="evil">Evil</button>
36496               <span id="evilError">
36497                 {{ctrl.evilError}}
36498               </span>
36499             </div>
36500           </div>
36501         </file>
36502         <file name="script.js">
36503            angular.module('cspExample', [])
36504              .controller('MainController', function MainController() {
36505                 this.counter = 0;
36506                 this.inc = function() {
36507                   this.counter++;
36508                 };
36509                 this.evil = function() {
36510                   try {
36511                     eval('1+2'); // eslint-disable-line no-eval
36512                   } catch (e) {
36513                     this.evilError = e.message;
36514                   }
36515                 };
36516               });
36517         </file>
36518         <file name="protractor.js" type="protractor">
36519           var util, webdriver;
36520
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'));
36525
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;
36530               });
36531             });
36532           }
36533
36534           function clearErrors() {
36535             getAndClearSevereErrors();
36536           }
36537
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));
36543               }
36544             });
36545           }
36546
36547           function expectError(regex) {
36548             getAndClearSevereErrors().then(function(filteredLog) {
36549               var found = false;
36550               filteredLog.forEach(function(log) {
36551                 if (log.message.match(regex)) {
36552                   found = true;
36553                 }
36554               });
36555               if (!found) {
36556                 throw new Error('expected an error that matches ' + regex);
36557               }
36558             });
36559           }
36560
36561           beforeEach(function() {
36562             util = require('util');
36563             webdriver = require('selenium-webdriver');
36564           });
36565
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') {
36570             return;
36571           }
36572
36573           it('should not report errors when the page is loaded', function() {
36574             // clear errors so we are not dependent on previous tests
36575             clearErrors();
36576             // Need to reload the page as the page is already loaded when
36577             // we come here
36578             browser.driver.getCurrentUrl().then(function(url) {
36579               browser.get(url);
36580             });
36581             expectNoErrors();
36582           });
36583
36584           it('should evaluate expressions', function() {
36585             expect(counter.getText()).toEqual('0');
36586             incBtn.click();
36587             expect(counter.getText()).toEqual('1');
36588             expectNoErrors();
36589           });
36590
36591           it('should throw and report an error when using "eval"', function() {
36592             evilBtn.click();
36593             expect(evilError.getText()).toMatch(/Content Security Policy/);
36594             expectError(/Content Security Policy/);
36595           });
36596         </file>
36597       </example>
36598   */
36599
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.
36603
36604 /**
36605  * @ngdoc directive
36606  * @name ngClick
36607  *
36608  * @description
36609  * The ngClick directive allows you to specify custom behavior when
36610  * an element is clicked.
36611  *
36612  * @element ANY
36613  * @priority 0
36614  * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
36615  * click. ({@link guide/expression#-event- Event object is available as `$event`})
36616  *
36617  * @example
36618    <example name="ng-click">
36619      <file name="index.html">
36620       <button ng-click="count = count + 1" ng-init="count=0">
36621         Increment
36622       </button>
36623       <span>
36624         count: {{count}}
36625       </span>
36626      </file>
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');
36632        });
36633      </file>
36634    </example>
36635  */
36636 /*
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.
36639  */
36640 var ngEventDirectives = {};
36641
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 = {
36646   'blur': true,
36647   'focus': true
36648 };
36649 forEach(
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) {
36654       return {
36655         restrict: 'A',
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});
36666               };
36667               if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
36668                 scope.$evalAsync(callback);
36669               } else {
36670                 scope.$apply(callback);
36671               }
36672             });
36673           };
36674         }
36675       };
36676     }];
36677   }
36678 );
36679
36680 /**
36681  * @ngdoc directive
36682  * @name ngDblclick
36683  *
36684  * @description
36685  * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
36686  *
36687  * @element ANY
36688  * @priority 0
36689  * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
36690  * a dblclick. (The Event object is available as `$event`)
36691  *
36692  * @example
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)
36697       </button>
36698       count: {{count}}
36699      </file>
36700    </example>
36701  */
36702
36703
36704 /**
36705  * @ngdoc directive
36706  * @name ngMousedown
36707  *
36708  * @description
36709  * The ngMousedown directive allows you to specify custom behavior on mousedown event.
36710  *
36711  * @element ANY
36712  * @priority 0
36713  * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
36714  * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
36715  *
36716  * @example
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)
36721       </button>
36722       count: {{count}}
36723      </file>
36724    </example>
36725  */
36726
36727
36728 /**
36729  * @ngdoc directive
36730  * @name ngMouseup
36731  *
36732  * @description
36733  * Specify custom behavior on mouseup event.
36734  *
36735  * @element ANY
36736  * @priority 0
36737  * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
36738  * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
36739  *
36740  * @example
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)
36745       </button>
36746       count: {{count}}
36747      </file>
36748    </example>
36749  */
36750
36751 /**
36752  * @ngdoc directive
36753  * @name ngMouseover
36754  *
36755  * @description
36756  * Specify custom behavior on mouseover event.
36757  *
36758  * @element ANY
36759  * @priority 0
36760  * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
36761  * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
36762  *
36763  * @example
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)
36768       </button>
36769       count: {{count}}
36770      </file>
36771    </example>
36772  */
36773
36774
36775 /**
36776  * @ngdoc directive
36777  * @name ngMouseenter
36778  *
36779  * @description
36780  * Specify custom behavior on mouseenter event.
36781  *
36782  * @element ANY
36783  * @priority 0
36784  * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
36785  * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
36786  *
36787  * @example
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)
36792       </button>
36793       count: {{count}}
36794      </file>
36795    </example>
36796  */
36797
36798
36799 /**
36800  * @ngdoc directive
36801  * @name ngMouseleave
36802  *
36803  * @description
36804  * Specify custom behavior on mouseleave event.
36805  *
36806  * @element ANY
36807  * @priority 0
36808  * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
36809  * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
36810  *
36811  * @example
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)
36816       </button>
36817       count: {{count}}
36818      </file>
36819    </example>
36820  */
36821
36822
36823 /**
36824  * @ngdoc directive
36825  * @name ngMousemove
36826  *
36827  * @description
36828  * Specify custom behavior on mousemove event.
36829  *
36830  * @element ANY
36831  * @priority 0
36832  * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
36833  * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
36834  *
36835  * @example
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)
36840       </button>
36841       count: {{count}}
36842      </file>
36843    </example>
36844  */
36845
36846
36847 /**
36848  * @ngdoc directive
36849  * @name ngKeydown
36850  *
36851  * @description
36852  * Specify custom behavior on keydown event.
36853  *
36854  * @element ANY
36855  * @priority 0
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.)
36858  *
36859  * @example
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}}
36864      </file>
36865    </example>
36866  */
36867
36868
36869 /**
36870  * @ngdoc directive
36871  * @name ngKeyup
36872  *
36873  * @description
36874  * Specify custom behavior on keyup event.
36875  *
36876  * @element ANY
36877  * @priority 0
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.)
36880  *
36881  * @example
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}}
36886
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>
36891      </file>
36892    </example>
36893  */
36894
36895
36896 /**
36897  * @ngdoc directive
36898  * @name ngKeypress
36899  *
36900  * @description
36901  * Specify custom behavior on keypress event.
36902  *
36903  * @element ANY
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.)
36907  *
36908  * @example
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}}
36913      </file>
36914    </example>
36915  */
36916
36917
36918 /**
36919  * @ngdoc directive
36920  * @name ngSubmit
36921  *
36922  * @description
36923  * Enables binding angular expressions to onsubmit events.
36924  *
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.
36928  *
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.
36934  * </div>
36935  *
36936  * @element form
36937  * @priority 0
36938  * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
36939  * ({@link guide/expression#-event- Event object is available as `$event`})
36940  *
36941  * @example
36942    <example module="submitExample" name="ng-submit">
36943      <file name="index.html">
36944       <script>
36945         angular.module('submitExample', [])
36946           .controller('ExampleController', ['$scope', function($scope) {
36947             $scope.list = [];
36948             $scope.text = 'hello';
36949             $scope.submit = function() {
36950               if ($scope.text) {
36951                 $scope.list.push(this.text);
36952                 $scope.text = '';
36953               }
36954             };
36955           }]);
36956       </script>
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>
36962       </form>
36963      </file>
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('');
36970        });
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');
36976         });
36977      </file>
36978    </example>
36979  */
36980
36981 /**
36982  * @ngdoc directive
36983  * @name ngFocus
36984  *
36985  * @description
36986  * Specify custom behavior on focus event.
36987  *
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.
36991  *
36992  * @element window, input, select, textarea, a
36993  * @priority 0
36994  * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
36995  * focus. ({@link guide/expression#-event- Event object is available as `$event`})
36996  *
36997  * @example
36998  * See {@link ng.directive:ngClick ngClick}
36999  */
37000
37001 /**
37002  * @ngdoc directive
37003  * @name ngBlur
37004  *
37005  * @description
37006  * Specify custom behavior on blur event.
37007  *
37008  * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
37009  * an element has lost focus.
37010  *
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.
37015  *
37016  * @element window, input, select, textarea, a
37017  * @priority 0
37018  * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
37019  * blur. ({@link guide/expression#-event- Event object is available as `$event`})
37020  *
37021  * @example
37022  * See {@link ng.directive:ngClick ngClick}
37023  */
37024
37025 /**
37026  * @ngdoc directive
37027  * @name ngCopy
37028  *
37029  * @description
37030  * Specify custom behavior on copy event.
37031  *
37032  * @element window, input, select, textarea, a
37033  * @priority 0
37034  * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
37035  * copy. ({@link guide/expression#-event- Event object is available as `$event`})
37036  *
37037  * @example
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">
37041       copied: {{copied}}
37042      </file>
37043    </example>
37044  */
37045
37046 /**
37047  * @ngdoc directive
37048  * @name ngCut
37049  *
37050  * @description
37051  * Specify custom behavior on cut event.
37052  *
37053  * @element window, input, select, textarea, a
37054  * @priority 0
37055  * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
37056  * cut. ({@link guide/expression#-event- Event object is available as `$event`})
37057  *
37058  * @example
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">
37062       cut: {{cut}}
37063      </file>
37064    </example>
37065  */
37066
37067 /**
37068  * @ngdoc directive
37069  * @name ngPaste
37070  *
37071  * @description
37072  * Specify custom behavior on paste event.
37073  *
37074  * @element window, input, select, textarea, a
37075  * @priority 0
37076  * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
37077  * paste. ({@link guide/expression#-event- Event object is available as `$event`})
37078  *
37079  * @example
37080    <example name="ng-paste">
37081      <file name="index.html">
37082       <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
37083       pasted: {{paste}}
37084      </file>
37085    </example>
37086  */
37087
37088 /**
37089  * @ngdoc directive
37090  * @name ngIf
37091  * @restrict A
37092  * @multiElement
37093  *
37094  * @description
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.
37099  *
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.
37104  *
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.
37112  *
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.
37117  *
37118  * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
37119  * and `leave` effects.
37120  *
37121  * @animations
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 |
37126  *
37127  * @element ANY
37128  * @scope
37129  * @priority 600
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.
37133  *
37134  * @example
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/>
37138       Show when checked:
37139       <span ng-if="checked" class="animate-if">
37140         This is removed when the checkbox is unchecked.
37141       </span>
37142     </file>
37143     <file name="animations.css">
37144       .animate-if {
37145         background:white;
37146         border:1px solid black;
37147         padding:10px;
37148       }
37149
37150       .animate-if.ng-enter, .animate-if.ng-leave {
37151         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
37152       }
37153
37154       .animate-if.ng-enter,
37155       .animate-if.ng-leave.ng-leave-active {
37156         opacity:0;
37157       }
37158
37159       .animate-if.ng-leave,
37160       .animate-if.ng-enter.ng-enter-active {
37161         opacity:1;
37162       }
37163     </file>
37164   </example>
37165  */
37166 var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
37167   return {
37168     multiElement: true,
37169     transclude: 'element',
37170     priority: 600,
37171     terminal: true,
37172     restrict: 'A',
37173     $$tlb: true,
37174     link: function($scope, $element, $attr, ctrl, $transclude) {
37175         var block, childScope, previousElements;
37176         $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
37177
37178           if (value) {
37179             if (!childScope) {
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.
37186                 block = {
37187                   clone: clone
37188                 };
37189                 $animate.enter(clone, $element.parent(), $element);
37190               });
37191             }
37192           } else {
37193             if (previousElements) {
37194               previousElements.remove();
37195               previousElements = null;
37196             }
37197             if (childScope) {
37198               childScope.$destroy();
37199               childScope = null;
37200             }
37201             if (block) {
37202               previousElements = getBlockNodes(block.clone);
37203               $animate.leave(previousElements).done(function(response) {
37204                 if (response !== false) previousElements = null;
37205               });
37206               block = null;
37207             }
37208           }
37209         });
37210     }
37211   };
37212 }];
37213
37214 /**
37215  * @ngdoc directive
37216  * @name ngInclude
37217  * @restrict ECA
37218  *
37219  * @description
37220  * Fetches, compiles and includes an external HTML fragment.
37221  *
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}.
37228  *
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.
37235  *
37236  * @animations
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 |
37241  *
37242  * The enter and leave animation occur concurrently.
37243  *
37244  * @scope
37245  * @priority 400
37246  *
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`.
37255  *                  </div>
37256    *
37257  * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
37258  *                  $anchorScroll} to scroll the viewport after the content is loaded.
37259  *
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.
37263  *
37264  * @example
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>
37270        </select>
37271        url of the template: <code>{{template.url}}</code>
37272        <hr/>
37273        <div class="slide-animate-container">
37274          <div class="slide-animate" ng-include="template.url"></div>
37275        </div>
37276      </div>
37277     </file>
37278     <file name="script.js">
37279       angular.module('includeExample', ['ngAnimate'])
37280         .controller('ExampleController', ['$scope', function($scope) {
37281           $scope.templates =
37282             [{ name: 'template1.html', url: 'template1.html'},
37283              { name: 'template2.html', url: 'template2.html'}];
37284           $scope.template = $scope.templates[0];
37285         }]);
37286      </file>
37287     <file name="template1.html">
37288       Content of template1.html
37289     </file>
37290     <file name="template2.html">
37291       Content of template2.html
37292     </file>
37293     <file name="animations.css">
37294       .slide-animate-container {
37295         position:relative;
37296         background:white;
37297         border:1px solid black;
37298         height:40px;
37299         overflow:hidden;
37300       }
37301
37302       .slide-animate {
37303         padding:10px;
37304       }
37305
37306       .slide-animate.ng-enter, .slide-animate.ng-leave {
37307         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
37308
37309         position:absolute;
37310         top:0;
37311         left:0;
37312         right:0;
37313         bottom:0;
37314         display:block;
37315         padding:10px;
37316       }
37317
37318       .slide-animate.ng-enter {
37319         top:-50px;
37320       }
37321       .slide-animate.ng-enter.ng-enter-active {
37322         top:0;
37323       }
37324
37325       .slide-animate.ng-leave {
37326         top:0;
37327       }
37328       .slide-animate.ng-leave.ng-leave-active {
37329         top:50px;
37330       }
37331     </file>
37332     <file name="protractor.js" type="protractor">
37333       var templateSelect = element(by.model('template'));
37334       var includeElem = element(by.css('[ng-include]'));
37335
37336       it('should load template1.html', function() {
37337         expect(includeElem.getText()).toMatch(/Content of template1.html/);
37338       });
37339
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
37344           return;
37345         }
37346         templateSelect.click();
37347         templateSelect.all(by.css('option')).get(2).click();
37348         expect(includeElem.getText()).toMatch(/Content of template2.html/);
37349       });
37350
37351       it('should change to blank', function() {
37352         if (browser.params.browser === 'firefox') {
37353           // Firefox can't handle using selects
37354           return;
37355         }
37356         templateSelect.click();
37357         templateSelect.all(by.css('option')).get(0).click();
37358         expect(includeElem.isPresent()).toBe(false);
37359       });
37360     </file>
37361   </example>
37362  */
37363
37364
37365 /**
37366  * @ngdoc event
37367  * @name ngInclude#$includeContentRequested
37368  * @eventType emit on the scope ngInclude was declared in
37369  * @description
37370  * Emitted every time the ngInclude content is requested.
37371  *
37372  * @param {Object} angularEvent Synthetic event object.
37373  * @param {String} src URL of content to load.
37374  */
37375
37376
37377 /**
37378  * @ngdoc event
37379  * @name ngInclude#$includeContentLoaded
37380  * @eventType emit on the current ngInclude scope
37381  * @description
37382  * Emitted every time the ngInclude content is reloaded.
37383  *
37384  * @param {Object} angularEvent Synthetic event object.
37385  * @param {String} src URL of content to load.
37386  */
37387
37388
37389 /**
37390  * @ngdoc event
37391  * @name ngInclude#$includeContentError
37392  * @eventType emit on the scope ngInclude was declared in
37393  * @description
37394  * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
37395  *
37396  * @param {Object} angularEvent Synthetic event object.
37397  * @param {String} src URL of content to load.
37398  */
37399 var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
37400                   function($templateRequest,   $anchorScroll,   $animate) {
37401   return {
37402     restrict: 'ECA',
37403     priority: 400,
37404     terminal: true,
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;
37411
37412       return function(scope, $element, $attr, ctrl, $transclude) {
37413         var changeCounter = 0,
37414             currentScope,
37415             previousElement,
37416             currentElement;
37417
37418         var cleanupLastIncludeContent = function() {
37419           if (previousElement) {
37420             previousElement.remove();
37421             previousElement = null;
37422           }
37423           if (currentScope) {
37424             currentScope.$destroy();
37425             currentScope = null;
37426           }
37427           if (currentElement) {
37428             $animate.leave(currentElement).done(function(response) {
37429               if (response !== false) previousElement = null;
37430             });
37431             previousElement = currentElement;
37432             currentElement = null;
37433           }
37434         };
37435
37436         scope.$watch(srcExp, function ngIncludeWatchAction(src) {
37437           var afterAnimation = function(response) {
37438             if (response !== false && isDefined(autoScrollExp) &&
37439               (!autoScrollExp || scope.$eval(autoScrollExp))) {
37440                 $anchorScroll();
37441             }
37442           };
37443           var thisChangeId = ++changeCounter;
37444
37445           if (src) {
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;
37450
37451               if (thisChangeId !== changeCounter) return;
37452               var newScope = scope.$new();
37453               ctrl.template = response;
37454
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);
37464               });
37465
37466               currentScope = newScope;
37467               currentElement = clone;
37468
37469               currentScope.$emit('$includeContentLoaded', src);
37470               scope.$eval(onloadExp);
37471             }, function() {
37472               if (scope.$$destroyed) return;
37473
37474               if (thisChangeId === changeCounter) {
37475                 cleanupLastIncludeContent();
37476                 scope.$emit('$includeContentError', src);
37477               }
37478             });
37479             scope.$emit('$includeContentRequested', src);
37480           } else {
37481             cleanupLastIncludeContent();
37482             ctrl.template = null;
37483           }
37484         });
37485       };
37486     }
37487   };
37488 }];
37489
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
37494 // is called.
37495 var ngIncludeFillContentDirective = ['$compile',
37496   function($compile) {
37497     return {
37498       restrict: 'ECA',
37499       priority: -400,
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
37505           // specially.
37506           $element.empty();
37507           $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
37508               function namespaceAdaptedClone(clone) {
37509             $element.append(clone);
37510           }, {futureParentElement: $element});
37511           return;
37512         }
37513
37514         $element.html(ctrl.template);
37515         $compile($element.contents())(scope);
37516       }
37517     };
37518   }];
37519
37520 /**
37521  * @ngdoc directive
37522  * @name ngInit
37523  * @restrict AC
37524  *
37525  * @description
37526  * The `ngInit` directive allows you to evaluate an expression in the
37527  * current scope.
37528  *
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.
37535  * </div>
37536  *
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>`
37542  * </pre>
37543  * </div>
37544  *
37545  * @priority 450
37546  *
37547  * @element ANY
37548  * @param {expression} ngInit {@link guide/expression Expression} to eval.
37549  *
37550  * @example
37551    <example module="initExample" name="ng-init">
37552      <file name="index.html">
37553    <script>
37554      angular.module('initExample', [])
37555        .controller('ExampleController', ['$scope', function($scope) {
37556          $scope.list = [['a', 'b'], ['c', 'd']];
37557        }]);
37558    </script>
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>
37563        </div>
37564      </div>
37565    </div>
37566      </file>
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;');
37574        });
37575      </file>
37576    </example>
37577  */
37578 var ngInitDirective = ngDirective({
37579   priority: 450,
37580   compile: function() {
37581     return {
37582       pre: function(scope, element, attrs) {
37583         scope.$eval(attrs.ngInit);
37584       }
37585     };
37586   }
37587 });
37588
37589 /**
37590  * @ngdoc directive
37591  * @name ngList
37592  *
37593  * @description
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=" | "`.
37597  *
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.
37606  *
37607  * ### Example with Validation
37608  *
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'];
37614  *        }]);
37615  *   </file>
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">
37621  *        Required!</span>
37622  *      </span>
37623  *      <br>
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/>
37629  *     </form>
37630  *   </file>
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'));
37636  *
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');
37641  *     });
37642  *
37643  *     it('should be invalid if empty', function() {
37644  *       listInput.clear();
37645  *       listInput.sendKeys('');
37646  *
37647  *       expect(names.getText()).toContain('');
37648  *       expect(valid.getText()).toContain('false');
37649  *       expect(error.getCssValue('display')).not.toBe('none');
37650  *     });
37651  *   </file>
37652  * </example>
37653  *
37654  * ### Example - splitting on newline
37655  * <example name="ngList-directive-newlines">
37656  *   <file name="index.html">
37657  *    <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
37658  *    <pre>{{ list | json }}</pre>
37659  *   </file>
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]');
37666  *     });
37667  *   </file>
37668  * </example>
37669  *
37670  * @element input
37671  * @param {string=} ngList optional delimiter that should be used to split the value.
37672  */
37673 var ngListDirective = function() {
37674   return {
37675     restrict: 'A',
37676     priority: 100,
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;
37684
37685       var parse = function(viewValue) {
37686         // If the viewValue is invalid (say required but empty) it will be `undefined`
37687         if (isUndefined(viewValue)) return;
37688
37689         var list = [];
37690
37691         if (viewValue) {
37692           forEach(viewValue.split(separator), function(value) {
37693             if (value) list.push(trimValues ? trim(value) : value);
37694           });
37695         }
37696
37697         return list;
37698       };
37699
37700       ctrl.$parsers.push(parse);
37701       ctrl.$formatters.push(function(value) {
37702         if (isArray(value)) {
37703           return value.join(ngList);
37704         }
37705
37706         return undefined;
37707       });
37708
37709       // Override the standard $isEmpty because an empty array means the input is empty.
37710       ctrl.$isEmpty = function(value) {
37711         return !value || !value.length;
37712       };
37713     }
37714   };
37715 };
37716
37717 /* global VALID_CLASS: true,
37718   INVALID_CLASS: true,
37719   PRISTINE_CLASS: true,
37720   DIRTY_CLASS: true,
37721   UNTOUCHED_CLASS: true,
37722   TOUCHED_CLASS: true
37723 */
37724
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';
37734
37735 var ngModelMinErr = minErr('ngModel');
37736
37737 /**
37738  * @ngdoc type
37739  * @name ngModel.NgModelController
37740  *
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
37743  * is set.
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.
37749
37750 Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
37751 `$viewValue`}.
37752
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`.
37757
37758  *
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.
37763  * ```js
37764  * function formatter(value) {
37765  *   if (value) {
37766  *     return value.toUpperCase();
37767  *   }
37768  * }
37769  * ngModel.$formatters.push(formatter);
37770  * ```
37771  *
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.
37777  *
37778  * ```js
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);
37785  * };
37786  * ```
37787  *
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.
37796  *
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.
37799  *
37800  * ```js
37801  * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
37802  *   var value = modelValue || viewValue;
37803  *
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
37811  *        return true;
37812  *      });
37813  * };
37814  * ```
37815  *
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.
37819  *
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.
37822  *
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.
37830  *
37831  * @description
37832  *
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.
37842  *
37843  * @example
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.
37848  *
37849  * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
37850  * contents be edited in place by the user.
37851  *
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.
37856  *
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;
37862         min-height: 20px;
37863       }
37864
37865       .ng-invalid {
37866         border: 1px solid red;
37867       }
37868
37869     </file>
37870     <file name="script.js">
37871       angular.module('customControl', ['ngSanitize']).
37872         directive('contenteditable', ['$sce', function($sce) {
37873           return {
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
37878
37879               // Specify how UI should be updated
37880               ngModel.$render = function() {
37881                 element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
37882               };
37883
37884               // Listen for change events to enable binding
37885               element.on('blur keyup change', function() {
37886                 scope.$evalAsync(read);
37887               });
37888               read(); // initialize
37889
37890               // Write data to the model
37891               function read() {
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>') {
37896                   html = '';
37897                 }
37898                 ngModel.$setViewValue(html);
37899               }
37900             }
37901           };
37902         }]);
37903     </file>
37904     <file name="index.html">
37905       <form name="myForm">
37906        <div contenteditable
37907             name="myWidget" ng-model="userContent"
37908             strip-br="true"
37909             required>Change me!</div>
37910         <span ng-show="myForm.myWidget.$error.required">Required!</span>
37911        <hr>
37912        <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
37913       </form>
37914     </file>
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
37920         return;
37921       }
37922       var contentEditable = element(by.css('[contenteditable]'));
37923       var content = 'Change me!';
37924
37925       expect(contentEditable.getText()).toEqual(content);
37926
37927       contentEditable.clear();
37928       contentEditable.sendKeys(protractor.Key.BACK_SPACE);
37929       expect(contentEditable.getText()).toEqual('');
37930       expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
37931     });
37932     </file>
37933  * </example>
37934  *
37935  *
37936  */
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;
37958
37959   var parsedNgModel = $parse($attr.ngModel),
37960       parsedNgModelAssign = parsedNgModel.assign,
37961       ngModelGet = parsedNgModel,
37962       ngModelSet = parsedNgModelAssign,
37963       pendingDebounce = null,
37964       parserValid,
37965       ctrl = this;
37966
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)');
37972
37973       ngModelGet = function($scope) {
37974         var modelValue = parsedNgModel($scope);
37975         if (isFunction(modelValue)) {
37976           modelValue = invokeModelGetter($scope);
37977         }
37978         return modelValue;
37979       };
37980       ngModelSet = function($scope, newValue) {
37981         if (isFunction(parsedNgModel($scope))) {
37982           invokeModelSetter($scope, {$$$p: newValue});
37983         } else {
37984           parsedNgModelAssign($scope, newValue);
37985         }
37986       };
37987     } else if (!parsedNgModel.assign) {
37988       throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}',
37989           $attr.ngModel, startingTag($element));
37990     }
37991   };
37992
37993   /**
37994    * @ngdoc method
37995    * @name ngModel.NgModelController#$render
37996    *
37997    * @description
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.
38000    *
38001    * The `$render()` method is invoked in the following situations:
38002    *
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.
38007    *
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.
38012    */
38013   this.$render = noop;
38014
38015   /**
38016    * @ngdoc method
38017    * @name ngModel.NgModelController#$isEmpty
38018    *
38019    * @description
38020    * This is called when we need to determine if the value of an input is empty.
38021    *
38022    * For instance, the required directive does this to work out if the input has data or not.
38023    *
38024    * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
38025    *
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`
38028    * implies empty.
38029    *
38030    * @param {*} value The value of the input to check for emptiness.
38031    * @returns {boolean} True if `value` is "empty".
38032    */
38033   this.$isEmpty = function(value) {
38034     // eslint-disable-next-line no-self-compare
38035     return isUndefined(value) || value === '' || value === null || value !== value;
38036   };
38037
38038   this.$$updateEmptyClasses = function(value) {
38039     if (ctrl.$isEmpty(value)) {
38040       $animate.removeClass($element, NOT_EMPTY_CLASS);
38041       $animate.addClass($element, EMPTY_CLASS);
38042     } else {
38043       $animate.removeClass($element, EMPTY_CLASS);
38044       $animate.addClass($element, NOT_EMPTY_CLASS);
38045     }
38046   };
38047
38048
38049   var currentValidationRunId = 0;
38050
38051   /**
38052    * @ngdoc method
38053    * @name ngModel.NgModelController#$setValidity
38054    *
38055    * @description
38056    * Change the validity state, and notify the form.
38057    *
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.
38061    *
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.
38072    */
38073   addSetValidityMethod({
38074     ctrl: this,
38075     $element: $element,
38076     set: function(object, property) {
38077       object[property] = true;
38078     },
38079     unset: function(object, property) {
38080       delete object[property];
38081     },
38082     $animate: $animate
38083   });
38084
38085   /**
38086    * @ngdoc method
38087    * @name ngModel.NgModelController#$setPristine
38088    *
38089    * @description
38090    * Sets the control to its pristine state.
38091    *
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.
38095    */
38096   this.$setPristine = function() {
38097     ctrl.$dirty = false;
38098     ctrl.$pristine = true;
38099     $animate.removeClass($element, DIRTY_CLASS);
38100     $animate.addClass($element, PRISTINE_CLASS);
38101   };
38102
38103   /**
38104    * @ngdoc method
38105    * @name ngModel.NgModelController#$setDirty
38106    *
38107    * @description
38108    * Sets the control to its dirty state.
38109    *
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.
38113    */
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();
38120   };
38121
38122   /**
38123    * @ngdoc method
38124    * @name ngModel.NgModelController#$setUntouched
38125    *
38126    * @description
38127    * Sets the control to its untouched state.
38128    *
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.
38133    */
38134   this.$setUntouched = function() {
38135     ctrl.$touched = false;
38136     ctrl.$untouched = true;
38137     $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
38138   };
38139
38140   /**
38141    * @ngdoc method
38142    * @name ngModel.NgModelController#$setTouched
38143    *
38144    * @description
38145    * Sets the control to its touched state.
38146    *
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).
38150    */
38151   this.$setTouched = function() {
38152     ctrl.$touched = true;
38153     ctrl.$untouched = false;
38154     $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
38155   };
38156
38157   /**
38158    * @ngdoc method
38159    * @name ngModel.NgModelController#$rollbackViewValue
38160    *
38161    * @description
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
38164    * future event.
38165    *
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`.
38169    *
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.
38172    *
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.
38176    *
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.
38180    *
38181    * <example name="ng-model-cancel-update" module="cancel-update-example">
38182    *   <file name="app.js">
38183    *     angular.module('cancel-update-example', [])
38184    *
38185    *     .controller('CancelUpdateController', ['$scope', function($scope) {
38186    *       $scope.model = {value1: '', value2: ''};
38187    *
38188    *       $scope.setEmpty = function(e, value, rollback) {
38189    *         if (e.keyCode === 27) {
38190    *           e.preventDefault();
38191    *           if (rollback) {
38192    *             $scope.myForm[value].$rollbackViewValue();
38193    *           }
38194    *           $scope.model[value] = '';
38195    *         }
38196    *       };
38197    *     }]);
38198    *   </file>
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>
38203    *       <ol>
38204    *         <li>Type something in the input. You will see that the model is not yet updated</li>
38205    *         <li>Press the Escape key.
38206    *           <ol>
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.
38209    *             </li>
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.
38212    *             </li>
38213    *           </ol>
38214    *         </li>
38215    *       </ol>
38216    *
38217    *       <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
38218    *         <div>
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 }}"
38223    *         </div>
38224    *
38225    *         <div>
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 }}"
38230    *         </div>
38231    *       </form>
38232    *     </div>
38233    *   </file>
38234        <file name="style.css">
38235           div {
38236             display: table-cell;
38237           }
38238           div:nth-child(1) {
38239             padding-right: 30px;
38240           }
38241
38242         </file>
38243    * </example>
38244    */
38245   this.$rollbackViewValue = function() {
38246     $timeout.cancel(pendingDebounce);
38247     ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
38248     ctrl.$render();
38249   };
38250
38251   /**
38252    * @ngdoc method
38253    * @name ngModel.NgModelController#$validate
38254    *
38255    * @description
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.
38262    */
38263   this.$validate = function() {
38264     // ignore $validate before model is initialized
38265     if (isNumberNaN(ctrl.$modelValue)) {
38266       return;
38267     }
38268
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;
38275
38276     var prevValid = ctrl.$valid;
38277     var prevModelValue = ctrl.$modelValue;
38278
38279     var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
38280
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;
38290
38291         if (ctrl.$modelValue !== prevModelValue) {
38292           ctrl.$$writeModelToScope();
38293         }
38294       }
38295     });
38296
38297   };
38298
38299   this.$$runValidators = function(modelValue, viewValue, doneCallback) {
38300     currentValidationRunId++;
38301     var localValidationRunId = currentValidationRunId;
38302
38303     // check parser error
38304     if (!processParseErrors()) {
38305       validationDone(false);
38306       return;
38307     }
38308     if (!processSyncValidators()) {
38309       validationDone(false);
38310       return;
38311     }
38312     processAsyncValidators();
38313
38314     function processParseErrors() {
38315       var errorKey = ctrl.$$parserName || 'parse';
38316       if (isUndefined(parserValid)) {
38317         setValidity(errorKey, null);
38318       } else {
38319         if (!parserValid) {
38320           forEach(ctrl.$validators, function(v, name) {
38321             setValidity(name, null);
38322           });
38323           forEach(ctrl.$asyncValidators, function(v, name) {
38324             setValidity(name, null);
38325           });
38326         }
38327         // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
38328         setValidity(errorKey, parserValid);
38329         return parserValid;
38330       }
38331       return true;
38332     }
38333
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);
38340       });
38341       if (!syncValidatorsValid) {
38342         forEach(ctrl.$asyncValidators, function(v, name) {
38343           setValidity(name, null);
38344         });
38345         return false;
38346       }
38347       return true;
38348     }
38349
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);
38358         }
38359         setValidity(name, undefined);
38360         validatorPromises.push(promise.then(function() {
38361           setValidity(name, true);
38362         }, function() {
38363           allValid = false;
38364           setValidity(name, false);
38365         }));
38366       });
38367       if (!validatorPromises.length) {
38368         validationDone(true);
38369       } else {
38370         $q.all(validatorPromises).then(function() {
38371           validationDone(allValid);
38372         }, noop);
38373       }
38374     }
38375
38376     function setValidity(name, isValid) {
38377       if (localValidationRunId === currentValidationRunId) {
38378         ctrl.$setValidity(name, isValid);
38379       }
38380     }
38381
38382     function validationDone(allValid) {
38383       if (localValidationRunId === currentValidationRunId) {
38384
38385         doneCallback(allValid);
38386       }
38387     }
38388   };
38389
38390   /**
38391    * @ngdoc method
38392    * @name ngModel.NgModelController#$commitViewValue
38393    *
38394    * @description
38395    * Commit a pending update to the `$modelValue`.
38396    *
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.
38400    */
38401   this.$commitViewValue = function() {
38402     var viewValue = ctrl.$viewValue;
38403
38404     $timeout.cancel(pendingDebounce);
38405
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)) {
38410       return;
38411     }
38412     ctrl.$$updateEmptyClasses(viewValue);
38413     ctrl.$$lastCommittedViewValue = viewValue;
38414
38415     // change to dirty
38416     if (ctrl.$pristine) {
38417       this.$setDirty();
38418     }
38419     this.$$parseAndValidate();
38420   };
38421
38422   this.$$parseAndValidate = function() {
38423     var viewValue = ctrl.$$lastCommittedViewValue;
38424     var modelValue = viewValue;
38425     parserValid = isUndefined(modelValue) ? undefined : true;
38426
38427     if (parserValid) {
38428       for (var i = 0; i < ctrl.$parsers.length; i++) {
38429         modelValue = ctrl.$parsers[i](modelValue);
38430         if (isUndefined(modelValue)) {
38431           parserValid = false;
38432           break;
38433         }
38434       }
38435     }
38436     if (isNumberNaN(ctrl.$modelValue)) {
38437       // ctrl.$modelValue has not been touched yet...
38438       ctrl.$modelValue = ngModelGet($scope);
38439     }
38440     var prevModelValue = ctrl.$modelValue;
38441     var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
38442     ctrl.$$rawModelValue = modelValue;
38443
38444     if (allowInvalid) {
38445       ctrl.$modelValue = modelValue;
38446       writeToModelIfNeeded();
38447     }
38448
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();
38459       }
38460     });
38461
38462     function writeToModelIfNeeded() {
38463       if (ctrl.$modelValue !== prevModelValue) {
38464         ctrl.$$writeModelToScope();
38465       }
38466     }
38467   };
38468
38469   this.$$writeModelToScope = function() {
38470     ngModelSet($scope, ctrl.$modelValue);
38471     forEach(ctrl.$viewChangeListeners, function(listener) {
38472       try {
38473         listener();
38474       } catch (e) {
38475         $exceptionHandler(e);
38476       }
38477     });
38478   };
38479
38480   /**
38481    * @ngdoc method
38482    * @name ngModel.NgModelController#$setViewValue
38483    *
38484    * @description
38485    * Update the view value.
38486    *
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.
38491    *
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.
38497    *
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.
38505    *
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.
38515    *
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.
38525    * </div>
38526    *
38527    * @param {*} value value from the view.
38528    * @param {string} trigger Event that triggered the update.
38529    */
38530   this.$setViewValue = function(value, trigger) {
38531     ctrl.$viewValue = value;
38532     if (!ctrl.$options || ctrl.$options.updateOnDefault) {
38533       ctrl.$$debounceViewValueCommit(trigger);
38534     }
38535   };
38536
38537   this.$$debounceViewValueCommit = function(trigger) {
38538     var debounceDelay = 0,
38539         options = ctrl.$options,
38540         debounce;
38541
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'];
38550       }
38551     }
38552
38553     $timeout.cancel(pendingDebounce);
38554     if (debounceDelay) {
38555       pendingDebounce = $timeout(function() {
38556         ctrl.$commitViewValue();
38557       }, debounceDelay);
38558     } else if ($rootScope.$$phase) {
38559       ctrl.$commitViewValue();
38560     } else {
38561       $scope.$apply(function() {
38562         ctrl.$commitViewValue();
38563       });
38564     }
38565   };
38566
38567   // model -> value
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);
38577
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)
38584     ) {
38585       ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
38586       parserValid = undefined;
38587
38588       var formatters = ctrl.$formatters,
38589           idx = formatters.length;
38590
38591       var viewValue = modelValue;
38592       while (idx--) {
38593         viewValue = formatters[idx](viewValue);
38594       }
38595       if (ctrl.$viewValue !== viewValue) {
38596         ctrl.$$updateEmptyClasses(viewValue);
38597         ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
38598         ctrl.$render();
38599
38600         // It is possible that model and view value have been updated during render
38601         ctrl.$$runValidators(ctrl.$modelValue, ctrl.$viewValue, noop);
38602       }
38603     }
38604
38605     return modelValue;
38606   });
38607 }];
38608
38609
38610 /**
38611  * @ngdoc directive
38612  * @name ngModel
38613  *
38614  * @element input
38615  * @priority 1
38616  *
38617  * @description
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.
38621  *
38622  * `ngModel` is responsible for:
38623  *
38624  * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
38625  *   require.
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}.
38631  *
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.
38635  *
38636  * For best practices on using `ngModel`, see:
38637  *
38638  *  - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
38639  *
38640  * For basic examples, how to use `ngModel`, see:
38641  *
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}
38656  *
38657  * # Complex Models (objects or collections)
38658  *
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.
38662  *
38663  * The model must be assigned an entirely new object or collection before a re-rendering will occur.
38664  *
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.
38668  *
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.
38672  *
38673  * # CSS classes
38674  * The following CSS classes are added and removed on the associated input/select/textarea element
38675  * depending on the validity of the model.
38676  *
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
38689  *
38690  * Keep in mind that ngAnimate can detect each of these classes when added and removed.
38691  *
38692  * ## Animation Hooks
38693  *
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.
38699  *
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:
38702  *
38703  * <pre>
38704  * //be sure to include ngAnimate as a module to hook into more
38705  * //advanced animations
38706  * .my-input {
38707  *   transition:0.5s linear all;
38708  *   background: white;
38709  * }
38710  * .my-input.ng-invalid {
38711  *   background: red;
38712  *   color:white;
38713  * }
38714  * </pre>
38715  *
38716  * @example
38717  * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model">
38718      <file name="index.html">
38719        <script>
38720         angular.module('inputExample', [])
38721           .controller('ExampleController', ['$scope', function($scope) {
38722             $scope.val = '1';
38723           }]);
38724        </script>
38725        <style>
38726          .my-input {
38727            transition:all linear 0.5s;
38728            background: transparent;
38729          }
38730          .my-input.ng-invalid {
38731            color:white;
38732            background: red;
38733          }
38734        </style>
38735        <p id="inputDescription">
38736         Update input to see transitions when valid/invalid.
38737         Integer is a valid value.
38738        </p>
38739        <form name="testForm" ng-controller="ExampleController">
38740          <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
38741                 aria-describedby="inputDescription" />
38742        </form>
38743      </file>
38744  * </example>
38745  *
38746  * ## Binding to a getter/setter
38747  *
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
38752  * to the view.
38753  *
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.
38757  * </div>
38758  *
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.
38763  *
38764  * The following example shows how to use `ngModel` with a getter/setter:
38765  *
38766  * @example
38767  * <example name="ngModel-getter-setter" module="getterSetterExample">
38768      <file name="index.html">
38769        <div ng-controller="ExampleController">
38770          <form name="userForm">
38771            <label>Name:
38772              <input type="text" name="userName"
38773                     ng-model="user.name"
38774                     ng-model-options="{ getterSetter: true }" />
38775            </label>
38776          </form>
38777          <pre>user.name = <span ng-bind="user.name()"></span></pre>
38778        </div>
38779      </file>
38780      <file name="app.js">
38781        angular.module('getterSetterExample', [])
38782          .controller('ExampleController', ['$scope', function($scope) {
38783            var _name = 'Brian';
38784            $scope.user = {
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;
38791              }
38792            };
38793          }]);
38794      </file>
38795  * </example>
38796  */
38797 var ngModelDirective = ['$rootScope', function($rootScope) {
38798   return {
38799     restrict: 'A',
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.
38805     priority: 1,
38806     compile: function ngModelCompile(element) {
38807       // Setup initial state of the control
38808       element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
38809
38810       return {
38811         pre: function ngModelPreLink(scope, element, attr, ctrls) {
38812           var modelCtrl = ctrls[0],
38813               formCtrl = ctrls[1] || modelCtrl.$$parentForm;
38814
38815           modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
38816
38817           // notify others, especially parent forms
38818           formCtrl.$addControl(modelCtrl);
38819
38820           attr.$observe('name', function(newValue) {
38821             if (modelCtrl.$name !== newValue) {
38822               modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
38823             }
38824           });
38825
38826           scope.$on('$destroy', function() {
38827             modelCtrl.$$parentForm.$removeControl(modelCtrl);
38828           });
38829         },
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);
38835             });
38836           }
38837
38838           element.on('blur', function() {
38839             if (modelCtrl.$touched) return;
38840
38841             if ($rootScope.$$phase) {
38842               scope.$evalAsync(modelCtrl.$setTouched);
38843             } else {
38844               scope.$apply(modelCtrl.$setTouched);
38845             }
38846           });
38847         }
38848       };
38849     }
38850   };
38851 }];
38852
38853
38854
38855 var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
38856
38857 /**
38858  * @ngdoc directive
38859  * @name ngModelOptions
38860  *
38861  * @description
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.
38865  *
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.
38870  *
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.
38875  *
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.
38879  *
38880  * `ngModelOptions` has an effect on the element it's declared on and its descendants.
38881  *
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.
38899  *
38900  * @example
38901
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.
38905
38906   <example name="ngModelOptions-directive-blur" module="optionsExample">
38907     <file name="index.html">
38908       <div ng-controller="ExampleController">
38909         <form name="userForm">
38910           <label>Name:
38911             <input type="text" name="userName"
38912                    ng-model="user.name"
38913                    ng-model-options="{ updateOn: 'blur' }"
38914                    ng-keyup="cancel($event)" />
38915           </label><br />
38916           <label>Other data:
38917             <input type="text" ng-model="user.data" />
38918           </label><br />
38919         </form>
38920         <pre>user.name = <span ng-bind="user.name"></span></pre>
38921         <pre>user.data = <span ng-bind="user.data"></span></pre>
38922       </div>
38923     </file>
38924     <file name="app.js">
38925       angular.module('optionsExample', [])
38926         .controller('ExampleController', ['$scope', function($scope) {
38927           $scope.user = { name: 'John', data: '' };
38928
38929           $scope.cancel = function(e) {
38930             if (e.keyCode === 27) {
38931               $scope.userForm.userName.$rollbackViewValue();
38932             }
38933           };
38934         }]);
38935     </file>
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'));
38940
38941       it('should allow custom events', function() {
38942         input.sendKeys(' Doe');
38943         input.click();
38944         expect(model.getText()).toEqual('John');
38945         other.click();
38946         expect(model.getText()).toEqual('John Doe');
38947       });
38948
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');
38954         other.click();
38955         expect(model.getText()).toEqual('John');
38956       });
38957     </file>
38958   </example>
38959
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.
38962
38963   <example name="ngModelOptions-directive-debounce" module="optionsExample">
38964     <file name="index.html">
38965       <div ng-controller="ExampleController">
38966         <form name="userForm">
38967           <label>Name:
38968             <input type="text" name="userName"
38969                    ng-model="user.name"
38970                    ng-model-options="{ debounce: 1000 }" />
38971           </label>
38972           <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
38973           <br />
38974         </form>
38975         <pre>user.name = <span ng-bind="user.name"></span></pre>
38976       </div>
38977     </file>
38978     <file name="app.js">
38979       angular.module('optionsExample', [])
38980         .controller('ExampleController', ['$scope', function($scope) {
38981           $scope.user = { name: 'Igor' };
38982         }]);
38983     </file>
38984   </example>
38985
38986   This one shows how to bind to getter/setters:
38987
38988   <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
38989     <file name="index.html">
38990       <div ng-controller="ExampleController">
38991         <form name="userForm">
38992           <label>Name:
38993             <input type="text" name="userName"
38994                    ng-model="user.name"
38995                    ng-model-options="{ getterSetter: true }" />
38996           </label>
38997         </form>
38998         <pre>user.name = <span ng-bind="user.name()"></span></pre>
38999       </div>
39000     </file>
39001     <file name="app.js">
39002       angular.module('getterSetterExample', [])
39003         .controller('ExampleController', ['$scope', function($scope) {
39004           var _name = 'Brian';
39005           $scope.user = {
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;
39012             }
39013           };
39014         }]);
39015     </file>
39016   </example>
39017  */
39018 var ngModelOptionsDirective = function() {
39019   return {
39020     restrict: 'A',
39021     controller: ['$scope', '$attrs', function NgModelOptionsController($scope, $attrs) {
39022       var that = this;
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;
39030           return ' ';
39031         }));
39032       } else {
39033         this.$options.updateOnDefault = true;
39034       }
39035     }]
39036   };
39037 };
39038
39039
39040
39041 // helper methods
39042 function addSetValidityMethod(context) {
39043   var ctrl = context.ctrl,
39044       $element = context.$element,
39045       classCache = {},
39046       set = context.set,
39047       unset = context.unset,
39048       $animate = context.$animate;
39049
39050   classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
39051
39052   ctrl.$setValidity = setValidity;
39053
39054   function setValidity(validationErrorKey, state, controller) {
39055     if (isUndefined(state)) {
39056       createAndSet('$pending', validationErrorKey, controller);
39057     } else {
39058       unsetAndCleanup('$pending', validationErrorKey, controller);
39059     }
39060     if (!isBoolean(state)) {
39061       unset(ctrl.$error, validationErrorKey, controller);
39062       unset(ctrl.$$success, validationErrorKey, controller);
39063     } else {
39064       if (state) {
39065         unset(ctrl.$error, validationErrorKey, controller);
39066         set(ctrl.$$success, validationErrorKey, controller);
39067       } else {
39068         set(ctrl.$error, validationErrorKey, controller);
39069         unset(ctrl.$$success, validationErrorKey, controller);
39070       }
39071     }
39072     if (ctrl.$pending) {
39073       cachedToggleClass(PENDING_CLASS, true);
39074       ctrl.$valid = ctrl.$invalid = undefined;
39075       toggleValidationCss('', null);
39076     } else {
39077       cachedToggleClass(PENDING_CLASS, false);
39078       ctrl.$valid = isObjectEmpty(ctrl.$error);
39079       ctrl.$invalid = !ctrl.$valid;
39080       toggleValidationCss('', ctrl.$valid);
39081     }
39082
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.
39087     var combinedState;
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;
39094     } else {
39095       combinedState = null;
39096     }
39097
39098     toggleValidationCss(validationErrorKey, combinedState);
39099     ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
39100   }
39101
39102   function createAndSet(name, value, controller) {
39103     if (!ctrl[name]) {
39104       ctrl[name] = {};
39105     }
39106     set(ctrl[name], value, controller);
39107   }
39108
39109   function unsetAndCleanup(name, value, controller) {
39110     if (ctrl[name]) {
39111       unset(ctrl[name], value, controller);
39112     }
39113     if (isObjectEmpty(ctrl[name])) {
39114       ctrl[name] = undefined;
39115     }
39116   }
39117
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;
39125     }
39126   }
39127
39128   function toggleValidationCss(validationErrorKey, isValid) {
39129     validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
39130
39131     cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
39132     cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
39133   }
39134 }
39135
39136 function isObjectEmpty(obj) {
39137   if (obj) {
39138     for (var prop in obj) {
39139       if (obj.hasOwnProperty(prop)) {
39140         return false;
39141       }
39142     }
39143   }
39144   return true;
39145 }
39146
39147 /**
39148  * @ngdoc directive
39149  * @name ngNonBindable
39150  * @restrict AC
39151  * @priority 1000
39152  *
39153  * @description
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.
39158  *
39159  * @element ANY
39160  *
39161  * @example
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.
39164  *
39165  * @example
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>
39170       </file>
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/);
39175        });
39176       </file>
39177     </example>
39178  */
39179 var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
39180
39181 /* exported ngOptionsDirective */
39182
39183 /* global jqLiteRemove */
39184
39185 var ngOptionsMinErr = minErr('ngOptions');
39186
39187 /**
39188  * @ngdoc directive
39189  * @name ngOptions
39190  * @restrict A
39191  *
39192  * @description
39193  *
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.
39197  *
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
39205  * present.
39206  *
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`
39209  * directive.
39210  *
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.
39214  *
39215  * ## Complex Models (objects or collections)
39216  *
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.
39219  *
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]`.
39224  *
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`.
39228  *
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.
39234  *
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.
39238  *
39239  * ## `select` **`as`**
39240  *
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.
39245  *
39246  *
39247  * ### `select` **`as`** and **`track by`**
39248  *
39249  * <div class="alert alert-warning">
39250  * Be careful when using `select` **`as`** and **`track by`** in the same expression.
39251  * </div>
39252  *
39253  * Given this array of items on the $scope:
39254  *
39255  * ```js
39256  * $scope.items = [{
39257  *   id: 1,
39258  *   label: 'aLabel',
39259  *   subItem: { name: 'aSubItem' }
39260  * }, {
39261  *   id: 2,
39262  *   label: 'bLabel',
39263  *   subItem: { name: 'bSubItem' }
39264  * }];
39265  * ```
39266  *
39267  * This will work:
39268  *
39269  * ```html
39270  * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
39271  * ```
39272  * ```js
39273  * $scope.selected = $scope.items[0];
39274  * ```
39275  *
39276  * but this will not work:
39277  *
39278  * ```html
39279  * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
39280  * ```
39281  * ```js
39282  * $scope.selected = $scope.items[0].subItem;
39283  * ```
39284  *
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.
39292  *
39293  *
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:
39301  *
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`
39320  *
39321  * Where:
39322  *
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>`
39332  *      DOM element.
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).
39339  *
39340  * @example
39341     <example module="selectExample" name="select">
39342       <file name="index.html">
39343         <script>
39344         angular.module('selectExample', [])
39345           .controller('ExampleController', ['$scope', function($scope) {
39346             $scope.colors = [
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}
39352             ];
39353             $scope.myColor = $scope.colors[2]; // red
39354           }]);
39355         </script>
39356         <div ng-controller="ExampleController">
39357           <ul>
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>
39362             </li>
39363             <li>
39364               <button ng-click="colors.push({})">add</button>
39365             </li>
39366           </ul>
39367           <hr/>
39368           <label>Color (null not allowed):
39369             <select ng-model="myColor" ng-options="color.name for color in colors"></select>
39370           </label><br/>
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>
39375             </select>
39376           </span></label><br/>
39377
39378           <label>Color grouped by shade:
39379             <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
39380             </select>
39381           </label><br/>
39382
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">
39386             </select>
39387           </label><br/>
39388
39389
39390
39391           Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
39392           <br/>
39393           <hr/>
39394           Currently selected: {{ {selected_color:myColor} }}
39395           <div style="border:solid 1px black; height:20px"
39396                ng-style="{'background-color':myColor.name}">
39397           </div>
39398         </div>
39399       </file>
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');
39409          });
39410       </file>
39411     </example>
39412  */
39413
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 */
39427
39428
39429 var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
39430
39431   function parseOptionsExpression(optionsExp, selectElement, scope) {
39432
39433     var match = optionsExp.match(NG_OPTIONS_REGEXP);
39434     if (!(match)) {
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));
39440     }
39441
39442     // Extract the parts from the ngOptions expression
39443
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];
39448
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);
39458
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));
39467     };
39468
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]);
39473
39474     var locals = {};
39475     var getLocals = keyName ? function(value, key) {
39476       locals[keyName] = key;
39477       locals[valueName] = value;
39478       return locals;
39479     } : function(value) {
39480       locals[valueName] = value;
39481       return locals;
39482     };
39483
39484
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;
39491     }
39492
39493     function getOptionValuesKeys(optionValues) {
39494       var optionValuesKeys;
39495
39496       if (!keyName && isArrayLike(optionValues)) {
39497         optionValuesKeys = optionValues;
39498       } else {
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);
39504           }
39505         }
39506       }
39507       return optionValuesKeys;
39508     }
39509
39510     return {
39511       trackBy: trackBy,
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 || [];
39519
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];
39525
39526           var locals = getLocals(value, key);
39527           var selectValue = getTrackByValueFn(value, locals);
39528           watchedArray.push(selectValue);
39529
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);
39534           }
39535
39536           // Only need to watch the disableWhenFn if there is a specific disable expression
39537           if (match[4]) {
39538             var disableWhen = disableWhenFn(scope, locals);
39539             watchedArray.push(disableWhen);
39540           }
39541         }
39542         return watchedArray;
39543       }),
39544
39545       getOptions: function() {
39546
39547         var optionItems = [];
39548         var selectValueMap = {};
39549
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;
39555
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);
39566
39567           optionItems.push(optionItem);
39568           selectValueMap[selectValue] = optionItem;
39569         }
39570
39571         return {
39572           items: optionItems,
39573           selectValueMap: selectValueMap,
39574           getOptionFromViewValue: function(value) {
39575             return selectValueMap[getTrackByValue(value)];
39576           },
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;
39581           }
39582         };
39583       }
39584     };
39585   }
39586
39587
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');
39592
39593     function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
39594
39595       var selectCtrl = ctrls[0];
39596       var ngModelCtrl = ctrls[1];
39597       var multiple = attr.multiple;
39598
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.
39601       var emptyOption;
39602       for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
39603         if (children[i].value === '') {
39604           emptyOption = children.eq(i);
39605           break;
39606         }
39607       }
39608
39609       var providedEmptyOption = !!emptyOption;
39610       var emptyOptionRendered = false;
39611
39612       var unknownOption = jqLite(optionTemplate.cloneNode(false));
39613       unknownOption.val('?');
39614
39615       var options;
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();
39621
39622       var renderEmptyOption = function() {
39623         if (!providedEmptyOption) {
39624           selectElement.prepend(emptyOption);
39625         }
39626         selectElement.val('');
39627         if (emptyOptionRendered) {
39628           emptyOption.prop('selected', true); // needed for IE
39629           emptyOption.attr('selected', true);
39630         }
39631       };
39632
39633       var removeEmptyOption = function() {
39634         if (!providedEmptyOption) {
39635           emptyOption.remove();
39636         } else if (emptyOptionRendered) {
39637           emptyOption.removeAttr('selected');
39638         }
39639       };
39640
39641       var renderUnknownOption = function() {
39642         selectElement.prepend(unknownOption);
39643         selectElement.val('?');
39644         unknownOption.prop('selected', true); // needed for IE
39645         unknownOption.attr('selected', true);
39646       };
39647
39648       var removeUnknownOption = function() {
39649         unknownOption.remove();
39650       };
39651
39652       // Update the controller methods for multiple selectable options
39653       if (!multiple) {
39654
39655         selectCtrl.writeValue = function writeNgOptionsValue(value) {
39656           var selectedOption = options.selectValueMap[selectElement.val()];
39657           var option = options.getOptionFromViewValue(value);
39658
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');
39662
39663           if (option) {
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
39667             // set always
39668
39669             if (selectElement[0].value !== option.selectValue) {
39670               removeUnknownOption();
39671               removeEmptyOption();
39672
39673               selectElement[0].value = option.selectValue;
39674               option.element.selected = true;
39675             }
39676
39677             option.element.setAttribute('selected', 'selected');
39678           } else {
39679             if (value === null || providedEmptyOption) {
39680               removeUnknownOption();
39681               renderEmptyOption();
39682             } else {
39683               removeEmptyOption();
39684               renderUnknownOption();
39685             }
39686           }
39687         };
39688
39689         selectCtrl.readValue = function readNgOptionsValue() {
39690
39691           var selectedOption = options.selectValueMap[selectElement.val()];
39692
39693           if (selectedOption && !selectedOption.disabled) {
39694             removeEmptyOption();
39695             removeUnknownOption();
39696             return options.getViewValueFromOption(selectedOption);
39697           }
39698           return null;
39699         };
39700
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) {
39705           scope.$watch(
39706             function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
39707             function() { ngModelCtrl.$render(); }
39708           );
39709         }
39710
39711       } else {
39712
39713         ngModelCtrl.$isEmpty = function(value) {
39714           return !value || value.length === 0;
39715         };
39716
39717
39718         selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
39719           options.items.forEach(function(option) {
39720             option.element.selected = false;
39721           });
39722
39723           if (value) {
39724             value.forEach(function(item) {
39725               var option = options.getOptionFromViewValue(item);
39726               if (option) option.element.selected = true;
39727             });
39728           }
39729         };
39730
39731
39732         selectCtrl.readValue = function readNgOptionsMultiple() {
39733           var selectedValues = selectElement.val() || [],
39734               selections = [];
39735
39736           forEach(selectedValues, function(value) {
39737             var option = options.selectValueMap[value];
39738             if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
39739           });
39740
39741           return selections;
39742         };
39743
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) {
39747
39748           scope.$watchCollection(function() {
39749             if (isArray(ngModelCtrl.$viewValue)) {
39750               return ngModelCtrl.$viewValue.map(function(value) {
39751                 return ngOptions.getTrackByValue(value);
39752               });
39753             }
39754           }, function() {
39755             ngModelCtrl.$render();
39756           });
39757
39758         }
39759       }
39760
39761
39762       if (providedEmptyOption) {
39763
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();
39767
39768         // compile the element since there might be bindings in it
39769         $compile(emptyOption)(scope);
39770
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.
39774
39775           emptyOptionRendered = false;
39776
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();
39787
39788               optionEl.on('$destroy', function() {
39789                 emptyOption = undefined;
39790                 emptyOptionRendered = false;
39791               });
39792             }
39793           };
39794
39795         } else {
39796           emptyOption.removeClass('ng-scope');
39797           emptyOptionRendered = true;
39798         }
39799
39800       } else {
39801         emptyOption = jqLite(optionTemplate.cloneNode(false));
39802       }
39803
39804       selectElement.empty();
39805
39806       // We need to do this here to ensure that the options object is defined
39807       // when we first hit it in writeNgOptionsValue
39808       updateOptions();
39809
39810       // We will re-render the option elements if the option values or labels change
39811       scope.$watchCollection(ngOptions.getWatchables, updateOptions);
39812
39813       // ------------------------------------------------------------------ //
39814
39815       function addOptionElement(option, parent) {
39816         var optionElement = optionTemplate.cloneNode(false);
39817         parent.appendChild(optionElement);
39818         updateOptionElement(option, optionElement);
39819       }
39820
39821
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;
39833         }
39834         element.value = option.selectValue;
39835       }
39836
39837       function updateOptions() {
39838         var previousValue = options && selectCtrl.readValue();
39839
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
39842         // must preserve.
39843         // Instead, iterate over the current option elements and remove them or their optgroup
39844         // parents
39845         if (options) {
39846
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);
39851             } else {
39852               jqLiteRemove(option.element);
39853             }
39854           }
39855         }
39856
39857         options = ngOptions.getOptions();
39858
39859         var groupElementMap = {};
39860
39861         // Ensure that the empty option is always there if it was explicitly provided
39862         if (providedEmptyOption) {
39863           selectElement.prepend(emptyOption);
39864         }
39865
39866         options.items.forEach(function addOption(option) {
39867           var groupElement;
39868
39869           if (isDefined(option.group)) {
39870
39871             // This option is to live in a group
39872             // See if we have already created this group
39873             groupElement = groupElementMap[option.group];
39874
39875             if (!groupElement) {
39876
39877               groupElement = optGroupTemplate.cloneNode(false);
39878               listFragment.appendChild(groupElement);
39879
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;
39883
39884               // Store it for use later
39885               groupElementMap[option.group] = groupElement;
39886             }
39887
39888             addOptionElement(option, groupElement);
39889
39890           } else {
39891
39892             // This option is not in a group
39893             addOptionElement(option, listFragment);
39894           }
39895         });
39896
39897         selectElement[0].appendChild(listFragment);
39898
39899         ngModelCtrl.$render();
39900
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();
39908           }
39909         }
39910
39911       }
39912   }
39913
39914   return {
39915     restrict: 'A',
39916     terminal: true,
39917     require: ['select', 'ngModel'],
39918     link: {
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;
39924       },
39925       post: ngOptionsPostLink
39926     }
39927   };
39928 }];
39929
39930 /**
39931  * @ngdoc directive
39932  * @name ngPluralize
39933  * @restrict EA
39934  *
39935  * @description
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.
39942  *
39943  * # Plural categories and explicit number rules
39944  * There are two
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".
39947  *
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.
39952  *
39953  * # Configuring ngPluralize
39954  * You configure ngPluralize by providing 2 attributes: `count` and `when`.
39955  * You can also provide an optional attribute, `offset`.
39956  *
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.
39959  *
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.
39962  *
39963  * The following example shows how to configure ngPluralize:
39964  *
39965  * ```html
39966  * <ng-pluralize count="personCount"
39967                  when="{'0': 'Nobody is viewing.',
39968  *                      'one': '1 person is viewing.',
39969  *                      'other': '{} people are viewing.'}">
39970  * </ng-pluralize>
39971  *```
39972  *
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".
39978  *
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>.
39983  *
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`.
39986  *
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:
39993  *
39994  * ```html
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.'}">
40001  * </ng-pluralize>
40002  * ```
40003  *
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"
40010  * is shown.
40011  *
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".
40016  *
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.
40020  *
40021  * @example
40022     <example module="pluralizeExample" name="ng-pluralize">
40023       <file name="index.html">
40024         <script>
40025           angular.module('pluralizeExample', [])
40026             .controller('ExampleController', ['$scope', function($scope) {
40027               $scope.person1 = 'Igor';
40028               $scope.person2 = 'Misko';
40029               $scope.personCount = 1;
40030             }]);
40031         </script>
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/>
40036
40037           <!--- Example with simple pluralization rules for en locale --->
40038           Without Offset:
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>
40044
40045           <!--- Example with offset --->
40046           With Offset(2):
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.'}">
40053           </ng-pluralize>
40054         </div>
40055       </file>
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'));
40061
40062           expect(withoutOffset.getText()).toEqual('1 person is viewing.');
40063           expect(withOffset.getText()).toEqual('Igor is viewing.');
40064
40065           countInput.clear();
40066           countInput.sendKeys('0');
40067
40068           expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
40069           expect(withOffset.getText()).toEqual('Nobody is viewing.');
40070
40071           countInput.clear();
40072           countInput.sendKeys('2');
40073
40074           expect(withoutOffset.getText()).toEqual('2 people are viewing.');
40075           expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
40076
40077           countInput.clear();
40078           countInput.sendKeys('3');
40079
40080           expect(withoutOffset.getText()).toEqual('3 people are viewing.');
40081           expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
40082
40083           countInput.clear();
40084           countInput.sendKeys('4');
40085
40086           expect(withoutOffset.getText()).toEqual('4 people are viewing.');
40087           expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
40088         });
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');
40096           person1.clear();
40097           person1.sendKeys('Di');
40098           person2.clear();
40099           person2.sendKeys('Vojta');
40100           expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
40101         });
40102       </file>
40103     </example>
40104  */
40105 var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
40106   var BRACE = /{}/g,
40107       IS_WHEN = /^when(Minus)?(.+)$/;
40108
40109   return {
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) || {},
40115           whensExpFns = {},
40116           startSymbol = $interpolate.startSymbol(),
40117           endSymbol = $interpolate.endSymbol(),
40118           braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
40119           watchRemover = angular.noop,
40120           lastCount;
40121
40122       forEach(attr, function(expression, attributeName) {
40123         var tmpMatch = IS_WHEN.exec(attributeName);
40124         if (tmpMatch) {
40125           var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
40126           whens[whenKey] = element.attr(attr.$attr[attributeName]);
40127         }
40128       });
40129       forEach(whens, function(expression, key) {
40130         whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
40131
40132       });
40133
40134       scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
40135         var count = parseFloat(newVal);
40136         var countIsNaN = isNumberNaN(count);
40137
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);
40142         }
40143
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))) {
40147           watchRemover();
40148           var whenExpFn = whensExpFns[count];
40149           if (isUndefined(whenExpFn)) {
40150             if (newVal != null) {
40151               $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp);
40152             }
40153             watchRemover = noop;
40154             updateElementText();
40155           } else {
40156             watchRemover = scope.$watch(whenExpFn, updateElementText);
40157           }
40158           lastCount = count;
40159         }
40160       });
40161
40162       function updateElementText(newText) {
40163         element.text(newText || '');
40164       }
40165     }
40166   };
40167 }];
40168
40169 /* exported ngRepeatDirective */
40170
40171 /**
40172  * @ngdoc directive
40173  * @name ngRepeat
40174  * @multiElement
40175  *
40176  * @description
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.
40180  *
40181  * Special properties are exposed on the local scope of each template instance, including:
40182  *
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).            |
40191  *
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.
40195  * </div>
40196  *
40197  *
40198  * # Iterating over object properties
40199  *
40200  * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
40201  * syntax:
40202  *
40203  * ```js
40204  * <div ng-repeat="(key, value) in myObj"> ... </div>
40205  * ```
40206  *
40207  * However, there are a few limitations compared to array iteration:
40208  *
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).
40215  *
40216  * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
40217  *   it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
40218  *
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.
40221  *
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.
40226  *
40227  *
40228  * # Tracking and Duplicates
40229  *
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:
40232  *
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.
40236  *
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.
40241  *
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.
40245  *
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.
40248  *
40249  * For example, you may track items by the index of each item in the collection, using the
40250  * special scope property `$index`:
40251  * ```html
40252  *    <div ng-repeat="n in [42, 42, 43, 43] track by $index">
40253  *      {{n}}
40254  *    </div>
40255  * ```
40256  *
40257  * You may also use arbitrary expressions in `track by`, including references to custom functions
40258  * on the scope:
40259  * ```html
40260  *    <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
40261  *      {{n}}
40262  *    </div>
40263  * ```
40264  *
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.
40272  * </div>
40273  *
40274  * ```html
40275  *    <div ng-repeat="model in collection track by model.id">
40276  *      {{model.name}}
40277  *    </div>
40278  * ```
40279  *
40280  * <br />
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.
40287  * </div>
40288  *
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:
40291  * ```html
40292  *    <div ng-repeat="obj in collection track by $id(obj)">
40293  *      {{obj.prop}}
40294  *    </div>
40295  * ```
40296  *
40297  * <br />
40298  * <div class="alert alert-warning">
40299  * **Note:** `track by` must always be the last expression:
40300  * </div>
40301  * ```
40302  *    <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
40303  *      {{model.name}}
40304  *    </div>
40305  * ```
40306  *
40307  *
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.
40313  *
40314  * The example below makes use of this feature:
40315  * ```html
40316  *   <header ng-repeat-start="item in items">
40317  *     Header {{ item }}
40318  *   </header>
40319  *   <div class="body">
40320  *     Body {{ item }}
40321  *   </div>
40322  *   <footer ng-repeat-end>
40323  *     Footer {{ item }}
40324  *   </footer>
40325  * ```
40326  *
40327  * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
40328  * ```html
40329  *   <header>
40330  *     Header A
40331  *   </header>
40332  *   <div class="body">
40333  *     Body A
40334  *   </div>
40335  *   <footer>
40336  *     Footer A
40337  *   </footer>
40338  *   <header>
40339  *     Header B
40340  *   </header>
40341  *   <div class="body">
40342  *     Body B
40343  *   </div>
40344  *   <footer>
40345  *     Footer B
40346  *   </footer>
40347  * ```
40348  *
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**).
40351  *
40352  * @animations
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 |
40358  *
40359  * See the example below for defining CSS animations with ngRepeat.
40360  *
40361  * @element ANY
40362  * @scope
40363  * @priority 1000
40364  * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
40365  *   formats are currently supported:
40366  *
40367  *   * `variable in expression` â€“ where variable is the user defined loop variable and `expression`
40368  *     is a scope expression giving the collection to enumerate.
40369  *
40370  *     For example: `album in artist.albums`.
40371  *
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.
40374  *
40375  *     For example: `(name, age) in {'adam':10, 'amalie':12}`.
40376  *
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.)
40382  *
40383  *     Note that the tracking expression must come last, after any filters, and the alias expression.
40384  *
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.
40387  *
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.
40392  *
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.
40396  *
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.
40399  *
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.
40403  *
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.
40406  *
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).
40409  *
40410  *     For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
40411  *
40412  * @example
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.
40423           </li>
40424           <li class="animate-repeat" ng-if="results.length === 0">
40425             <strong>No results found...</strong>
40426           </li>
40427         </ul>
40428       </div>
40429     </file>
40430     <file name="script.js">
40431       angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
40432         $scope.friends = [
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'}
40443         ];
40444       });
40445     </file>
40446     <file name="animations.css">
40447       .example-animate-container {
40448         background:white;
40449         border:1px solid black;
40450         list-style:none;
40451         margin:0;
40452         padding:0 10px;
40453       }
40454
40455       .animate-repeat {
40456         line-height:30px;
40457         list-style:none;
40458         box-sizing:border-box;
40459       }
40460
40461       .animate-repeat.ng-move,
40462       .animate-repeat.ng-enter,
40463       .animate-repeat.ng-leave {
40464         transition:all linear 0.5s;
40465       }
40466
40467       .animate-repeat.ng-leave.ng-leave-active,
40468       .animate-repeat.ng-move,
40469       .animate-repeat.ng-enter {
40470         opacity:0;
40471         max-height:0;
40472       }
40473
40474       .animate-repeat.ng-leave,
40475       .animate-repeat.ng-move.ng-move-active,
40476       .animate-repeat.ng-enter.ng-enter-active {
40477         opacity:1;
40478         max-height:30px;
40479       }
40480     </file>
40481     <file name="protractor.js" type="protractor">
40482       var friends = element.all(by.repeater('friend in friends'));
40483
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:");
40491       });
40492
40493        it('should update repeater when filter predicate changes', function() {
40494          expect(friends.count()).toBe(10);
40495
40496          element(by.model('q')).sendKeys('ma');
40497
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.');
40501        });
40502       </file>
40503     </example>
40504  */
40505 var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
40506   var NG_REMOVED = '$$NG_REMOVED';
40507   var ngRepeatMinErr = minErr('ngRepeat');
40508
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);
40519   };
40520
40521   var getBlockStart = function(block) {
40522     return block.clone[0];
40523   };
40524
40525   var getBlockEnd = function(block) {
40526     return block.clone[block.clone.length - 1];
40527   };
40528
40529
40530   return {
40531     restrict: 'A',
40532     multiElement: true,
40533     transclude: 'element',
40534     priority: 1000,
40535     terminal: true,
40536     $$tlb: true,
40537     compile: function ngRepeatCompile($element, $attr) {
40538       var expression = $attr.ngRepeat;
40539       var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
40540
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*$/);
40542
40543       if (!match) {
40544         throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.',
40545             expression);
40546       }
40547
40548       var lhs = match[1];
40549       var rhs = match[2];
40550       var aliasAs = match[3];
40551       var trackByExp = match[4];
40552
40553       match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/);
40554
40555       if (!match) {
40556         throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.',
40557             lhs);
40558       }
40559       var valueIdentifier = match[3] || match[1];
40560       var keyIdentifier = match[2];
40561
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.',
40565           aliasAs);
40566       }
40567
40568       var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
40569       var hashFnLocals = {$id: hashKey};
40570
40571       if (trackByExp) {
40572         trackByExpGetter = $parse(trackByExp);
40573       } else {
40574         trackByIdArrayFn = function(key, value) {
40575           return hashKey(value);
40576         };
40577         trackByIdObjFn = function(key) {
40578           return key;
40579         };
40580       }
40581
40582       return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
40583
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);
40591           };
40592         }
40593
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
40599         //
40600         // We are using no-proto object so that we don't need to guard against inherited props via
40601         // hasOwnProperty.
40602         var lastBlockMap = createMap();
40603
40604         //watch props
40605         $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
40606           var index, length,
40607               previousNode = $element[0],     // node that cloned nodes should be inserted after
40608                                               // initialized to the comment node anchor
40609               nextNode,
40610               // Same as lastBlockMap but it has the current state. It will become the
40611               // lastBlockMap on the next iteration.
40612               nextBlockMap = createMap(),
40613               collectionLength,
40614               key, value, // key/value of iteration
40615               trackById,
40616               trackByIdFn,
40617               collectionKeys,
40618               block,       // last object information {scope, element, id}
40619               nextBlockOrder,
40620               elementsToRemove;
40621
40622           if (aliasAs) {
40623             $scope[aliasAs] = collection;
40624           }
40625
40626           if (isArrayLike(collection)) {
40627             collectionKeys = collection;
40628             trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
40629           } else {
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);
40636               }
40637             }
40638           }
40639
40640           collectionLength = collectionKeys.length;
40641           nextBlockOrder = new Array(collectionLength);
40642
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;
40658               });
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);
40662             } else {
40663               // new never before seen block
40664               nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
40665               nextBlockMap[trackById] = true;
40666             }
40667           }
40668
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;
40679               }
40680             }
40681             block.scope.$destroy();
40682           }
40683
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];
40689
40690             if (block.scope) {
40691               // if we have already seen this object, then we need to reuse the
40692               // associated scope/element
40693
40694               nextNode = previousNode;
40695
40696               // skip nodes that are already pending removal via leave animation
40697               do {
40698                 nextNode = nextNode.nextSibling;
40699               } while (nextNode && nextNode[NG_REMOVED]);
40700
40701               if (getBlockStart(block) !== nextNode) {
40702                 // existing item which got moved
40703                 $animate.move(getBlockNodes(block.clone), null, previousNode);
40704               }
40705               previousNode = getBlockEnd(block);
40706               updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
40707             } else {
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;
40714
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);
40723               });
40724             }
40725           }
40726           lastBlockMap = nextBlockMap;
40727         });
40728       };
40729     }
40730   };
40731 }];
40732
40733 var NG_HIDE_CLASS = 'ng-hide';
40734 var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
40735 /**
40736  * @ngdoc directive
40737  * @name ngShow
40738  * @multiElement
40739  *
40740  * @description
40741  * The `ngShow` directive shows or hides the given HTML element based on the expression provided to
40742  * the `ngShow` attribute.
40743  *
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}).
40748  *
40749  * ```html
40750  * <!-- when $scope.myValue is truthy (element is visible) -->
40751  * <div ng-show="myValue"></div>
40752  *
40753  * <!-- when $scope.myValue is falsy (element is hidden) -->
40754  * <div ng-show="myValue" class="ng-hide"></div>
40755  * ```
40756  *
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.
40760  *
40761  * ## Why is `!important` used?
40762  *
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.
40767  *
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.
40772  *
40773  * ### Overriding `.ng-hide`
40774  *
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.
40779  *
40780  * ```css
40781  * .ng-hide:not(.ng-hide-animate) {
40782  *   /&#42; These are just alternative ways of hiding an element &#42;/
40783  *   display: block!important;
40784  *   position: absolute;
40785  *   top: -9999px;
40786  *   left: -9999px;
40787  * }
40788  * ```
40789  *
40790  * By default you don't need to override anything in CSS and the animations will work around the
40791  * display style.
40792  *
40793  * ## A note about animations with `ngShow`
40794  *
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.
40799  *
40800  * ```css
40801  * /&#42; A working example can be found at the bottom of this page. &#42;/
40802  * .my-element.ng-hide-add, .my-element.ng-hide-remove {
40803  *   transition: all 0.5s linear;
40804  * }
40805  *
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 { ... }
40810  * ```
40811  *
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.
40814  *
40815  * @animations
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.        |
40820  *
40821  * @element ANY
40822  * @param {expression} ngShow If the {@link guide/expression expression} is truthy/falsy then the
40823  *                            element is shown/hidden respectively.
40824  *
40825  * @example
40826  * A simple example, animating the element's opacity:
40827  *
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.
40833       </div>
40834     </file>
40835     <file name="animations.css">
40836       .animate-show-hide.ng-hide {
40837         opacity: 0;
40838       }
40839
40840       .animate-show-hide.ng-hide-add,
40841       .animate-show-hide.ng-hide-remove {
40842         transition: all linear 0.5s;
40843       }
40844
40845       .check-element {
40846         border: 1px solid black;
40847         opacity: 1;
40848         padding: 10px;
40849       }
40850     </file>
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'));
40855
40856         expect(checkElem.isDisplayed()).toBe(false);
40857         checkbox.click();
40858         expect(checkElem.isDisplayed()).toBe(true);
40859       });
40860     </file>
40861   </example>
40862  *
40863  * <hr />
40864  * @example
40865  * A more complex example, featuring different show/hide animations:
40866  *
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.
40872       </div>
40873     </file>
40874     <file name="animations.css">
40875       body {
40876         overflow: hidden;
40877         perspective: 1000px;
40878       }
40879
40880       .funky-show-hide.ng-hide-add {
40881         transform: rotateZ(0);
40882         transform-origin: right;
40883         transition: all 0.5s ease-in-out;
40884       }
40885
40886       .funky-show-hide.ng-hide-add.ng-hide-add-active {
40887         transform: rotateZ(-135deg);
40888       }
40889
40890       .funky-show-hide.ng-hide-remove {
40891         transform: rotateY(90deg);
40892         transform-origin: left;
40893         transition: all 0.5s ease;
40894       }
40895
40896       .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
40897         transform: rotateY(0);
40898       }
40899
40900       .check-element {
40901         border: 1px solid black;
40902         opacity: 1;
40903         padding: 10px;
40904       }
40905     </file>
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'));
40910
40911         expect(checkElem.isDisplayed()).toBe(false);
40912         checkbox.click();
40913         expect(checkElem.isDisplayed()).toBe(true);
40914       });
40915     </file>
40916   </example>
40917  */
40918 var ngShowDirective = ['$animate', function($animate) {
40919   return {
40920     restrict: 'A',
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
40930         });
40931       });
40932     }
40933   };
40934 }];
40935
40936
40937 /**
40938  * @ngdoc directive
40939  * @name ngHide
40940  * @multiElement
40941  *
40942  * @description
40943  * The `ngHide` directive shows or hides the given HTML element based on the expression provided to
40944  * the `ngHide` attribute.
40945  *
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}).
40950  *
40951  * ```html
40952  * <!-- when $scope.myValue is truthy (element is hidden) -->
40953  * <div ng-hide="myValue" class="ng-hide"></div>
40954  *
40955  * <!-- when $scope.myValue is falsy (element is visible) -->
40956  * <div ng-hide="myValue"></div>
40957  * ```
40958  *
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.
40962  *
40963  * ## Why is `!important` used?
40964  *
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.
40969  *
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.
40974  *
40975  * ### Overriding `.ng-hide`
40976  *
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.
40981  *
40982  * ```css
40983  * .ng-hide:not(.ng-hide-animate) {
40984  *   /&#42; These are just alternative ways of hiding an element &#42;/
40985  *   display: block!important;
40986  *   position: absolute;
40987  *   top: -9999px;
40988  *   left: -9999px;
40989  * }
40990  * ```
40991  *
40992  * By default you don't need to override in CSS anything and the animations will work around the
40993  * display style.
40994  *
40995  * ## A note about animations with `ngHide`
40996  *
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.
41001  *
41002  * ```css
41003  * /&#42; A working example can be found at the bottom of this page. &#42;/
41004  * .my-element.ng-hide-add, .my-element.ng-hide-remove {
41005  *   transition: all 0.5s linear;
41006  * }
41007  *
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 { ... }
41012  * ```
41013  *
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.
41016  *
41017  * @animations
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. |
41022  *
41023  *
41024  * @element ANY
41025  * @param {expression} ngHide If the {@link guide/expression expression} is truthy/falsy then the
41026  *                            element is hidden/shown respectively.
41027  *
41028  * @example
41029  * A simple example, animating the element's opacity:
41030  *
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.
41036       </div>
41037     </file>
41038     <file name="animations.css">
41039       .animate-show-hide.ng-hide {
41040         opacity: 0;
41041       }
41042
41043       .animate-show-hide.ng-hide-add,
41044       .animate-show-hide.ng-hide-remove {
41045         transition: all linear 0.5s;
41046       }
41047
41048       .check-element {
41049         border: 1px solid black;
41050         opacity: 1;
41051         padding: 10px;
41052       }
41053     </file>
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'));
41058
41059         expect(checkElem.isDisplayed()).toBe(true);
41060         checkbox.click();
41061         expect(checkElem.isDisplayed()).toBe(false);
41062       });
41063     </file>
41064   </example>
41065  *
41066  * <hr />
41067  * @example
41068  * A more complex example, featuring different show/hide animations:
41069  *
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.
41075       </div>
41076     </file>
41077     <file name="animations.css">
41078       body {
41079         overflow: hidden;
41080         perspective: 1000px;
41081       }
41082
41083       .funky-show-hide.ng-hide-add {
41084         transform: rotateZ(0);
41085         transform-origin: right;
41086         transition: all 0.5s ease-in-out;
41087       }
41088
41089       .funky-show-hide.ng-hide-add.ng-hide-add-active {
41090         transform: rotateZ(-135deg);
41091       }
41092
41093       .funky-show-hide.ng-hide-remove {
41094         transform: rotateY(90deg);
41095         transform-origin: left;
41096         transition: all 0.5s ease;
41097       }
41098
41099       .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
41100         transform: rotateY(0);
41101       }
41102
41103       .check-element {
41104         border: 1px solid black;
41105         opacity: 1;
41106         padding: 10px;
41107       }
41108     </file>
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'));
41113
41114         expect(checkElem.isDisplayed()).toBe(true);
41115         checkbox.click();
41116         expect(checkElem.isDisplayed()).toBe(false);
41117       });
41118     </file>
41119   </example>
41120  */
41121 var ngHideDirective = ['$animate', function($animate) {
41122   return {
41123     restrict: 'A',
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
41131         });
41132       });
41133     }
41134   };
41135 }];
41136
41137 /**
41138  * @ngdoc directive
41139  * @name ngStyle
41140  * @restrict AC
41141  *
41142  * @description
41143  * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
41144  *
41145  * @knownIssue
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.
41149  *
41150  * @element ANY
41151  * @param {expression} ngStyle
41152  *
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
41155  * keys.
41156  *
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.
41159  *
41160  * @example
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={}">
41166         <br/>
41167         <span ng-style="myStyle">Sample Text</span>
41168         <pre>myStyle={{myStyle}}</pre>
41169      </file>
41170      <file name="style.css">
41171        span {
41172          color: black;
41173        }
41174      </file>
41175      <file name="protractor.js" type="protractor">
41176        var colorSpan = element(by.css('span'));
41177
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)');
41184        });
41185      </file>
41186    </example>
41187  */
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, '');});
41192     }
41193     if (newStyles) element.css(newStyles);
41194   }, true);
41195 });
41196
41197 /**
41198  * @ngdoc directive
41199  * @name ngSwitch
41200  * @restrict EA
41201  *
41202  * @description
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.
41206  *
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.
41215  *
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`.
41221  * </div>
41222
41223  * @animations
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 |
41228  *
41229  * @usage
41230  *
41231  * ```
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>
41236  * </ANY>
41237  * ```
41238  *
41239  *
41240  * @scope
41241  * @priority 1200
41242  * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
41243  * On child elements add:
41244  *
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
41254  *   case match.
41255  *
41256  *
41257  * @example
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">
41262         </select>
41263         <code>selection={{selection}}</code>
41264         <hr/>
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>
41270         </div>
41271       </div>
41272     </file>
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];
41278         }]);
41279     </file>
41280     <file name="animations.css">
41281       .animate-switch-container {
41282         position:relative;
41283         background:white;
41284         border:1px solid black;
41285         height:40px;
41286         overflow:hidden;
41287       }
41288
41289       .animate-switch {
41290         padding:10px;
41291       }
41292
41293       .animate-switch.ng-animate {
41294         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
41295
41296         position:absolute;
41297         top:0;
41298         left:0;
41299         right:0;
41300         bottom:0;
41301       }
41302
41303       .animate-switch.ng-leave.ng-leave-active,
41304       .animate-switch.ng-enter {
41305         top:-50px;
41306       }
41307       .animate-switch.ng-leave,
41308       .animate-switch.ng-enter.ng-enter-active {
41309         top:0;
41310       }
41311     </file>
41312     <file name="protractor.js" type="protractor">
41313       var switchElem = element(by.css('[ng-switch]'));
41314       var select = element(by.model('selection'));
41315
41316       it('should start in settings', function() {
41317         expect(switchElem.getText()).toMatch(/Settings Div/);
41318       });
41319       it('should change to home', function() {
41320         select.all(by.css('option')).get(1).click();
41321         expect(switchElem.getText()).toMatch(/Home Span/);
41322       });
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/);
41326       });
41327       it('should select default', function() {
41328         select.all(by.css('option')).get(3).click();
41329         expect(switchElem.getText()).toMatch(/default/);
41330       });
41331     </file>
41332   </example>
41333  */
41334 var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
41335   return {
41336     require: 'ngSwitch',
41337
41338     // asks for $scope to fool the BC controller module
41339     controller: ['$scope', function NgSwitchController() {
41340      this.cases = {};
41341     }],
41342     link: function(scope, element, attr, ngSwitchController) {
41343       var watchExpr = attr.ngSwitch || attr.on,
41344           selectedTranscludes = [],
41345           selectedElements = [],
41346           previousLeaveAnimations = [],
41347           selectedScopes = [];
41348
41349       var spliceFactory = function(array, index) {
41350           return function(response) {
41351             if (response !== false) array.splice(index, 1);
41352           };
41353       };
41354
41355       scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
41356         var i, ii;
41357
41358         // Start with the last, in case the array is modified during the loop
41359         while (previousLeaveAnimations.length) {
41360           $animate.cancel(previousLeaveAnimations.pop());
41361         }
41362
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));
41368         }
41369
41370         selectedElements.length = 0;
41371         selectedScopes.length = 0;
41372
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 };
41380
41381               selectedElements.push(block);
41382               $animate.enter(caseElement, anchor.parent(), anchor);
41383             });
41384           });
41385         }
41386       });
41387     }
41388   };
41389 }];
41390
41391 var ngSwitchWhenDirective = ngDirective({
41392   transclude: 'element',
41393   priority: 1200,
41394   require: '^ngSwitch',
41395   multiElement: true,
41396   link: function(scope, element, attrs, ctrl, $transclude) {
41397
41398     var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(
41399       // Filter duplicate cases
41400       function(element, index, array) { return array[index - 1] !== element; }
41401     );
41402
41403     forEach(cases, function(whenCase) {
41404       ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);
41405       ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });
41406     });
41407   }
41408 });
41409
41410 var ngSwitchDefaultDirective = ngDirective({
41411   transclude: 'element',
41412   priority: 1200,
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 });
41418    }
41419 });
41420
41421 /**
41422  * @ngdoc directive
41423  * @name ngTransclude
41424  * @restrict EAC
41425  *
41426  * @description
41427  * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
41428  *
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.
41431  *
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.
41436  *
41437  * @element ANY
41438  *
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.
41441  *
41442  * @example
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">
41447  *     <script>
41448  *       angular.module('transcludeExample', [])
41449  *        .directive('pane', function(){
41450  *           return {
41451  *             restrict: 'E',
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>' +
41457  *                       '</div>'
41458  *           };
41459  *       })
41460  *       .controller('ExampleController', ['$scope', function($scope) {
41461  *         $scope.title = 'Lorem Ipsum';
41462  *         $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
41463  *       }]);
41464  *     </script>
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>
41469  *     </div>
41470  *   </file>
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');
41481  *      });
41482  *   </file>
41483  * </example>
41484  *
41485  * @example
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.
41489  *
41490  * <example module="transcludeFallbackContentExample" name="ng-transclude">
41491  * <file name="index.html">
41492  * <script>
41493  * angular.module('transcludeFallbackContentExample', [])
41494  * .directive('myButton', function(){
41495  *             return {
41496  *               restrict: 'E',
41497  *               transclude: true,
41498  *               scope: true,
41499  *               template: '<button style="cursor: pointer;">' +
41500  *                           '<ng-transclude>' +
41501  *                             '<b style="color: red;">Button1</b>' +
41502  *                           '</ng-transclude>' +
41503  *                         '</button>'
41504  *             };
41505  *         });
41506  * </script>
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>
41512  * </my-button>
41513  * </file>
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');
41518  *        });
41519  * </file>
41520  * </example>
41521  *
41522  * @example
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">
41527  *    <style>
41528  *      .title, .footer {
41529  *        background-color: gray
41530  *      }
41531  *    </style>
41532  *    <div ng-controller="ExampleController">
41533  *      <input ng-model="title" aria-label="title"> <br/>
41534  *      <textarea ng-model="text" aria-label="text"></textarea> <br/>
41535  *      <pane>
41536  *        <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
41537  *        <pane-body><p>{{text}}</p></pane-body>
41538  *      </pane>
41539  *    </div>
41540  *   </file>
41541  *   <file name="app.js">
41542  *    angular.module('multiSlotTranscludeExample', [])
41543  *     .directive('pane', function() {
41544  *        return {
41545  *          restrict: 'E',
41546  *          transclude: {
41547  *            'title': '?paneTitle',
41548  *            'body': 'paneBody',
41549  *            'footer': '?paneFooter'
41550  *          },
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>' +
41555  *                    '</div>'
41556  *        };
41557  *    })
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...';
41562  *    }]);
41563  *   </file>
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');
41575  *      });
41576  *   </file>
41577  * </example>
41578  */
41579 var ngTranscludeMinErr = minErr('ngTransclude');
41580 var ngTranscludeDirective = ['$compile', function($compile) {
41581   return {
41582     restrict: 'EAC',
41583     terminal: true,
41584     compile: function ngTranscludeCompile(tElement) {
41585
41586       // Remove and cache any original content to act as a fallback
41587       var fallbackLinkFn = $compile(tElement.contents());
41588       tElement.empty();
41589
41590       return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {
41591
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. ' +
41596           'Element: {0}',
41597           startingTag($element));
41598         }
41599
41600
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 = '';
41604         }
41605         var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
41606
41607         // If the slot is required and no transclusion content is provided then this call will throw an error
41608         $transclude(ngTranscludeCloneAttachFn, null, slotName);
41609
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();
41613         }
41614
41615         function ngTranscludeCloneAttachFn(clone, transcludedScope) {
41616           if (clone.length) {
41617             $element.append(clone);
41618           } else {
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();
41623           }
41624         }
41625
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);
41631           });
41632         }
41633       };
41634     }
41635   };
41636 }];
41637
41638 /**
41639  * @ngdoc directive
41640  * @name script
41641  * @restrict E
41642  *
41643  * @description
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`.
41649  *
41650  * @param {string} type Must be set to `'text/ng-template'`.
41651  * @param {string} id Cache name of the template.
41652  *
41653  * @example
41654   <example  name="script-tag">
41655     <file name="index.html">
41656       <script type="text/ng-template" id="/tpl.html">
41657         Content of the template.
41658       </script>
41659
41660       <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
41661       <div id="tpl-content" ng-include src="currentTpl"></div>
41662     </file>
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/);
41667       });
41668     </file>
41669   </example>
41670  */
41671 var scriptDirective = ['$templateCache', function($templateCache) {
41672   return {
41673     restrict: 'E',
41674     terminal: true,
41675     compile: function(element, attr) {
41676       if (attr.type === 'text/ng-template') {
41677         var templateUrl = attr.id,
41678             text = element[0].text;
41679
41680         $templateCache.put(templateUrl, text);
41681       }
41682     }
41683   };
41684 }];
41685
41686 /* exported selectDirective, optionDirective */
41687
41688 var noopNgModelController = { $setViewValue: noop, $render: noop };
41689
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;
41696   }
41697 }
41698
41699 /**
41700  * @ngdoc type
41701  * @name  select.SelectController
41702  * @description
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.
41706  */
41707 var SelectController =
41708         ['$element', '$scope', /** @this */ function($element, $scope) {
41709
41710   var self = this,
41711       optionsMap = new HashMap();
41712
41713   // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
41714   self.ngModelCtrl = noopNgModelController;
41715
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.
41719   //
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);
41728   };
41729
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;
41733   });
41734
41735   self.removeUnknownOption = function() {
41736     if (self.unknownOption.parent()) self.unknownOption.remove();
41737   };
41738
41739
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();
41745   };
41746
41747
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
41755     } else {
41756       if (value == null && self.emptyOption) {
41757         self.removeUnknownOption();
41758         $element.val('');
41759       } else {
41760         self.renderUnknownOption(value);
41761       }
41762     }
41763   };
41764
41765
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;
41770
41771     assertNotHasOwnProperty(value, '"option value"');
41772     if (value === '') {
41773       self.emptyOption = element;
41774     }
41775     var count = optionsMap.get(value) || 0;
41776     optionsMap.put(value, count + 1);
41777     self.ngModelCtrl.$render();
41778     chromeHack(element);
41779   };
41780
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);
41784     if (count) {
41785       if (count === 1) {
41786         optionsMap.remove(value);
41787         if (value === '') {
41788           self.emptyOption = undefined;
41789         }
41790       } else {
41791         optionsMap.put(value, count - 1);
41792       }
41793     }
41794   };
41795
41796   // Check whether the select control has an option matching the given value
41797   self.hasOption = function(value) {
41798     return !!optionsMap.get(value);
41799   };
41800
41801
41802   self.registerOption = function(optionScope, optionElement, optionAttrs, hasDynamicValueAttr, interpolateTextFn) {
41803
41804     if (hasDynamicValueAttr) {
41805       // either "value" is interpolated directly, or set by ngValue
41806       var oldVal;
41807       optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
41808         if (isDefined(oldVal)) {
41809           self.removeOption(oldVal);
41810         }
41811         oldVal = newVal;
41812         self.addOption(newVal, optionElement);
41813       });
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);
41820         }
41821         self.addOption(newVal, optionElement);
41822       });
41823     } else {
41824       // The value attribute is static
41825       self.addOption(optionAttrs.value, optionElement);
41826     }
41827
41828     optionElement.on('$destroy', function() {
41829       self.removeOption(optionAttrs.value);
41830       self.ngModelCtrl.$render();
41831     });
41832   };
41833 }];
41834
41835 /**
41836  * @ngdoc directive
41837  * @name select
41838  * @restrict E
41839  *
41840  * @description
41841  * HTML `SELECT` element with angular data-binding.
41842  *
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.
41847  *
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`.
41854  *
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.
41860  * </div>
41861  *
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.
41864  *
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.
41868  *
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.
41875  * </div>
41876  *
41877  *
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`}.
41890  *
41891  * @example
41892  * ### Simple `select` elements with static options
41893  *
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>
41902  *     </select><br>
41903  *
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>
41909  *     </select><br>
41910  *     <button ng-click="forceUnknownOption()">Force unknown option</button><br>
41911  *     <tt>singleSelect = {{data.singleSelect}}</tt>
41912  *
41913  *     <hr>
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>
41919  *     </select><br>
41920  *     <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
41921  *   </form>
41922  * </div>
41923  * </file>
41924  * <file name="app.js">
41925  *  angular.module('staticSelect', [])
41926  *    .controller('ExampleController', ['$scope', function($scope) {
41927  *      $scope.data = {
41928  *       singleSelect: null,
41929  *       multipleSelect: [],
41930  *       option1: 'option-1'
41931  *      };
41932  *
41933  *      $scope.forceUnknownOption = function() {
41934  *        $scope.data.singleSelect = 'nonsense';
41935  *      };
41936  *   }]);
41937  * </file>
41938  *</example>
41939  *
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>
41948  *     </select>
41949  *   </form>
41950  *   <hr>
41951  *   <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
41952  * </div>
41953  * </file>
41954  * <file name="app.js">
41955  *  angular.module('ngrepeatSelect', [])
41956  *    .controller('ExampleController', ['$scope', function($scope) {
41957  *      $scope.data = {
41958  *       repeatSelect: null,
41959  *       availableOptions: [
41960  *         {id: '1', name: 'Option A'},
41961  *         {id: '2', name: 'Option B'},
41962  *         {id: '3', name: 'Option C'}
41963  *       ]
41964  *      };
41965  *   }]);
41966  * </file>
41967  *</example>
41968  *
41969  *
41970  * ### Using `select` with `ngOptions` and setting a default value
41971  * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
41972  *
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>
41981  *   </form>
41982  *   <hr>
41983  *   <tt>option = {{data.selectedOption}}</tt><br/>
41984  * </div>
41985  * </file>
41986  * <file name="app.js">
41987  *  angular.module('defaultValueSelect', [])
41988  *    .controller('ExampleController', ['$scope', function($scope) {
41989  *      $scope.data = {
41990  *       availableOptions: [
41991  *         {id: '1', name: 'Option A'},
41992  *         {id: '2', name: 'Option B'},
41993  *         {id: '3', name: 'Option C'}
41994  *       ],
41995  *       selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
41996  *       };
41997  *   }]);
41998  * </file>
41999  *</example>
42000  *
42001  *
42002  * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
42003  *
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>
42010  *     </select>
42011  *     {{ model }}
42012  *   </file>
42013  *   <file name="app.js">
42014  *     angular.module('nonStringSelect', [])
42015  *       .run(function($rootScope) {
42016  *         $rootScope.model = { id: 2 };
42017  *       })
42018  *       .directive('convertToNumber', function() {
42019  *         return {
42020  *           require: 'ngModel',
42021  *           link: function(scope, element, attrs, ngModel) {
42022  *             ngModel.$parsers.push(function(val) {
42023  *               return parseInt(val, 10);
42024  *             });
42025  *             ngModel.$formatters.push(function(val) {
42026  *               return '' + val;
42027  *             });
42028  *           }
42029  *         };
42030  *       });
42031  *   </file>
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');
42035  *     });
42036  *   </file>
42037  * </example>
42038  *
42039  */
42040 var selectDirective = function() {
42041
42042   return {
42043     restrict: 'E',
42044     require: ['select', '?ngModel'],
42045     controller: SelectController,
42046     priority: 1,
42047     link: {
42048       pre: selectPreLink,
42049       post: selectPostLink
42050     }
42051   };
42052
42053   function selectPreLink(scope, element, attr, ctrls) {
42054
42055       // if ngModel is not defined, we don't need to do anything
42056       var ngModelCtrl = ctrls[1];
42057       if (!ngModelCtrl) return;
42058
42059       var selectCtrl = ctrls[0];
42060
42061       selectCtrl.ngModelCtrl = ngModelCtrl;
42062
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());
42069         });
42070       });
42071
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) {
42077
42078         // Read value now needs to check each option to see if it is selected
42079         selectCtrl.readValue = function readMultipleValue() {
42080           var array = [];
42081           forEach(element.find('option'), function(option) {
42082             if (option.selected) {
42083               array.push(option.value);
42084             }
42085           });
42086           return array;
42087         };
42088
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));
42094           });
42095         };
42096
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();
42104           }
42105           lastViewRef = ngModelCtrl.$viewValue;
42106         });
42107
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;
42112         };
42113
42114       }
42115     }
42116
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;
42121
42122       var selectCtrl = ctrls[0];
42123
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);
42131       };
42132     }
42133 };
42134
42135
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) {
42140   return {
42141     restrict: 'E',
42142     priority: 100,
42143     compile: function(element, attr) {
42144       var hasDynamicValueAttr, interpolateTextFn;
42145
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);
42153       } else {
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());
42159         }
42160       }
42161
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
42169
42170         if (selectCtrl) {
42171           selectCtrl.registerOption(scope, element, attr, hasDynamicValueAttr, interpolateTextFn);
42172         }
42173       };
42174     }
42175   };
42176 }];
42177
42178 /**
42179  * @ngdoc directive
42180  * @name ngRequired
42181  * @restrict A
42182  *
42183  * @description
42184  *
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.
42188  *
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}
42192  * for more info.
42193  *
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.
42199  *
42200  * @example
42201  * <example name="ngRequiredDirective" module="ngRequiredExample">
42202  *   <file name="index.html">
42203  *     <script>
42204  *       angular.module('ngRequiredExample', [])
42205  *         .controller('ExampleController', ['$scope', function($scope) {
42206  *           $scope.required = true;
42207  *         }]);
42208  *     </script>
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" />
42213  *         <br>
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>
42216  *         <hr>
42217  *         required error set? = <code>{{form.input.$error.required}}</code><br>
42218  *         model = <code>{{model}}</code>
42219  *       </form>
42220  *     </div>
42221  *   </file>
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'));
42226
42227        it('should set the required error', function() {
42228          expect(required.getText()).toContain('true');
42229
42230          input.sendKeys('123');
42231          expect(required.getText()).not.toContain('true');
42232          expect(model.getText()).toContain('123');
42233        });
42234  *   </file>
42235  * </example>
42236  */
42237 var requiredDirective = function() {
42238   return {
42239     restrict: 'A',
42240     require: '?ngModel',
42241     link: function(scope, elm, attr, ctrl) {
42242       if (!ctrl) return;
42243       attr.required = true; // force truthy in case we are on non input element
42244
42245       ctrl.$validators.required = function(modelValue, viewValue) {
42246         return !attr.required || !ctrl.$isEmpty(viewValue);
42247       };
42248
42249       attr.$observe('required', function() {
42250         ctrl.$validate();
42251       });
42252     }
42253   };
42254 };
42255
42256 /**
42257  * @ngdoc directive
42258  * @name ngPattern
42259  *
42260  * @description
42261  *
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.
42264  *
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$')`.
42271  *
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
42275  * account.
42276  * </div>
42277  *
42278  * <div class="alert alert-info">
42279  * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
42280  * differences:
42281  * <ol>
42282  *   <li>
42283  *     `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
42284  *     not available.
42285  *   </li>
42286  *   <li>
42287  *     The `ngPattern` attribute must be an expression, while the `pattern` value must be
42288  *     interpolated.
42289  *   </li>
42290  * </ol>
42291  * </div>
42292  *
42293  * @example
42294  * <example name="ngPatternDirective" module="ngPatternExample">
42295  *   <file name="index.html">
42296  *     <script>
42297  *       angular.module('ngPatternExample', [])
42298  *         .controller('ExampleController', ['$scope', function($scope) {
42299  *           $scope.regex = '\\d+';
42300  *         }]);
42301  *     </script>
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" />
42306  *         <br>
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>
42309  *         <hr>
42310  *         input valid? = <code>{{form.input.$valid}}</code><br>
42311  *         model = <code>{{model}}</code>
42312  *       </form>
42313  *     </div>
42314  *   </file>
42315  *   <file name="protractor.js" type="protractor">
42316        var model = element(by.binding('model'));
42317        var input = element(by.id('input'));
42318
42319        it('should validate the input with the default pattern', function() {
42320          input.sendKeys('aaa');
42321          expect(model.getText()).not.toContain('aaa');
42322
42323          input.clear().then(function() {
42324            input.sendKeys('123');
42325            expect(model.getText()).toContain('123');
42326          });
42327        });
42328  *   </file>
42329  * </example>
42330  */
42331 var patternDirective = function() {
42332   return {
42333     restrict: 'A',
42334     require: '?ngModel',
42335     link: function(scope, elm, attr, ctrl) {
42336       if (!ctrl) return;
42337
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 + '$');
42342         }
42343
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));
42348         }
42349
42350         regexp = regex || undefined;
42351         ctrl.$validate();
42352       });
42353
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);
42357       };
42358     }
42359   };
42360 };
42361
42362 /**
42363  * @ngdoc directive
42364  * @name ngMaxlength
42365  *
42366  * @description
42367  *
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.
42370  *
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.
42374  *
42375  * <div class="alert alert-info">
42376  * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
42377  * differences:
42378  * <ol>
42379  *   <li>
42380  *     `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
42381  *     validation is not available.
42382  *   </li>
42383  *   <li>
42384  *     The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
42385  *     interpolated.
42386  *   </li>
42387  * </ol>
42388  * </div>
42389  *
42390  * @example
42391  * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
42392  *   <file name="index.html">
42393  *     <script>
42394  *       angular.module('ngMaxlengthExample', [])
42395  *         .controller('ExampleController', ['$scope', function($scope) {
42396  *           $scope.maxlength = 5;
42397  *         }]);
42398  *     </script>
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" />
42403  *         <br>
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>
42406  *         <hr>
42407  *         input valid? = <code>{{form.input.$valid}}</code><br>
42408  *         model = <code>{{model}}</code>
42409  *       </form>
42410  *     </div>
42411  *   </file>
42412  *   <file name="protractor.js" type="protractor">
42413        var model = element(by.binding('model'));
42414        var input = element(by.id('input'));
42415
42416        it('should validate the input with the default maxlength', function() {
42417          input.sendKeys('abcdef');
42418          expect(model.getText()).not.toContain('abcdef');
42419
42420          input.clear().then(function() {
42421            input.sendKeys('abcde');
42422            expect(model.getText()).toContain('abcde');
42423          });
42424        });
42425  *   </file>
42426  * </example>
42427  */
42428 var maxlengthDirective = function() {
42429   return {
42430     restrict: 'A',
42431     require: '?ngModel',
42432     link: function(scope, elm, attr, ctrl) {
42433       if (!ctrl) return;
42434
42435       var maxlength = -1;
42436       attr.$observe('maxlength', function(value) {
42437         var intVal = toInt(value);
42438         maxlength = isNumberNaN(intVal) ? -1 : intVal;
42439         ctrl.$validate();
42440       });
42441       ctrl.$validators.maxlength = function(modelValue, viewValue) {
42442         return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
42443       };
42444     }
42445   };
42446 };
42447
42448 /**
42449  * @ngdoc directive
42450  * @name ngMinlength
42451  *
42452  * @description
42453  *
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.
42456  *
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.
42460  *
42461  * <div class="alert alert-info">
42462  * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
42463  * differences:
42464  * <ol>
42465  *   <li>
42466  *     `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
42467  *     validation is not available.
42468  *   </li>
42469  *   <li>
42470  *     The `ngMinlength` value must be an expression, while the `minlength` value must be
42471  *     interpolated.
42472  *   </li>
42473  * </ol>
42474  * </div>
42475  *
42476  * @example
42477  * <example name="ngMinlengthDirective" module="ngMinlengthExample">
42478  *   <file name="index.html">
42479  *     <script>
42480  *       angular.module('ngMinlengthExample', [])
42481  *         .controller('ExampleController', ['$scope', function($scope) {
42482  *           $scope.minlength = 3;
42483  *         }]);
42484  *     </script>
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" />
42489  *         <br>
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>
42492  *         <hr>
42493  *         input valid? = <code>{{form.input.$valid}}</code><br>
42494  *         model = <code>{{model}}</code>
42495  *       </form>
42496  *     </div>
42497  *   </file>
42498  *   <file name="protractor.js" type="protractor">
42499        var model = element(by.binding('model'));
42500        var input = element(by.id('input'));
42501
42502        it('should validate the input with the default minlength', function() {
42503          input.sendKeys('ab');
42504          expect(model.getText()).not.toContain('ab');
42505
42506          input.sendKeys('abc');
42507          expect(model.getText()).toContain('abc');
42508        });
42509  *   </file>
42510  * </example>
42511  */
42512 var minlengthDirective = function() {
42513   return {
42514     restrict: 'A',
42515     require: '?ngModel',
42516     link: function(scope, elm, attr, ctrl) {
42517       if (!ctrl) return;
42518
42519       var minlength = 0;
42520       attr.$observe('minlength', function(value) {
42521         minlength = toInt(value) || 0;
42522         ctrl.$validate();
42523       });
42524       ctrl.$validators.minlength = function(modelValue, viewValue) {
42525         return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
42526       };
42527     }
42528   };
42529 };
42530
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.');
42535   }
42536   return;
42537 }
42538
42539 //try to bind to jquery now so that one can write jqLite(document).ready()
42540 //but we will rebind on bootstrap again.
42541 bindJQuery();
42542
42543 publishExternalAPI(angular);
42544
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) {
42548   n = n + '';
42549   var i = n.indexOf('.');
42550   return (i == -1) ? 0 : n.length - i - 1;
42551 }
42552
42553 function getVF(n, opt_precision) {
42554   var v = opt_precision;
42555
42556   if (undefined === v) {
42557     v = Math.min(getDecimals(n), 3);
42558   }
42559
42560   var base = Math.pow(10, v);
42561   var f = ((n * base) | 0) % base;
42562   return {v: v, f: f};
42563 }
42564
42565 $provide.value("$locale", {
42566   "DATETIME_FORMATS": {
42567     "AMPMS": [
42568       "AM",
42569       "PM"
42570     ],
42571     "DAY": [
42572       "Sunday",
42573       "Monday",
42574       "Tuesday",
42575       "Wednesday",
42576       "Thursday",
42577       "Friday",
42578       "Saturday"
42579     ],
42580     "ERANAMES": [
42581       "Before Christ",
42582       "Anno Domini"
42583     ],
42584     "ERAS": [
42585       "BC",
42586       "AD"
42587     ],
42588     "FIRSTDAYOFWEEK": 6,
42589     "MONTH": [
42590       "January",
42591       "February",
42592       "March",
42593       "April",
42594       "May",
42595       "June",
42596       "July",
42597       "August",
42598       "September",
42599       "October",
42600       "November",
42601       "December"
42602     ],
42603     "SHORTDAY": [
42604       "Sun",
42605       "Mon",
42606       "Tue",
42607       "Wed",
42608       "Thu",
42609       "Fri",
42610       "Sat"
42611     ],
42612     "SHORTMONTH": [
42613       "Jan",
42614       "Feb",
42615       "Mar",
42616       "Apr",
42617       "May",
42618       "Jun",
42619       "Jul",
42620       "Aug",
42621       "Sep",
42622       "Oct",
42623       "Nov",
42624       "Dec"
42625     ],
42626     "STANDALONEMONTH": [
42627       "January",
42628       "February",
42629       "March",
42630       "April",
42631       "May",
42632       "June",
42633       "July",
42634       "August",
42635       "September",
42636       "October",
42637       "November",
42638       "December"
42639     ],
42640     "WEEKENDRANGE": [
42641       5,
42642       6
42643     ],
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"
42652   },
42653   "NUMBER_FORMATS": {
42654     "CURRENCY_SYM": "$",
42655     "DECIMAL_SEP": ".",
42656     "GROUP_SEP": ",",
42657     "PATTERNS": [
42658       {
42659         "gSize": 3,
42660         "lgSize": 3,
42661         "maxFrac": 3,
42662         "minFrac": 0,
42663         "minInt": 1,
42664         "negPre": "-",
42665         "negSuf": "",
42666         "posPre": "",
42667         "posSuf": ""
42668       },
42669       {
42670         "gSize": 3,
42671         "lgSize": 3,
42672         "maxFrac": 2,
42673         "minFrac": 2,
42674         "minInt": 1,
42675         "negPre": "-\u00a4",
42676         "negSuf": "",
42677         "posPre": "\u00a4",
42678         "posSuf": ""
42679       }
42680     ]
42681   },
42682   "id": "en-us",
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;}
42685 });
42686 }]);
42687
42688 /**
42689  * Setup file for the Scenario.
42690  * Must be first in the compilation/bootstrap list.
42691  */
42692
42693 // Public namespace
42694 angular.scenario = angular.scenario || {};
42695
42696 /**
42697  * Expose jQuery (e.g. for custom dsl extensions).
42698  */
42699 angular.scenario.jQuery = _jQuery;
42700
42701 /**
42702  * Defines a new output format.
42703  *
42704  * @param {string} name the name of the new output format
42705  * @param {function()} fn function(context, runner) that generates the output
42706  */
42707 angular.scenario.output = angular.scenario.output || function(name, fn) {
42708   angular.scenario.output[name] = fn;
42709 };
42710
42711 /**
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.
42715  *
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
42718  *   functions.
42719  *
42720  * @param {string} name The name of the statement
42721  * @param {function()} fn Factory function(), return a function for
42722  *  the statement.
42723  */
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
42727     /** @this */
42728     function executeStatement(statement, args) {
42729       var result = statement.apply(this, args);
42730       if (angular.isFunction(result) || result instanceof angular.scenario.Future) {
42731         return result;
42732       }
42733       var self = this;
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);
42739           };
42740         } else {
42741           chain[name] = value;
42742         }
42743       });
42744       return chain;
42745     }
42746     var statement = fn.apply(this, arguments);
42747     return /** @this */ function() {
42748       return executeStatement.call(this, statement, arguments);
42749     };
42750   };
42751 };
42752
42753 /**
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
42757  * created for you.
42758  *
42759  * @param {string} name The name of the matcher
42760  * @param {function()} fn The matching function(expected).
42761  */
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);
42767     var self = this;
42768     this.addFuture('expect ' + description,
42769       function(done) {
42770         var error;
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);
42776         }
42777         done(error);
42778     });
42779   };
42780 };
42781
42782 /**
42783  * Initialize the scenario runner and run !
42784  *
42785  * Access global window and document object
42786  * Access $runner through closure
42787  *
42788  * @param {Object=} config Config options
42789  */
42790 angular.scenario.setUpAndRun = function(config) {
42791   var href = window.location.href;
42792   var body = _jQuery(window.document.body);
42793   var output = [];
42794   var objModel = new angular.scenario.ObjectModel($runner);
42795
42796   if (config && config.scenario_output) {
42797     output = config.scenario_output.split(',');
42798   }
42799
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);
42805     }
42806   });
42807
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.'
42813     );
42814     return;
42815   }
42816
42817   var appFrame = body.append('<div id="application"></div>').find('#application');
42818   var application = new angular.scenario.Application(appFrame);
42819
42820   $runner.on('RunnerEnd', function() {
42821     appFrame.css('display', 'none');
42822     appFrame.find('iframe').attr('src', 'about:blank');
42823   });
42824
42825   $runner.on('RunnerError', function(error) {
42826     if (window.console) {
42827       console.log(formatException(error));
42828     } else {
42829       // Do something for IE
42830       // eslint-disable-next-line no-alert
42831       alert(error);
42832     }
42833   });
42834
42835   $runner.run(application);
42836 };
42837
42838 /**
42839  * Iterates through list with iterator function that must call the
42840  * continueFunction to continue iterating.
42841  *
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.
42846  */
42847 function asyncForEach(list, iterator, done) {
42848   var i = 0;
42849   function loop(error, index) {
42850     if (index && index > i) {
42851       i = index;
42852     }
42853     if (error || i >= list.length) {
42854       done(error);
42855     } else {
42856       try {
42857         iterator(list[i++], loop);
42858       } catch (e) {
42859         done(e);
42860       }
42861     }
42862   }
42863   loop();
42864 }
42865
42866 /**
42867  * Formats an exception into a string with the stack trace, but limits
42868  * to a specific line length.
42869  *
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
42872  *  default is 5.
42873  */
42874 function formatException(error, maxStackLines) {
42875   maxStackLines = maxStackLines || 5;
42876   var message = error.toString();
42877   if (error.stack) {
42878     var stack = error.stack.split('\n');
42879     if (stack[0].indexOf(message) === -1) {
42880       maxStackLines++;
42881       stack.unshift(error.message);
42882     }
42883     message = stack.slice(0, maxStackLines).join('\n');
42884   }
42885   return message;
42886 }
42887
42888 /**
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.
42891  *
42892  * Note: this returns another function because accessing .stack is very
42893  * expensive in Chrome.
42894  *
42895  * @param {Number} offset Number of stack lines to skip
42896  */
42897 function callerFile(offset) {
42898   var error = new Error();
42899
42900   return function() {
42901     var line = (error.stack || '').split('\n')[offset];
42902
42903     // Clean up the stack trace line
42904     if (line) {
42905       if (line.indexOf('@') !== -1) {
42906         // Firefox
42907         line = line.substring(line.indexOf('@') + 1);
42908       } else {
42909         // Chrome
42910         line = line.substring(line.indexOf('(') + 1).replace(')', '');
42911       }
42912     }
42913
42914     return line || '';
42915   };
42916 }
42917
42918
42919 /**
42920  * Don't use the jQuery trigger method since it works incorrectly.
42921  *
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.
42925  *
42926  * To work around this we instead use our own handler that fires a real event.
42927  */
42928 (function(fn) {
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));
42936       });
42937
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;
42941     }
42942     return parentTrigger.apply(this, arguments);
42943   };
42944 })(_jQuery.fn);
42945
42946 /**
42947  * Finds all bindings with the substring match of name and returns an
42948  * array of their values.
42949  *
42950  * @param {string} bindExp The name to match
42951  * @return {Array.<string>} String of binding values
42952  */
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) {
42959       if (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) === '|';
42964         }
42965       }
42966     };
42967   } else if (bindExp) {
42968     match = function(actualExp) {
42969       return actualExp && bindExp.exec(actualExp);
42970     };
42971   } else {
42972     match = function(actualExp) {
42973       return !!actualExp;
42974     };
42975   }
42976   var selection = this.find(bindSelector);
42977   if (this.is(bindSelector)) {
42978     selection = selection.add(this);
42979   }
42980
42981   function push(value) {
42982     if (angular.isUndefined(value)) {
42983       value = '';
42984     } else if (typeof value !== 'string') {
42985       value = angular.toJson(value);
42986     }
42987     result.push('' + value);
42988   }
42989
42990   selection.each(/* @this Node */ function() {
42991     var element = windowJquery(this),
42992         bindings;
42993     if ((bindings = element.data('$binding'))) {
42994       for (var expressions = [], binding, j = 0, jj = bindings.length; j < jj; j++) {
42995         binding = bindings[j];
42996
42997         if (binding.expressions) {
42998           expressions = binding.expressions;
42999         } else {
43000           expressions = [binding];
43001         }
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));
43007           }
43008         }
43009       }
43010     }
43011   });
43012   return result;
43013 };
43014
43015 (function() {
43016   /**
43017    * Triggers a browser event. Attempts to choose the right event if one is
43018    * not specified.
43019    *
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
43024    */
43025   window.browserTrigger = function browserTrigger(element, eventType, eventData) {
43026     if (element && !element.nodeName) element = element[0];
43027     if (!element) return;
43028
43029     eventData = eventData || {};
43030     var relatedTarget = eventData.relatedTarget || element;
43031     var keys = eventData.keys;
43032     var x = eventData.x;
43033     var y = eventData.y;
43034
43035     var inputType = (element.type) ? element.type.toLowerCase() : null,
43036         nodeName = element.nodeName.toLowerCase();
43037     if (!eventType) {
43038       eventType = {
43039         'text':            'change',
43040         'textarea':        'change',
43041         'hidden':          'change',
43042         'password':        'change',
43043         'button':          'click',
43044         'submit':          'click',
43045         'reset':           'click',
43046         'image':           'click',
43047         'checkbox':        'click',
43048         'radio':           'click',
43049         'select-one':      'change',
43050         'select-multiple': 'change',
43051         '_default_':       'click'
43052       }[inputType || '_default_'];
43053     }
43054
43055     if (nodeName === 'option') {
43056       element.parentNode.value = element.value;
43057       element = element.parentNode;
43058       eventType = 'change';
43059     }
43060
43061     keys = keys || [];
43062     function pressed(key) {
43063       return keys.indexOf(key) !== -1;
43064     }
43065
43066     var evnt;
43067     if (/transitionend/.test(eventType)) {
43068       if (window.WebKitTransitionEvent) {
43069         evnt = new window.WebKitTransitionEvent(eventType, eventData);
43070         evnt.initEvent(eventType, false, true);
43071       } else {
43072         try {
43073           evnt = new window.TransitionEvent(eventType, eventData);
43074         } catch (e) {
43075           evnt = window.document.createEvent('TransitionEvent');
43076           evnt.initTransitionEvent(eventType, null, null, null, eventData.elapsedTime || 0);
43077         }
43078       }
43079     } else if (/animationend/.test(eventType)) {
43080       if (window.WebKitAnimationEvent) {
43081         evnt = new window.WebKitAnimationEvent(eventType, eventData);
43082         evnt.initEvent(eventType, false, true);
43083       } else {
43084         try {
43085           evnt = new window.AnimationEvent(eventType, eventData);
43086         } catch (e) {
43087           evnt = window.document.createEvent('AnimationEvent');
43088           evnt.initAnimationEvent(eventType, null, null, null, eventData.elapsedTime || 0);
43089         }
43090       }
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;
43104     } else {
43105       evnt = window.document.createEvent('MouseEvents');
43106       x = x || 0;
43107       y = y || 0;
43108       evnt.initMouseEvent(eventType, true, true, window, 0, x, y, x, y, pressed('ctrl'),
43109           pressed('alt'), pressed('shift'), pressed('meta'), 0, relatedTarget);
43110     }
43111
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
43114      * read */
43115     evnt.$manualTimeStamp = eventData.timeStamp;
43116
43117     if (!evnt) return;
43118
43119     var originalPreventDefault = evnt.preventDefault,
43120         appWindow = element.ownerDocument.defaultView,
43121         fakeProcessDefault = true,
43122         finalProcessDefault,
43123         angular = appWindow.angular || {};
43124
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);
43130     };
43131
43132     if (!eventData.bubbles || supportsEventBubblingInDetachedTree() || isAttachedToDocument(element)) {
43133       element.dispatchEvent(evnt);
43134     } else {
43135       triggerForPath(element, evnt);
43136     }
43137
43138     finalProcessDefault = !(angular['ff-684208-preventDefault'] || !fakeProcessDefault);
43139
43140     delete angular['ff-684208-preventDefault'];
43141
43142     return finalProcessDefault;
43143   };
43144
43145   function supportsTouchEvents() {
43146     if ('_cached' in supportsTouchEvents) {
43147       return supportsTouchEvents._cached;
43148     }
43149     if (!window.document.createTouch || !window.document.createTouchList) {
43150       supportsTouchEvents._cached = false;
43151       return false;
43152     }
43153     try {
43154       window.document.createEvent('TouchEvent');
43155     } catch (e) {
43156       supportsTouchEvents._cached = false;
43157       return false;
43158     }
43159     supportsTouchEvents._cached = true;
43160     return true;
43161   }
43162
43163   function createTouchEvent(element, eventType, x, y) {
43164     var evnt = new window.Event(eventType);
43165     x = x || 0;
43166     y = y || 0;
43167
43168     var touch = window.document.createTouch(window, element, Date.now(), x, y, x, y);
43169     var touches = window.document.createTouchList(touch);
43170
43171     evnt.touches = touches;
43172
43173     return evnt;
43174   }
43175
43176   function supportsEventBubblingInDetachedTree() {
43177     if ('_cached' in supportsEventBubblingInDetachedTree) {
43178       return supportsEventBubblingInDetachedTree._cached;
43179     }
43180     supportsEventBubblingInDetachedTree._cached = false;
43181     var doc = window.document;
43182     if (doc) {
43183       var parent = doc.createElement('div'),
43184           child = parent.cloneNode();
43185       parent.appendChild(child);
43186       parent.addEventListener('e', function() {
43187         supportsEventBubblingInDetachedTree._cached = true;
43188       });
43189       var evnt = window.document.createEvent('Events');
43190       evnt.initEvent('e', true, true);
43191       child.dispatchEvent(evnt);
43192     }
43193     return supportsEventBubblingInDetachedTree._cached;
43194   }
43195
43196   function triggerForPath(element, evnt) {
43197     var stop = false;
43198
43199     var _stopPropagation = evnt.stopPropagation;
43200     evnt.stopPropagation = function() {
43201       stop = true;
43202       _stopPropagation.apply(evnt, arguments);
43203     };
43204     patchEventTargetForBubbling(evnt, element);
43205     do {
43206       element.dispatchEvent(evnt);
43207       // eslint-disable-next-line no-unmodified-loop-condition
43208     } while (!stop && (element = element.parentNode));
43209   }
43210
43211   function patchEventTargetForBubbling(event, target) {
43212     event._target = target;
43213     Object.defineProperty(event, 'target', {get: function() { return this._target;}});
43214   }
43215
43216   function isAttachedToDocument(element) {
43217     while ((element = element.parentNode)) {
43218         if (element === window) {
43219             return true;
43220         }
43221     }
43222     return false;
43223   }
43224 })();
43225
43226 /**
43227  * Represents the application currently being tested and abstracts usage
43228  * of iframes or separate windows.
43229  *
43230  * @param {Object} context jQuery wrapper around HTML context.
43231  */
43232 angular.scenario.Application = function(context) {
43233   this.context = context;
43234   context.append(
43235     '<h2>Current URL: <a href="about:blank">None</a></h2>' +
43236     '<div id="test-frames"></div>'
43237   );
43238 };
43239
43240 /**
43241  * Gets the jQuery collection of frames. Don't use this directly because
43242  * frames may go stale.
43243  *
43244  * @private
43245  * @return {Object} jQuery collection
43246  */
43247 angular.scenario.Application.prototype.getFrame_ = function() {
43248   return this.context.find('#test-frames iframe:last');
43249 };
43250
43251 /**
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.
43254  *
43255  * @private
43256  * @return {Object} the window of the frame
43257  */
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.');
43262   }
43263   return contentWindow;
43264 };
43265
43266 /**
43267  * Changes the location of the frame.
43268  *
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.
43273  */
43274 angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) {
43275   var self = this;
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);
43285   } else {
43286     frame.remove();
43287     self.context.find('#test-frames').append('<iframe>');
43288     frame = self.getFrame_();
43289
43290     frame.on('load', function() {
43291       frame.off();
43292       try {
43293         var $window = self.getWindow_();
43294
43295         if (!$window.angular) {
43296           self.executeAction(loadFn);
43297           return;
43298         }
43299
43300         if (!$window.angular.resumeBootstrap) {
43301           $window.angular.resumeDeferredBootstrap = resumeDeferredBootstrap;
43302         } else {
43303           resumeDeferredBootstrap();
43304         }
43305
43306       } catch (e) {
43307         errorFn(e);
43308       }
43309
43310       function resumeDeferredBootstrap() {
43311         // Disable animations
43312         var $injector = $window.angular.resumeBootstrap([['$provide', function($provide) {
43313           return ['$animate', function($animate) {
43314             $animate.enabled(false);
43315           }];
43316         }]]);
43317         self.rootElement = $injector.get('$rootElement')[0];
43318         self.executeAction(loadFn);
43319       }
43320     }).attr('src', url);
43321
43322     // for IE compatibility set the name *after* setting the frame url
43323     frame[0].contentWindow.name = 'NG_DEFER_BOOTSTRAP!';
43324   }
43325   self.context.find('> h2 a').attr('href', url).text(url);
43326 };
43327
43328 /**
43329  * Executes a function in the context of the tested application. Will wait
43330  * for all pending angular xhr requests before executing.
43331  *
43332  * @param {function()} action The callback to execute. function($window, $document)
43333  *  $document is a jQuery wrapped document.
43334  */
43335 angular.scenario.Application.prototype.executeAction = function(action) {
43336   var self = this;
43337   var $window = this.getWindow_();
43338   if (!$window.document) {
43339     throw new Error('Sandbox Error: Application document not accessible.');
43340   }
43341   if (!$window.angular) {
43342     return action.call(this, $window, _jQuery($window.document));
43343   }
43344
43345   if (this.rootElement) {
43346     executeWithElement(this.rootElement);
43347   } else {
43348     angularInit($window.document, angular.bind(this, executeWithElement));
43349   }
43350
43351   function executeWithElement(element) {
43352     var $injector = $window.angular.element(element).injector();
43353     var $element = _jQuery(element);
43354
43355     $element.injector = function() {
43356       return $injector;
43357     };
43358
43359     $injector.invoke(function($browser) {
43360       $browser.notifyWhenNoOutstandingRequests(function() {
43361         action.call(self, $window, $element);
43362       });
43363     });
43364   }
43365 };
43366
43367 /**
43368  * The representation of define blocks. Don't used directly, instead use
43369  * define() in your tests.
43370  *
43371  * @param {string} descName Name of the block
43372  * @param {Object} parent describe or undefined if the root.
43373  */
43374 angular.scenario.Describe = function(descName, parent) {
43375   this.only = parent && parent.only;
43376   this.beforeEachFns = [];
43377   this.afterEachFns = [];
43378   this.its = [];
43379   this.children = [];
43380   this.name = descName;
43381   this.parent = parent;
43382   this.id = angular.scenario.Describe.id++;
43383
43384   /**
43385    * Calls all before functions.
43386    */
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);
43391   };
43392
43393   /**
43394    * Calls all after functions.
43395    */
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);
43400   };
43401 };
43402
43403 // Shared Unique ID generator for every describe block
43404 angular.scenario.Describe.id = 0;
43405
43406 // Shared Unique ID generator for every it (spec)
43407 angular.scenario.Describe.specId = 0;
43408
43409 /**
43410  * Defines a block to execute before each it or nested describe.
43411  *
43412  * @param {function()} body Body of the block.
43413  */
43414 angular.scenario.Describe.prototype.beforeEach = function(body) {
43415   this.beforeEachFns.push(body);
43416 };
43417
43418 /**
43419  * Defines a block to execute after each it or nested describe.
43420  *
43421  * @param {function()} body Body of the block.
43422  */
43423 angular.scenario.Describe.prototype.afterEach = function(body) {
43424   this.afterEachFns.push(body);
43425 };
43426
43427 /**
43428  * Creates a new describe block that's a child of this one.
43429  *
43430  * @param {string} name Name of the block. Appended to the parent block's name.
43431  * @param {function()} body Body of the block.
43432  */
43433 angular.scenario.Describe.prototype.describe = function(name, body) {
43434   var child = new angular.scenario.Describe(name, this);
43435   this.children.push(child);
43436   body.call(child);
43437 };
43438
43439 /**
43440  * Same as describe() but makes ddescribe blocks the only to run.
43441  *
43442  * @param {string} name Name of the test.
43443  * @param {function()} body Body of the block.
43444  */
43445 angular.scenario.Describe.prototype.ddescribe = function(name, body) {
43446   var child = new angular.scenario.Describe(name, this);
43447   child.only = true;
43448   this.children.push(child);
43449   body.call(child);
43450 };
43451
43452 /**
43453  * Use to disable a describe block.
43454  */
43455 angular.scenario.Describe.prototype.xdescribe = angular.noop;
43456
43457 /**
43458  * Defines a test.
43459  *
43460  * @param {string} name Name of the test.
43461  * @param {function()} body Body of the block.
43462  */
43463 angular.scenario.Describe.prototype.it = function(name, body) {
43464   this.its.push({
43465     id: angular.scenario.Describe.specId++,
43466     definition: this,
43467     only: this.only,
43468     name: name,
43469     before: this.setupBefore,
43470     body: body,
43471     after: this.setupAfter
43472   });
43473 };
43474
43475 /**
43476  * Same as it() but makes iit tests the only test to run.
43477  *
43478  * @param {string} name Name of the test.
43479  * @param {function()} body Body of the block.
43480  */
43481 angular.scenario.Describe.prototype.iit = function(name, body) {
43482   this.it.apply(this, arguments);
43483   this.its[this.its.length - 1].only = true;
43484 };
43485
43486 /**
43487  * Use to disable a test block.
43488  */
43489 angular.scenario.Describe.prototype.xit = angular.noop;
43490
43491 /**
43492  * Gets an array of functions representing all the tests (recursively).
43493  * that can be executed with SpecRunner's.
43494  *
43495  * @return {Array<Object>} Array of it blocks {
43496  *   definition : Object // parent Describe
43497  *   only: boolean
43498  *   name: string
43499  *   before: Function
43500  *   body: Function
43501  *   after: Function
43502  *  }
43503  */
43504 angular.scenario.Describe.prototype.getSpecs = function() {
43505   var specs = arguments[0] || [];
43506   angular.forEach(this.children, function(child) {
43507     child.getSpecs(specs);
43508   });
43509   angular.forEach(this.its, function(it) {
43510     specs.push(it);
43511   });
43512   var only = [];
43513   angular.forEach(specs, function(it) {
43514     if (it.only) {
43515       only.push(it);
43516     }
43517   });
43518   return (only.length && only) || specs;
43519 };
43520
43521 /**
43522  * A future action in a spec.
43523  *
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.
43527  */
43528 angular.scenario.Future = function(name, behavior, line) {
43529   this.name = name;
43530   this.behavior = behavior;
43531   this.fulfilled = false;
43532   this.value = undefined;
43533   this.parser = angular.identity;
43534   this.line = line || function() { return ''; };
43535 };
43536
43537 /**
43538  * Executes the behavior of the closure.
43539  *
43540  * @param {function()} doneFn Callback function(error, result)
43541  */
43542 angular.scenario.Future.prototype.execute = function(doneFn) {
43543   var self = this;
43544   this.behavior(function(error, result) {
43545     self.fulfilled = true;
43546     if (result) {
43547       try {
43548         result = self.parser(result);
43549       } catch (e) {
43550         error = e;
43551       }
43552     }
43553     self.value = error || result;
43554     doneFn(error, result);
43555   });
43556 };
43557
43558 /**
43559  * Configures the future to convert its final with a function fn(value)
43560  *
43561  * @param {function()} fn function(value) that returns the parsed value
43562  */
43563 angular.scenario.Future.prototype.parsedWith = function(fn) {
43564   this.parser = fn;
43565   return this;
43566 };
43567
43568 /**
43569  * Configures the future to parse its final value from JSON
43570  * into objects.
43571  */
43572 angular.scenario.Future.prototype.fromJson = function() {
43573   return this.parsedWith(angular.fromJson);
43574 };
43575
43576 /**
43577  * Configures the future to convert its final value from objects
43578  * into JSON.
43579  */
43580 angular.scenario.Future.prototype.toJson = function() {
43581   return this.parsedWith(angular.toJson);
43582 };
43583
43584 /**
43585  * Maintains an object tree from the runner events.
43586  *
43587  * @param {Object} runner The scenario Runner instance to connect to.
43588  *
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)
43592  *  silliness.
43593  *
43594  * TODO(vojta) refactor on, emit methods (from all objects) - use inheritance
43595  */
43596 angular.scenario.ObjectModel = function(runner) {
43597   var self = this;
43598
43599   this.specMap = {};
43600   this.listeners = [];
43601   this.value = {
43602     name: '',
43603     children: {}
43604   };
43605
43606   runner.on('SpecBegin', function(spec) {
43607     var block = self.value,
43608         definitions = [];
43609
43610     angular.forEach(self.getDefinitionPath(spec), function(def) {
43611       if (!block.children[def.name]) {
43612         block.children[def.name] = {
43613           id: def.id,
43614           name: def.name,
43615           children: {},
43616           specs: {}
43617         };
43618       }
43619       block = block.children[def.name];
43620       definitions.push(def.name);
43621     });
43622
43623     var it = self.specMap[spec.id] =
43624              block.specs[spec.name] =
43625              new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions);
43626
43627     // forward the event
43628     self.emit('SpecBegin', it);
43629   });
43630
43631   runner.on('SpecError', function(spec, error) {
43632     var it = self.getSpec(spec.id);
43633     it.status = 'error';
43634     it.error = error;
43635
43636     // forward the event
43637     self.emit('SpecError', it, error);
43638   });
43639
43640   runner.on('SpecEnd', function(spec) {
43641     var it = self.getSpec(spec.id);
43642     complete(it);
43643
43644     // forward the event
43645     self.emit('SpecEnd', it);
43646   });
43647
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);
43652
43653     // forward the event
43654     self.emit('StepBegin', it, step);
43655   });
43656
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.');
43662     }
43663     complete(step);
43664
43665     // forward the event
43666     self.emit('StepEnd', it, step);
43667   });
43668
43669   runner.on('StepFailure', function(spec, step, error) {
43670     var it = self.getSpec(spec.id),
43671         modelStep = it.getLastStep();
43672
43673     modelStep.setErrorStatus('failure', error, step.line());
43674     it.setStatusFromStep(modelStep);
43675
43676     // forward the event
43677     self.emit('StepFailure', it, modelStep, error);
43678   });
43679
43680   runner.on('StepError', function(spec, step, error) {
43681     var it = self.getSpec(spec.id),
43682         modelStep = it.getLastStep();
43683
43684     modelStep.setErrorStatus('error', error, step.line());
43685     it.setStatusFromStep(modelStep);
43686
43687     // forward the event
43688     self.emit('StepError', it, modelStep, error);
43689   });
43690
43691   runner.on('RunnerBegin', function() {
43692     self.emit('RunnerBegin');
43693   });
43694   runner.on('RunnerEnd', function() {
43695     self.emit('RunnerEnd');
43696   });
43697
43698   function complete(item) {
43699     item.endTime = Date.now();
43700     item.duration = item.endTime - item.startTime;
43701     item.status = item.status || 'success';
43702   }
43703 };
43704
43705 /**
43706  * Adds a listener for an event.
43707  *
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
43710  */
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);
43715 };
43716
43717 /**
43718  * Emits an event which notifies listeners and passes extra
43719  * arguments.
43720  *
43721  * @param {string} eventName Name of the event to fire.
43722  */
43723 angular.scenario.ObjectModel.prototype.emit = function(eventName) {
43724   var self = this,
43725       args = Array.prototype.slice.call(arguments, 1);
43726
43727   eventName = eventName.toLowerCase();
43728
43729   if (this.listeners[eventName]) {
43730     angular.forEach(this.listeners[eventName], function(listener) {
43731       listener.apply(self, args);
43732     });
43733   }
43734 };
43735
43736 /**
43737  * Computes the path of definition describe blocks that wrap around
43738  * this spec.
43739  *
43740  * @param spec Spec to compute the path for.
43741  * @return {Array<Describe>} The describe block path
43742  */
43743 angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) {
43744   var path = [];
43745   var currentDefinition = spec.definition;
43746   while (currentDefinition && currentDefinition.name) {
43747     path.unshift(currentDefinition);
43748     currentDefinition = currentDefinition.parent;
43749   }
43750   return path;
43751 };
43752
43753 /**
43754  * Gets a spec by id.
43755  *
43756  * @param {string} id The id of the spec to get the object for.
43757  * @return {Object} the Spec instance
43758  */
43759 angular.scenario.ObjectModel.prototype.getSpec = function(id) {
43760   return this.specMap[id];
43761 };
43762
43763 /**
43764  * A single it block.
43765  *
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
43769  */
43770 angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) {
43771   this.id = id;
43772   this.name = name;
43773   this.startTime = Date.now();
43774   this.steps = [];
43775   this.fullDefinitionName = (definitionNames || []).join(' ');
43776 };
43777
43778 /**
43779  * Adds a new step to the Spec.
43780  *
43781  * @param {string} name Name of the step (really name of the future)
43782  * @return {Object} the added step
43783  */
43784 angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) {
43785   var step = new angular.scenario.ObjectModel.Step(name);
43786   this.steps.push(step);
43787   return step;
43788 };
43789
43790 /**
43791  * Gets the most recent step.
43792  *
43793  * @return {Object} the step
43794  */
43795 angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() {
43796   return this.steps[this.steps.length - 1];
43797 };
43798
43799 /**
43800  * Set status of the Spec from given Step
43801  *
43802  * @param {angular.scenario.ObjectModel.Step} step
43803  */
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;
43809   }
43810 };
43811
43812 /**
43813  * A single step inside a Spec.
43814  *
43815  * @param {string} name Name of the step
43816  */
43817 angular.scenario.ObjectModel.Step = function(name) {
43818   this.name = name;
43819   this.startTime = Date.now();
43820 };
43821
43822 /**
43823  * Helper method for setting all error status related properties
43824  *
43825  * @param {string} status
43826  * @param {string} error
43827  * @param {string} line
43828  */
43829 angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) {
43830   this.status = status;
43831   this.error = error;
43832   this.line = line;
43833 };
43834
43835 /**
43836  * Runner for scenarios
43837  *
43838  * Has to be initialized before any test is loaded,
43839  * because it publishes the API into window (global space).
43840  */
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;
43846   this.api = {
43847     it: this.it,
43848     iit: this.iit,
43849     xit: angular.noop,
43850     describe: this.describe,
43851     ddescribe: this.ddescribe,
43852     xdescribe: angular.noop,
43853     beforeEach: this.beforeEach,
43854     afterEach: this.afterEach
43855   };
43856   angular.forEach(this.api, angular.bind(this, /** @this */ function(fn, key) {
43857     this.$window[key] = angular.bind(this, fn);
43858   }));
43859 };
43860
43861 /**
43862  * Emits an event which notifies listeners and passes extra
43863  * arguments.
43864  *
43865  * @param {string} eventName Name of the event to fire.
43866  */
43867 angular.scenario.Runner.prototype.emit = function(eventName) {
43868   var self = this;
43869   var args = Array.prototype.slice.call(arguments, 1);
43870   eventName = eventName.toLowerCase();
43871   if (!this.listeners[eventName]) {
43872     return;
43873   }
43874   angular.forEach(this.listeners[eventName], function(listener) {
43875     listener.apply(self, args);
43876   });
43877 };
43878
43879 /**
43880  * Adds a listener for an event.
43881  *
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()
43884  */
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);
43889 };
43890
43891 /**
43892  * Defines a describe block of a spec.
43893  *
43894  * @see Describe.js
43895  *
43896  * @param {string} name Name of the block
43897  * @param {function()} body Body of the block
43898  */
43899 angular.scenario.Runner.prototype.describe = function(name, body) {
43900   var self = this;
43901   this.currentDescribe.describe(name, /** @this */ function() {
43902     var parentDescribe = self.currentDescribe;
43903     self.currentDescribe = this;
43904     try {
43905       body.call(this);
43906     } finally {
43907       self.currentDescribe = parentDescribe;
43908     }
43909   });
43910 };
43911
43912 /**
43913  * Same as describe, but makes ddescribe the only blocks to run.
43914  *
43915  * @see Describe.js
43916  *
43917  * @param {string} name Name of the block
43918  * @param {function()} body Body of the block
43919  */
43920 angular.scenario.Runner.prototype.ddescribe = function(name, body) {
43921   var self = this;
43922   this.currentDescribe.ddescribe(name, /** @this */ function() {
43923     var parentDescribe = self.currentDescribe;
43924     self.currentDescribe = this;
43925     try {
43926       body.call(this);
43927     } finally {
43928       self.currentDescribe = parentDescribe;
43929     }
43930   });
43931 };
43932
43933 /**
43934  * Defines a test in a describe block of a spec.
43935  *
43936  * @see Describe.js
43937  *
43938  * @param {string} name Name of the block
43939  * @param {function()} body Body of the block
43940  */
43941 angular.scenario.Runner.prototype.it = function(name, body) {
43942   this.currentDescribe.it(name, body);
43943 };
43944
43945 /**
43946  * Same as it, but makes iit tests the only tests to run.
43947  *
43948  * @see Describe.js
43949  *
43950  * @param {string} name Name of the block
43951  * @param {function()} body Body of the block
43952  */
43953 angular.scenario.Runner.prototype.iit = function(name, body) {
43954   this.currentDescribe.iit(name, body);
43955 };
43956
43957 /**
43958  * Defines a function to be called before each it block in the describe
43959  * (and before all nested describes).
43960  *
43961  * @see Describe.js
43962  *
43963  * @param {function()} Callback to execute
43964  */
43965 angular.scenario.Runner.prototype.beforeEach = function(body) {
43966   this.currentDescribe.beforeEach(body);
43967 };
43968
43969 /**
43970  * Defines a function to be called after each it block in the describe
43971  * (and before all nested describes).
43972  *
43973  * @see Describe.js
43974  *
43975  * @param {function()} Callback to execute
43976  */
43977 angular.scenario.Runner.prototype.afterEach = function(body) {
43978   this.currentDescribe.afterEach(body);
43979 };
43980
43981 /**
43982  * Creates a new spec runner.
43983  *
43984  * @private
43985  * @param {Object} scope parent scope
43986  */
43987 angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) {
43988   var child = scope.$new();
43989   var Cls = angular.scenario.SpecRunner;
43990
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]);
43995   }
43996
43997   Cls.call(child);
43998   return child;
43999 };
44000
44001 /**
44002  * Runs all the loaded tests with the specified runner class on the
44003  * provided application.
44004  *
44005  * @param {angular.scenario.Application} application App to remote control.
44006  */
44007 angular.scenario.Runner.prototype.run = function(application) {
44008   var self = this;
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);
44013   });
44014   $root.application = application;
44015   $root.emit('RunnerBegin');
44016   asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) {
44017     var dslCache = {};
44018     var runner = self.createSpecRunner_($root);
44019     angular.forEach(angular.scenario.dsl, function(fn, key) {
44020       dslCache[key] = fn.call($root);
44021     });
44022     angular.forEach(angular.scenario.dsl, function(fn, key) {
44023       self.$window[key] = function() {
44024         var line = callerFile(3);
44025         var scope = runner.$new();
44026
44027         // Make the dsl accessible on the current chain
44028         scope.dsl = {};
44029         angular.forEach(dslCache, function(fn, key) {
44030           scope.dsl[key] = function() {
44031             return dslCache[key].apply(scope, arguments);
44032           };
44033         });
44034
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);
44040         };
44041         scope.addFutureAction = function() {
44042           Array.prototype.push.call(arguments, line);
44043           return angular.scenario.SpecRunner.
44044             prototype.addFutureAction.apply(scope, arguments);
44045         };
44046
44047         return scope.dsl[key].apply(scope, arguments);
44048       };
44049     });
44050     runner.run(spec, /** @this */ function() {
44051       runner.$destroy();
44052       specDone.apply(this, arguments);
44053     });
44054   },
44055   function(error) {
44056     if (error) {
44057       self.emit('RunnerError', error);
44058     }
44059     self.emit('RunnerEnd');
44060   });
44061 };
44062
44063 /**
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)
44070  */
44071 angular.scenario.SpecRunner = function() {
44072   this.futures = [];
44073   this.afterIndex = 0;
44074 };
44075
44076 /**
44077  * Executes a spec which is an it block with associated before/after functions
44078  * based on the describe nesting.
44079  *
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)`
44083  */
44084 angular.scenario.SpecRunner.prototype.run = function(spec, specDone) {
44085   var self = this;
44086   this.spec = spec;
44087
44088   this.emit('SpecBegin', spec);
44089
44090   try {
44091     spec.before.call(this);
44092     spec.body.call(this);
44093     this.afterIndex = this.futures.length;
44094     spec.after.call(this);
44095   } catch (e) {
44096     this.emit('SpecError', spec, e);
44097     this.emit('SpecEnd', spec);
44098     specDone();
44099     return;
44100   }
44101
44102   var handleError = function(error, done) {
44103     if (self.error) {
44104       return done();
44105     }
44106     self.error = true;
44107     done(null, self.afterIndex);
44108   };
44109
44110   asyncForEach(
44111     this.futures,
44112     function(future, futureDone) {
44113       self.step = future;
44114       self.emit('StepBegin', spec, future);
44115       try {
44116         future.execute(function(error) {
44117           if (error) {
44118             self.emit('StepFailure', spec, future, error);
44119             self.emit('StepEnd', spec, future);
44120             return handleError(error, futureDone);
44121           }
44122           self.emit('StepEnd', spec, future);
44123           self.$window.setTimeout(function() { futureDone(); }, 0);
44124         });
44125       } catch (e) {
44126         self.emit('StepError', spec, future, e);
44127         self.emit('StepEnd', spec, future);
44128         handleError(e, futureDone);
44129       }
44130     },
44131     function(e) {
44132       if (e) {
44133         self.emit('SpecError', spec, e);
44134       }
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);
44139     }
44140   );
44141 };
44142
44143 /**
44144  * Adds a new future action.
44145  *
44146  * Note: Do not pass line manually. It happens automatically.
44147  *
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
44151  */
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);
44155   return future;
44156 };
44157
44158 /**
44159  * Adds a new future action to be executed on the application window.
44160  *
44161  * Note: Do not pass line manually. It happens automatically.
44162  *
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
44166  */
44167 angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) {
44168   var self = this;
44169   var NG = /\[ng\\:/;
44170   return this.addFuture(name, /** @this */ function(done) {
44171     this.application.executeAction(function($window, $document) {
44172
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);
44180         });
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);
44185           });
44186         }
44187         if (!result.length) {
44188           // eslint-disable-next-line no-throw-literal
44189           throw {
44190             type: 'selector',
44191             message: 'Selector ' + selector + ' did not match any elements.'
44192           };
44193         }
44194
44195         return result;
44196       };
44197
44198       try {
44199         behavior.call(self, $window, $document, done);
44200       } catch (e) {
44201         if (e.type && e.type === 'selector') {
44202           done(e.message);
44203         } else {
44204           throw e;
44205         }
44206       }
44207     });
44208   }, line);
44209 };
44210
44211 /* eslint-disable no-invalid-this */
44212
44213 /**
44214  * Shared DSL statements that are useful to all scenarios.
44215  */
44216
44217  /**
44218  * Usage:
44219  *    pause() pauses until you call resume() in the console
44220  */
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(); };
44226     });
44227   };
44228 });
44229
44230 /**
44231  * Usage:
44232  *    sleep(seconds) pauses the test for specified number of seconds
44233  */
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);
44238     });
44239   };
44240 });
44241
44242 /**
44243  * Usage:
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
44255  */
44256 angular.scenario.dsl('browser', function() {
44257   var chain = {};
44258
44259   chain.navigateTo = function(url, delegate) {
44260     var application = this.application;
44261     return this.addFuture('browser navigate to \'' + url + '\'', function(done) {
44262       if (delegate) {
44263         url = delegate.call(this, url);
44264       }
44265       application.navigateTo(url, function() {
44266         done(null, url);
44267       }, done);
44268     });
44269   };
44270
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() {
44276         done(null, href);
44277       }, done);
44278     });
44279   };
44280
44281   chain.window = function() {
44282     var api = {};
44283
44284     api.href = function() {
44285       return this.addFutureAction('window.location.href', function($window, $document, done) {
44286         done(null, $window.location.href);
44287       });
44288     };
44289
44290     api.path = function() {
44291       return this.addFutureAction('window.location.path', function($window, $document, done) {
44292         done(null, $window.location.pathname);
44293       });
44294     };
44295
44296     api.search = function() {
44297       return this.addFutureAction('window.location.search', function($window, $document, done) {
44298         done(null, $window.location.search);
44299       });
44300     };
44301
44302     api.hash = function() {
44303       return this.addFutureAction('window.location.hash', function($window, $document, done) {
44304         done(null, $window.location.hash.replace('#', ''));
44305       });
44306     };
44307
44308     return api;
44309   };
44310
44311   chain.location = function() {
44312     var api = {};
44313
44314     api.url = function() {
44315       return this.addFutureAction('$location.url()', function($window, $document, done) {
44316         done(null, $document.injector().get('$location').url());
44317       });
44318     };
44319
44320     api.path = function() {
44321       return this.addFutureAction('$location.path()', function($window, $document, done) {
44322         done(null, $document.injector().get('$location').path());
44323       });
44324     };
44325
44326     api.search = function() {
44327       return this.addFutureAction('$location.search()', function($window, $document, done) {
44328         done(null, $document.injector().get('$location').search());
44329       });
44330     };
44331
44332     api.hash = function() {
44333       return this.addFutureAction('$location.hash()', function($window, $document, done) {
44334         done(null, $document.injector().get('$location').hash());
44335       });
44336     };
44337
44338     return api;
44339   };
44340
44341   return function() {
44342     return chain;
44343   };
44344 });
44345
44346 /**
44347  * Usage:
44348  *    expect(future).{matcher} where matcher is one of the matchers defined
44349  *    with angular.scenario.matcher
44350  *
44351  * ex. expect(binding("name")).toEqual("Elliott")
44352  */
44353 angular.scenario.dsl('expect', function() {
44354   var chain = angular.extend({}, angular.scenario.matcher);
44355
44356   chain.not = function() {
44357     this.inverse = true;
44358     return chain;
44359   };
44360
44361   return function(future) {
44362     this.future = future;
44363     return chain;
44364   };
44365 });
44366
44367 /**
44368  * Usage:
44369  *    using(selector, label) scopes the next DSL element selection
44370  *
44371  * ex.
44372  *   using('#foo', "'Foo' text field").input('bar')
44373  */
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 + ' )';
44379     } else {
44380       this.label = this.selector;
44381     }
44382     return this.dsl;
44383   };
44384 });
44385
44386 /**
44387  * Usage:
44388  *    binding(name) returns the value of the first matching binding
44389  */
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.');
44397         }
44398         done(null, values[0]);
44399     });
44400   };
44401 });
44402
44403 /**
44404  * Usage:
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.
44409  */
44410 angular.scenario.dsl('input', function() {
44411   var chain = {};
44412   var supportInputEvent = 'oninput' in window.document.createElement('div') && !msie;
44413
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');
44418         input.val(value);
44419         input.trigger(event || (supportInputEvent ? 'input' : 'change'));
44420         done();
44421     });
44422   };
44423
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');
44429         done();
44430     });
44431   };
44432
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');
44439         done();
44440     });
44441   };
44442
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());
44447     });
44448   };
44449
44450   return function(name) {
44451     this.name = name;
44452     return chain;
44453   };
44454 });
44455
44456
44457 /**
44458  * Usage:
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
44462  *    in an array
44463  */
44464 angular.scenario.dsl('repeater', function() {
44465   var chain = {};
44466
44467   chain.count = function() {
44468     return this.addFutureAction('repeater \'' + this.label + '\' count',
44469       function($window, $document, done) {
44470         try {
44471           done(null, $document.elements().length);
44472         } catch (e) {
44473           done(null, 0);
44474         }
44475     });
44476   };
44477
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));
44482     });
44483   };
44484
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');
44491         }
44492         done(null, matches.bindings($window.angular.element));
44493     });
44494   };
44495
44496   return function(selector, label) {
44497     this.dsl.using(selector, label);
44498     return chain;
44499   };
44500 });
44501
44502 /**
44503  * Usage:
44504  *    select(name).option('value') select one option
44505  *    select(name).options('value1', 'value2', ...) select options from a multi select
44506  */
44507 angular.scenario.dsl('select', function() {
44508   var chain = {};
44509
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) {
44516           select.val(value);
44517         } else {
44518           option = select.find('option').filter(function() {
44519             return _jQuery(this).text() === value;
44520           });
44521           if (!option.length) {
44522             option = select.find('option:contains("' + value + '")');
44523           }
44524           if (option.length) {
44525             select.val(option.val());
44526           } else {
44527               return done('option \'' + value + '\' not found');
44528           }
44529         }
44530         select.trigger('change');
44531         done();
44532     });
44533   };
44534
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');
44542         done();
44543     });
44544   };
44545
44546   return function(name) {
44547     this.name = name;
44548     return chain;
44549   };
44550 });
44551
44552 /**
44553  * Usage:
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)
44564  */
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'
44570   ];
44571   var chain = {};
44572
44573   chain.count = function() {
44574     return this.addFutureAction('element \'' + this.label + '\' count',
44575       function($window, $document, done) {
44576         try {
44577           done(null, $document.elements().length);
44578         } catch (e) {
44579           done(null, 0);
44580         }
44581     });
44582   };
44583
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];
44590
44591         if (href && elements[0].nodeName.toLowerCase() === 'a' && eventProcessDefault) {
44592           this.application.navigateTo(href, function() {
44593             done();
44594           }, done);
44595         } else {
44596           done();
44597         }
44598     });
44599   };
44600
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];
44607
44608         if (href && elements[0].nodeName.toLowerCase() === 'a' && eventProcessDefault) {
44609           this.application.navigateTo(href, function() {
44610             done();
44611           }, done);
44612         } else {
44613           done();
44614         }
44615     });
44616   };
44617
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');
44623         done();
44624     });
44625   };
44626
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');
44632           done();
44633       });
44634     };
44635
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');
44641           done();
44642       });
44643     };
44644
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);
44649     });
44650   };
44651
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 \'' +
44658                 value + '\'';
44659
44660       return this.addFutureAction(futureName, function($window, $document, done) {
44661         var element = $document.elements();
44662         done(null, element[methodName].apply(element, args));
44663       });
44664     };
44665   });
44666
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 + '\'';
44673
44674       return this.addFutureAction(futureName, function($window, $document, done) {
44675         var element = $document.elements();
44676         done(null, element[methodName].apply(element, args));
44677       });
44678     };
44679   });
44680
44681   return function(selector, label) {
44682     this.dsl.using(selector, label);
44683     return chain;
44684   };
44685 });
44686
44687 /**
44688  * Matchers for implementing specs. Follows the Jasmine spec conventions.
44689  */
44690
44691 angular.scenario.matcher('toEqual', /** @this */ function(expected) {
44692   return angular.equals(this.actual, expected);
44693 });
44694
44695 angular.scenario.matcher('toBe', /** @this */ function(expected) {
44696   return this.actual === expected;
44697 });
44698
44699 angular.scenario.matcher('toBeDefined', /** @this */ function() {
44700   return angular.isDefined(this.actual);
44701 });
44702
44703 angular.scenario.matcher('toBeTruthy', /** @this */ function() {
44704   return this.actual;
44705 });
44706
44707 angular.scenario.matcher('toBeFalsy', /** @this */ function() {
44708   return !this.actual;
44709 });
44710
44711 angular.scenario.matcher('toMatch', /** @this */ function(expected) {
44712   return new RegExp(expected).test(this.actual);
44713 });
44714
44715 angular.scenario.matcher('toBeNull', /** @this */ function() {
44716   return this.actual === null;
44717 });
44718
44719 angular.scenario.matcher('toContain', /** @this */ function(expected) {
44720   return includes(this.actual, expected);
44721 });
44722
44723 angular.scenario.matcher('toBeLessThan', /** @this */ function(expected) {
44724   return this.actual < expected;
44725 });
44726
44727 angular.scenario.matcher('toBeGreaterThan', /** @this */ function(expected) {
44728   return this.actual > expected;
44729 });
44730
44731 /**
44732  * User Interface for the Scenario Runner.
44733  *
44734  * TODO(esprehn): This should be refactored now that ObjectModel exists
44735  *  to use angular bindings for the UI.
44736  */
44737 angular.scenario.output('html', function(context, runner, model) {
44738   var specUiMap = {},
44739       lastStepUiMap = {};
44740
44741   context.append(
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>' +
44748     '  </ul>' +
44749     '</div>' +
44750     '<div id="specs">' +
44751     '  <div class="test-children"></div>' +
44752     '</div>'
44753   );
44754
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.');
44759   });
44760
44761   runner.on('SpecBegin', function(spec) {
44762     var ui = findContext(spec);
44763     ui.find('> .tests').append(
44764       '<li class="status-pending test-it"></li>'
44765     );
44766     ui = ui.find('> .tests li:last');
44767     ui.append(
44768       '<div class="test-info">' +
44769       '  <p class="test-title">' +
44770       '    <span class="timer-result"></span>' +
44771       '    <span class="test-name"></span>' +
44772       '  </p>' +
44773       '</div>' +
44774       '<div class="scrollpane">' +
44775       '  <ol class="test-actions"></ol>' +
44776       '</div>'
44777     );
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) {
44784         actions.hide();
44785         name.removeClass('open').addClass('closed');
44786       } else {
44787         actions.show();
44788         scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
44789         name.removeClass('closed').addClass('open');
44790       }
44791     });
44792
44793     specUiMap[spec.id] = ui;
44794   });
44795
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));
44800   });
44801
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();
44811     }
44812     updateTotals(spec.status);
44813   });
44814
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');
44821     stepUi.append(
44822       '<div class="timer-result"></div>' +
44823       '<div class="test-title"></div>'
44824     );
44825     stepUi.find('> .test-title').text(step.name);
44826     var scrollpane = stepUi.parents('.scrollpane');
44827     scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
44828   });
44829
44830   runner.on('StepFailure', function(spec, step, error) {
44831     var ui = lastStepUiMap[spec.id];
44832     addError(ui, step.line, error);
44833   });
44834
44835   runner.on('StepError', function(spec, step, error) {
44836     var ui = lastStepUiMap[spec.id];
44837     addError(ui, step.line, error);
44838   });
44839
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'));
44849   });
44850
44851   /**
44852    * Finds the context of a spec block defined by the passed definition.
44853    *
44854    * @param {Object} The definition created by the Describe object.
44855    */
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 + '">' +
44863           '  <h2></h2>' +
44864           '  <div class="test-children"></div>' +
44865           '  <ul class="tests"></ul>' +
44866           '</div>'
44867         );
44868         context.find('#' + id).find('> h2').text('describe: ' + defn.name);
44869       }
44870       currentContext = context.find('#' + id);
44871     });
44872     return context.find('#describe-' + spec.definition.id);
44873   }
44874
44875   /**
44876    * Updates the test counter for the status.
44877    *
44878    * @param {string} the status.
44879    */
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]);
44885   }
44886
44887   /**
44888    * Add an error to a step.
44889    *
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.
44893    */
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);
44898   }
44899 });
44900
44901 /**
44902  * Generates JSON output into a context.
44903  */
44904 angular.scenario.output('json', function(context, runner, model) {
44905   model.on('RunnerEnd', function() {
44906     context.text(angular.toJson(model.value));
44907   });
44908 });
44909
44910 /**
44911  * Generates XML output into a context.
44912  */
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);
44917   };
44918   model.on('RunnerEnd', function() {
44919     var scenario = $('<scenario></scenario>');
44920     context.append(scenario);
44921     serializeXml(scenario, model.value);
44922   });
44923
44924   /**
44925    * Convert the tree into XML.
44926    *
44927    * @param {Object} context jQuery context to add the XML to.
44928    * @param {Object} tree node to serialize
44929    */
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);
44937      });
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);
44946        its.append(it);
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);
44953          if (step.error) {
44954            var error = $('<error></error>');
44955            stepContext.append(error);
44956            error.text(formatException(step.error));
44957          }
44958        });
44959      });
44960    }
44961 });
44962
44963 /**
44964  * Creates a global value $result with the result of the runner.
44965  */
44966 angular.scenario.output('object', function(context, runner, model) {
44967   runner.$window.$result = model.value;
44968 });
44969
44970 bindJQuery();
44971 publishExternalAPI(angular);
44972
44973 var $runner = new angular.scenario.Runner(window),
44974     scripts = window.document.getElementsByTagName('script'),
44975     script = scripts[scripts.length - 1],
44976     config = {};
44977
44978 angular.forEach(script.attributes, function(attr) {
44979   var match = attr.name.match(/ng[:\-](.*)/);
44980   if (match) {
44981     config[match[1]] = attr.value || true;
44982   }
44983 });
44984
44985 if (config.autotest) {
44986   JQLite(window.document).ready(function() {
44987     angular.scenario.setUpAndRun(config);
44988   });
44989 }
44990 })(window);
44991
44992
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>');